blob: 387af17357c528fa9a5db816ee66ba8cc95c1e9e [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Makoto Onukif76b06a2015-09-22 15:03:44 -070018import android.Manifest.permission;
19import android.app.Activity;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070020import android.app.admin.DeviceAdminReceiver;
21import android.app.admin.DevicePolicyManager;
22import android.app.admin.DevicePolicyManagerInternal;
Makoto Onukif76b06a2015-09-22 15:03:44 -070023import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070024import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000025import android.content.Context;
26import android.content.Intent;
27import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000028import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070030import android.content.pm.PackageManager;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010031import android.content.res.Resources;
32import android.graphics.Color;
33import android.net.IIpConnectivityMetrics;
Tony Mak2f26b792016-11-28 17:54:51 +000034import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080035import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080036import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070037import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000038import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080039import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070040import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070041import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080042import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000043import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080044import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000045import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010046import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070047import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070048
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010049import com.android.internal.R;
Alan Treadwayafad8782016-01-19 15:15:08 +000050import com.android.server.LocalServices;
51import com.android.server.SystemService;
52
Makoto Onukib643fb02015-09-22 15:03:44 -070053import org.mockito.invocation.InvocationOnMock;
54import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070055
Makoto Onukic8a5a552015-11-19 14:29:12 -080056import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000057import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000058import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070059import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070060import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070061import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010062import java.util.Set;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070063
64import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070065import static org.mockito.Matchers.anyInt;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010066import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070067import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070068import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070069import static org.mockito.Matchers.isNull;
Makoto Onukib643fb02015-09-22 15:03:44 -070070import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070071import static org.mockito.Mockito.doReturn;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080072import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070073import static org.mockito.Mockito.times;
74import static org.mockito.Mockito.verify;
75import static org.mockito.Mockito.when;
76
77/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070078 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070079 *
80 m FrameworksServicesTests &&
81 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000082 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070083 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080084 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070085
86 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
87 */
Benjamin Franz6d009032016-01-25 18:56:38 +000088@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070089public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000090 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
91 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
92 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
93
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070094 private DpmMockContext mContext;
95 public DevicePolicyManager dpm;
96 public DevicePolicyManagerServiceTestable dpms;
97
98 @Override
99 protected void setUp() throws Exception {
100 super.setUp();
101
102 mContext = getContext();
103
104 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
105 .thenReturn(true);
106
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800107 // By default, pretend all users are running and unlocked.
108 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
109
Makoto Onukia52562c2015-10-01 16:12:31 -0700110 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700111
Makoto Onukid932f762015-09-29 16:53:38 -0700112 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
113 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
114 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800115 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700116
Makoto Onukib643fb02015-09-22 15:03:44 -0700117 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700118 }
119
Makoto Onukia52562c2015-10-01 16:12:31 -0700120 private void initializeDpms() {
121 // Need clearCallingIdentity() to pass permission checks.
122 final long ident = mContext.binder.clearCallingIdentity();
123 try {
124 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
125
126 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
127
128 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
129 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
130
131 dpm = new DevicePolicyManagerTestable(mContext, dpms);
132 } finally {
133 mContext.binder.restoreCallingIdentity(ident);
134 }
135 }
136
Makoto Onukib643fb02015-09-22 15:03:44 -0700137 private void setUpUserManager() {
138 // Emulate UserManager.set/getApplicationRestriction().
139 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
140
141 // UM.setApplicationRestrictions() will save to appRestrictions.
142 doAnswer(new Answer<Void>() {
143 @Override
144 public Void answer(InvocationOnMock invocation) throws Throwable {
145 String pkg = (String) invocation.getArguments()[0];
146 Bundle bundle = (Bundle) invocation.getArguments()[1];
147 UserHandle user = (UserHandle) invocation.getArguments()[2];
148
149 appRestrictions.put(Pair.create(pkg, user), bundle);
150
151 return null;
152 }
153 }).when(mContext.userManager).setApplicationRestrictions(
154 anyString(), any(Bundle.class), any(UserHandle.class));
155
156 // UM.getApplicationRestrictions() will read from appRestrictions.
157 doAnswer(new Answer<Bundle>() {
158 @Override
159 public Bundle answer(InvocationOnMock invocation) throws Throwable {
160 String pkg = (String) invocation.getArguments()[0];
161 UserHandle user = (UserHandle) invocation.getArguments()[1];
162
163 return appRestrictions.get(Pair.create(pkg, user));
164 }
165 }).when(mContext.userManager).getApplicationRestrictions(
166 anyString(), any(UserHandle.class));
167
Makoto Onukid932f762015-09-29 16:53:38 -0700168 // Add the first secondary user.
169 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700170 }
171
172 private void setAsProfileOwner(ComponentName admin) {
173 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
174 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
175
Makoto Onukia4f11972015-10-01 13:19:58 -0700176 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700177 dpm.setActiveAdmin(admin, /* replace =*/ false);
178
179 // Fire!
180 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
181
182 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700183 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700184 }
185
186 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700187 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
188 .thenReturn(false);
189
190 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
191 new DevicePolicyManagerServiceTestable(mContext, dataDir);
192
193 // If the device has no DPMS feature, it shouldn't register the local service.
194 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
195 }
196
197 /**
198 * Caller doesn't have proper permissions.
199 */
200 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700201 // 1. Failure cases.
202
203 // Caller doesn't have MANAGE_DEVICE_ADMINS.
204 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700205 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700206 fail("Didn't throw SecurityException");
207 } catch (SecurityException expected) {
208 }
209
210 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
211 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
212 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700213 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700214 fail("Didn't throw SecurityException");
215 } catch (SecurityException expected) {
216 }
217 }
218
Makoto Onukif76b06a2015-09-22 15:03:44 -0700219 /**
220 * Test for:
221 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800222 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700223 * {@link DevicePolicyManager#isAdminActive}
224 * {@link DevicePolicyManager#isAdminActiveAsUser}
225 * {@link DevicePolicyManager#getActiveAdmins}
226 * {@link DevicePolicyManager#getActiveAdminsAsUser}
227 */
228 public void testSetActiveAdmin() throws Exception {
229 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700230 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
231
Makoto Onukif76b06a2015-09-22 15:03:44 -0700232 // 2. Call the API.
233 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700234
235 // 3. Verify internal calls.
236
237 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700238 verify(mContext.spiedContext).sendBroadcastAsUser(
239 MockUtils.checkIntentAction(
240 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
241 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
242 verify(mContext.spiedContext).sendBroadcastAsUser(
243 MockUtils.checkIntentAction(
244 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700245 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
246
Makoto Onukif76b06a2015-09-22 15:03:44 -0700247 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
248 eq(admin1.getPackageName()),
249 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
250 eq(PackageManager.DONT_KILL_APP),
251 eq(DpmMockContext.CALLER_USER_HANDLE),
252 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700253
254 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700255
256 // Make sure it's active admin1.
257 assertTrue(dpm.isAdminActive(admin1));
258 assertFalse(dpm.isAdminActive(admin2));
259 assertFalse(dpm.isAdminActive(admin3));
260
261 // But not admin1 for a different user.
262
263 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
264 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
265 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
266
267 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
268 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
269
270 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
271
272 // Next, add one more admin.
273 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700274 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
275 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700276
277 dpm.setActiveAdmin(admin2, /* replace =*/ false);
278
279 // Now we have two admins.
280 assertTrue(dpm.isAdminActive(admin1));
281 assertTrue(dpm.isAdminActive(admin2));
282 assertFalse(dpm.isAdminActive(admin3));
283
284 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
285 // again. (times(1) because it was previously called for admin1)
286 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
287 eq(admin1.getPackageName()),
288 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
289 eq(PackageManager.DONT_KILL_APP),
290 eq(DpmMockContext.CALLER_USER_HANDLE),
291 anyString());
292
293 // 4. Add the same admin1 again without replace, which should throw.
294 try {
295 dpm.setActiveAdmin(admin1, /* replace =*/ false);
296 fail("Didn't throw");
297 } catch (IllegalArgumentException expected) {
298 }
299
300 // 5. Add the same admin1 again with replace, which should succeed.
301 dpm.setActiveAdmin(admin1, /* replace =*/ true);
302
303 // TODO make sure it's replaced.
304
305 // 6. Test getActiveAdmins()
306 List<ComponentName> admins = dpm.getActiveAdmins();
307 assertEquals(2, admins.size());
308 assertEquals(admin1, admins.get(0));
309 assertEquals(admin2, admins.get(1));
310
311 // Another user has no admins.
312 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
313
314 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
315 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
316
317 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
318 }
319
Makoto Onukid932f762015-09-29 16:53:38 -0700320 public void testSetActiveAdmin_multiUsers() throws Exception {
321
322 final int ANOTHER_USER_ID = 100;
323 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
324
325 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
326
327 // Set up pacakge manager for the other user.
328 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700329
330 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
331
332 dpm.setActiveAdmin(admin1, /* replace =*/ false);
333
334 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
335 dpm.setActiveAdmin(admin2, /* replace =*/ false);
336
337
338 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
339 assertTrue(dpm.isAdminActive(admin1));
340 assertFalse(dpm.isAdminActive(admin2));
341
342 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
343 assertFalse(dpm.isAdminActive(admin1));
344 assertTrue(dpm.isAdminActive(admin2));
345 }
346
Makoto Onukif76b06a2015-09-22 15:03:44 -0700347 /**
348 * Test for:
349 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800350 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700351 */
352 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
353 // 1. Make sure the caller has proper permissions.
354 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
355
356 dpm.setActiveAdmin(admin1, /* replace =*/ false);
357 assertTrue(dpm.isAdminActive(admin1));
358
359 // Add the same admin1 again without replace, which should throw.
360 try {
361 dpm.setActiveAdmin(admin1, /* replace =*/ false);
362 fail("Didn't throw");
363 } catch (IllegalArgumentException expected) {
364 }
365 }
366
367 /**
368 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800369 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
370 * BIND_DEVICE_ADMIN.
371 */
372 public void testSetActiveAdmin_permissionCheck() throws Exception {
373 // 1. Make sure the caller has proper permissions.
374 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
375
376 try {
377 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
378 fail();
379 } catch (IllegalArgumentException expected) {
380 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
381 }
382 assertFalse(dpm.isAdminActive(adminNoPerm));
383
384 // Change the target API level to MNC. Now it can be set as DA.
385 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
386 VERSION_CODES.M);
387 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
388 assertTrue(dpm.isAdminActive(adminNoPerm));
389
390 // TODO Test the "load from the file" case where DA will still be loaded even without
391 // BIND_DEVICE_ADMIN and target API is N.
392 }
393
394 /**
395 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700396 * {@link DevicePolicyManager#removeActiveAdmin}
397 */
398 public void testRemoveActiveAdmin_SecurityException() {
399 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
400
401 // Add admin.
402
403 dpm.setActiveAdmin(admin1, /* replace =*/ false);
404
405 assertTrue(dpm.isAdminActive(admin1));
406
407 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
408
409 // Directly call the DPMS method with a different userid, which should fail.
410 try {
411 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
412 fail("Didn't throw SecurityException");
413 } catch (SecurityException expected) {
414 }
415
416 // Try to remove active admin with a different caller userid should fail too, without
417 // having MANAGE_DEVICE_ADMINS.
418 mContext.callerPermissions.clear();
419
Makoto Onukid932f762015-09-29 16:53:38 -0700420 // Change the caller, and call into DPMS directly with a different user-id.
421
Makoto Onukif76b06a2015-09-22 15:03:44 -0700422 mContext.binder.callingUid = 1234567;
423 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700424 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700425 fail("Didn't throw SecurityException");
426 } catch (SecurityException expected) {
427 }
428 }
429
430 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800431 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
432 * (because we can't send the remove broadcast).
433 */
434 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
435 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
436
437 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
438
439 // Add admin.
440
441 dpm.setActiveAdmin(admin1, /* replace =*/ false);
442
443 assertTrue(dpm.isAdminActive(admin1));
444
445 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
446
447 // 1. User not unlocked.
448 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
449 .thenReturn(false);
450 try {
451 dpm.removeActiveAdmin(admin1);
452 fail("Didn't throw IllegalStateException");
453 } catch (IllegalStateException expected) {
454 MoreAsserts.assertContainsRegex(
455 "User must be running and unlocked", expected.getMessage());
456 }
457
458 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
459
460 // 2. User unlocked.
461 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
462 .thenReturn(true);
463
464 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700465 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800466 }
467
468 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700469 * Test for:
470 * {@link DevicePolicyManager#removeActiveAdmin}
471 */
Makoto Onukid932f762015-09-29 16:53:38 -0700472 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700473 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
474
475 // Add admin1.
476
477 dpm.setActiveAdmin(admin1, /* replace =*/ false);
478
479 assertTrue(dpm.isAdminActive(admin1));
480 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
481
482 // Different user, but should work, because caller has proper permissions.
483 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700484
485 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700486 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700487
488 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700489 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700490
491 // TODO DO Still can't be removed in this case.
492 }
493
494 /**
495 * Test for:
496 * {@link DevicePolicyManager#removeActiveAdmin}
497 */
498 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
499 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
500 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
501
502 // Add admin1.
503
504 dpm.setActiveAdmin(admin1, /* replace =*/ false);
505
506 assertTrue(dpm.isAdminActive(admin1));
507 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
508
509 // Broadcast from saveSettingsLocked().
510 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
511 MockUtils.checkIntentAction(
512 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
513 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
514
515 // Remove. No permissions, but same user, so it'll work.
516 mContext.callerPermissions.clear();
517 dpm.removeActiveAdmin(admin1);
518
Makoto Onukif76b06a2015-09-22 15:03:44 -0700519 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
520 MockUtils.checkIntentAction(
521 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
522 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
523 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700524 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700525 eq(dpms.mHandler),
526 eq(Activity.RESULT_OK),
527 isNull(String.class),
528 isNull(Bundle.class));
529
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700530 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700531
532 // Again broadcast from saveSettingsLocked().
533 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
534 MockUtils.checkIntentAction(
535 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
536 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
537
538 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700539 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700540
541 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000542 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700543 */
544 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000545 setDeviceOwner();
546
547 // Try to set a profile owner on the same user, which should fail.
548 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
549 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
550 try {
551 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
552 fail("IllegalStateException not thrown");
553 } catch (IllegalStateException expected) {
554 assertTrue("Message was: " + expected.getMessage(),
555 expected.getMessage().contains("already has a device owner"));
556 }
557
558 // DO admin can't be deactivated.
559 dpm.removeActiveAdmin(admin1);
560 assertTrue(dpm.isAdminActive(admin1));
561
562 // TODO Test getDeviceOwnerName() too. To do so, we need to change
563 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
564 }
565
566 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700567 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800568 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700569 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
570 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
571
Makoto Onukid932f762015-09-29 16:53:38 -0700572 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700573 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
574
Makoto Onukid932f762015-09-29 16:53:38 -0700575 // Make sure admin1 is installed on system user.
576 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700577
Makoto Onukic8a5a552015-11-19 14:29:12 -0800578 // Check various get APIs.
579 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
580
Makoto Onukib643fb02015-09-22 15:03:44 -0700581 // DO needs to be an DA.
582 dpm.setActiveAdmin(admin1, /* replace =*/ false);
583
584 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700585 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700586
Makoto Onukic8a5a552015-11-19 14:29:12 -0800587 // getDeviceOwnerComponent should return the admin1 component.
588 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
589 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
590
591 // Check various get APIs.
592 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
593
594 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
595 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
596 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
597 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
598
599 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
600
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000601 // Verify internal calls.
602 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
603 eq(admin1.getPackageName()));
604
Makoto Onukib643fb02015-09-22 15:03:44 -0700605 // TODO We should check if the caller has called clearCallerIdentity().
606 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
607 eq(UserHandle.USER_SYSTEM), eq(false));
608
609 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
610 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
611 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
612
Makoto Onukic8a5a552015-11-19 14:29:12 -0800613 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700614 }
615
Makoto Onukic8a5a552015-11-19 14:29:12 -0800616 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
617 final int origCallingUser = mContext.binder.callingUid;
618 final List origPermissions = new ArrayList(mContext.callerPermissions);
619 mContext.callerPermissions.clear();
620
621 mContext.callerPermissions.add(permission.MANAGE_USERS);
622
623 mContext.binder.callingUid = Process.SYSTEM_UID;
624
625 // TODO Test getDeviceOwnerName() too. To do so, we need to change
626 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
627 if (hasDeviceOwner) {
628 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
629 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
630 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
631
632 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
633 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
634 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
635 } else {
636 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
637 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
638 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
639
640 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
641 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
642 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
643 }
644
645 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
646 if (hasDeviceOwner) {
647 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
648 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
649 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
650
651 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
652 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
653 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
654 } else {
655 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
656 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
657 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
658
659 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
660 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
661 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
662 }
663
664 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
665 // Still with MANAGE_USERS.
666 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
667 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
668 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
669
670 if (hasDeviceOwner) {
671 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
672 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
673 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
674 } else {
675 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
676 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
677 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
678 }
679
680 mContext.binder.callingUid = Process.SYSTEM_UID;
681 mContext.callerPermissions.remove(permission.MANAGE_USERS);
682 // System can still call "OnAnyUser" without MANAGE_USERS.
683 if (hasDeviceOwner) {
684 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
685 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
686 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
687
688 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
689 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
690 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
691 } else {
692 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
693 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
694 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
695
696 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
697 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
698 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
699 }
700
701 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
702 // Still no MANAGE_USERS.
703 if (hasDeviceOwner) {
704 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
705 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
706 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
707 } else {
708 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
709 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
710 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
711 }
712
713 try {
714 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
715 fail();
716 } catch (SecurityException expected) {
717 }
718 try {
719 dpm.getDeviceOwnerComponentOnAnyUser();
720 fail();
721 } catch (SecurityException expected) {
722 }
723 try {
724 dpm.getDeviceOwnerUserId();
725 fail();
726 } catch (SecurityException expected) {
727 }
728 try {
729 dpm.getDeviceOwnerNameOnAnyUser();
730 fail();
731 } catch (SecurityException expected) {
732 }
733
734 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
735 // Still no MANAGE_USERS.
736 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
737 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
738 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
739
740 try {
741 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
742 fail();
743 } catch (SecurityException expected) {
744 }
745 try {
746 dpm.getDeviceOwnerComponentOnAnyUser();
747 fail();
748 } catch (SecurityException expected) {
749 }
750 try {
751 dpm.getDeviceOwnerUserId();
752 fail();
753 } catch (SecurityException expected) {
754 }
755 try {
756 dpm.getDeviceOwnerNameOnAnyUser();
757 fail();
758 } catch (SecurityException expected) {
759 }
760
761 // Restore.
762 mContext.binder.callingUid = origCallingUser;
763 mContext.callerPermissions.addAll(origPermissions);
764 }
765
766
Makoto Onukib643fb02015-09-22 15:03:44 -0700767 /**
768 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
769 */
770 public void testSetDeviceOwner_noSuchPackage() {
771 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800772 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700773 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
774 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
775
776 // Call from a process on the system user.
777 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
778
Makoto Onukib643fb02015-09-22 15:03:44 -0700779 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700780 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700781 fail("Didn't throw IllegalArgumentException");
782 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700783 assertTrue("Message was: " + expected.getMessage(),
784 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700785 }
786 }
787
788 public void testSetDeviceOwner_failures() throws Exception {
789 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
790 }
791
Makoto Onukia52562c2015-10-01 16:12:31 -0700792 public void testClearDeviceOwner() throws Exception {
793 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800794 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700795 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
796 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
797
798 // Set admin1 as a DA to the secondary user.
799 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
800
801 dpm.setActiveAdmin(admin1, /* replace =*/ false);
802
803 // Set admin 1 as the DO to the system user.
804
805 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
806 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
807 dpm.setActiveAdmin(admin1, /* replace =*/ false);
808 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
809
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000810 // Verify internal calls.
811 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
812 eq(admin1.getPackageName()));
813
Makoto Onukic8a5a552015-11-19 14:29:12 -0800814 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700815
Makoto Onuki90b89652016-01-28 14:44:18 -0800816 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
817
818 assertTrue(dpm.isAdminActive(admin1));
819 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
820
Makoto Onukia52562c2015-10-01 16:12:31 -0700821 // Set up other mocks.
822 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
823
824 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700825 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700826 eq(admin1.getPackageName()),
827 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800828
829 // But first pretend the user is locked. Then it should fail.
830 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
831 try {
832 dpm.clearDeviceOwnerApp(admin1.getPackageName());
833 fail("Didn't throw IllegalStateException");
834 } catch (IllegalStateException expected) {
835 MoreAsserts.assertContainsRegex(
836 "User must be running and unlocked", expected.getMessage());
837 }
838
839 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800840 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700841 dpm.clearDeviceOwnerApp(admin1.getPackageName());
842
843 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800844 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700845
Makoto Onuki90b89652016-01-28 14:44:18 -0800846 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
847 eq(UserHandle.USER_SYSTEM),
848 MockUtils.checkUserRestrictions(),
849 MockUtils.checkUserRestrictions()
850 );
851
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700852 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100853
854 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
855 // and once for clearing it.
856 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
857 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
858 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700859 // TODO Check other calls.
860 }
861
862 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
863 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800864 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700865 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
866 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
867
868 // Set admin1 as a DA to the secondary user.
869 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
870
871 dpm.setActiveAdmin(admin1, /* replace =*/ false);
872
873 // Set admin 1 as the DO to the system user.
874
875 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
876 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
877 dpm.setActiveAdmin(admin1, /* replace =*/ false);
878 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
879
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000880 // Verify internal calls.
881 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
882 eq(admin1.getPackageName()));
883
Makoto Onukic8a5a552015-11-19 14:29:12 -0800884 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700885
886 // Now call clear from the secondary user, which should throw.
887 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
888
889 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700890 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700891 eq(admin1.getPackageName()),
892 anyInt());
893 try {
894 dpm.clearDeviceOwnerApp(admin1.getPackageName());
895 fail("Didn't throw");
896 } catch (SecurityException e) {
897 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
898 }
899
Makoto Onukic8a5a552015-11-19 14:29:12 -0800900 // DO shouldn't be removed.
901 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700902 }
903
Makoto Onukib643fb02015-09-22 15:03:44 -0700904 public void testSetProfileOwner() throws Exception {
905 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700906
Makoto Onuki90b89652016-01-28 14:44:18 -0800907 // PO admin can't be deactivated.
908 dpm.removeActiveAdmin(admin1);
909 assertTrue(dpm.isAdminActive(admin1));
910
Makoto Onuki803d6752015-10-30 12:58:39 -0700911 // Try setting DO on the same user, which should fail.
912 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
913 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
914 try {
915 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
916 fail("IllegalStateException not thrown");
917 } catch (IllegalStateException expected) {
918 assertTrue("Message was: " + expected.getMessage(),
919 expected.getMessage().contains("already has a profile owner"));
920 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700921 }
922
Makoto Onuki90b89652016-01-28 14:44:18 -0800923 public void testClearProfileOwner() throws Exception {
924 setAsProfileOwner(admin1);
925
926 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
927
928 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
929 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
930
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800931 // First try when the user is locked, which should fail.
932 when(mContext.userManager.isUserUnlocked(anyInt()))
933 .thenReturn(false);
934 try {
935 dpm.clearProfileOwner(admin1);
936 fail("Didn't throw IllegalStateException");
937 } catch (IllegalStateException expected) {
938 MoreAsserts.assertContainsRegex(
939 "User must be running and unlocked", expected.getMessage());
940 }
941 // Clear, really.
942 when(mContext.userManager.isUserUnlocked(anyInt()))
943 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800944 dpm.clearProfileOwner(admin1);
945
946 // Check
947 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700948 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -0800949 }
950
Makoto Onukib643fb02015-09-22 15:03:44 -0700951 public void testSetProfileOwner_failures() throws Exception {
952 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
953 }
954
Makoto Onukia52562c2015-10-01 16:12:31 -0700955 public void testGetDeviceOwnerAdminLocked() throws Exception {
956 checkDeviceOwnerWithMultipleDeviceAdmins();
957 }
958
959 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
960 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
961 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
962 // make sure it gets the right component from the right user.
963
964 final int ANOTHER_USER_ID = 100;
965 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
966
967 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
968
969 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800970 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700971 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
972 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
973
974 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
975
Victor Change29cd472016-03-02 20:57:42 +0000976 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
977
Makoto Onukia52562c2015-10-01 16:12:31 -0700978 // Make sure the admin packge is installed to each user.
979 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
980 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
981
982 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
983 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
984
985 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
986
987
988 // Set active admins to the users.
989 dpm.setActiveAdmin(admin1, /* replace =*/ false);
990 dpm.setActiveAdmin(admin3, /* replace =*/ false);
991
992 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
993 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
994
995 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
996
997 // Set DO on the first non-system user.
998 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
999 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1000
Makoto Onukic8a5a552015-11-19 14:29:12 -08001001 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001002
1003 // Then check getDeviceOwnerAdminLocked().
1004 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1005 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1006 }
1007
1008 /**
1009 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001010 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1011 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001012 *
1013 * We didn't use to persist the DO component class name, but now we do, and the above method
1014 * finds the right component from a package name upon migration.
1015 */
1016 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001017 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001018 checkDeviceOwnerWithMultipleDeviceAdmins();
1019
1020 // Overwrite the device owner setting and clears the clas name.
1021 dpms.mOwners.setDeviceOwner(
1022 new ComponentName(admin2.getPackageName(), ""),
1023 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1024 dpms.mOwners.writeDeviceOwner();
1025
1026 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001027 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001028
1029 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001030 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1031 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001032 initializeDpms();
1033
1034 // Now the DO component name is a full name.
1035 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1036 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001037 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001038 }
1039
Makoto Onukib643fb02015-09-22 15:03:44 -07001040 public void testSetGetApplicationRestriction() {
1041 setAsProfileOwner(admin1);
1042
1043 {
1044 Bundle rest = new Bundle();
1045 rest.putString("KEY_STRING", "Foo1");
1046 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1047 }
1048
1049 {
1050 Bundle rest = new Bundle();
1051 rest.putString("KEY_STRING", "Foo2");
1052 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1053 }
1054
1055 {
1056 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1057 assertNotNull(returned);
1058 assertEquals(returned.size(), 1);
1059 assertEquals(returned.get("KEY_STRING"), "Foo1");
1060 }
1061
1062 {
1063 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1064 assertNotNull(returned);
1065 assertEquals(returned.size(), 1);
1066 assertEquals(returned.get("KEY_STRING"), "Foo2");
1067 }
1068
1069 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1070 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1071 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001072
Esteban Talaverabf60f722015-12-10 16:26:44 +00001073 public void testApplicationRestrictionsManagingApp() throws Exception {
1074 setAsProfileOwner(admin1);
1075
Rubin Xued1928a2016-02-11 17:23:06 +00001076 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001077 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1078 final int appRestrictionsManagerAppId = 20987;
1079 final int appRestrictionsManagerUid = UserHandle.getUid(
1080 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001081 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001082 eq(appRestrictionsManagerPackage),
1083 eq(DpmMockContext.CALLER_USER_HANDLE));
1084 mContext.binder.callingUid = appRestrictionsManagerUid;
1085
Rubin Xued1928a2016-02-11 17:23:06 +00001086 final PackageInfo pi = new PackageInfo();
1087 pi.applicationInfo = new ApplicationInfo();
1088 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1089 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1090 eq(appRestrictionsManagerPackage),
1091 anyInt(),
1092 eq(DpmMockContext.CALLER_USER_HANDLE));
1093
Esteban Talaverabf60f722015-12-10 16:26:44 +00001094 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1095 // delegated that permission yet.
1096 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1097 Bundle rest = new Bundle();
1098 rest.putString("KEY_STRING", "Foo1");
1099 try {
1100 dpm.setApplicationRestrictions(null, "pkg1", rest);
1101 fail("Didn't throw expected SecurityException");
1102 } catch (SecurityException expected) {
1103 MoreAsserts.assertContainsRegex(
1104 "caller cannot manage application restrictions", expected.getMessage());
1105 }
1106 try {
1107 dpm.getApplicationRestrictions(null, "pkg1");
1108 fail("Didn't throw expected SecurityException");
1109 } catch (SecurityException expected) {
1110 MoreAsserts.assertContainsRegex(
1111 "caller cannot manage application restrictions", expected.getMessage());
1112 }
1113
1114 // Check via the profile owner that no restrictions were set.
1115 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1116 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1117
Rubin Xued1928a2016-02-11 17:23:06 +00001118 // Check the API does not allow setting a non-existent package
1119 try {
1120 dpm.setApplicationRestrictionsManagingPackage(admin1,
1121 nonExistAppRestrictionsManagerPackage);
1122 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001123 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001124 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001125 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001126 }
1127
Esteban Talaverabf60f722015-12-10 16:26:44 +00001128 // Let appRestrictionsManagerPackage manage app restrictions
1129 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1130 assertEquals(appRestrictionsManagerPackage,
1131 dpm.getApplicationRestrictionsManagingPackage(admin1));
1132
1133 // Now that package should be able to set and retrieve app restrictions.
1134 mContext.binder.callingUid = appRestrictionsManagerUid;
1135 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1136 dpm.setApplicationRestrictions(null, "pkg1", rest);
1137 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1138 assertEquals(1, returned.size(), 1);
1139 assertEquals("Foo1", returned.get("KEY_STRING"));
1140
1141 // The same app running on a separate user shouldn't be able to manage app restrictions.
1142 mContext.binder.callingUid = UserHandle.getUid(
1143 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1144 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1145 try {
1146 dpm.setApplicationRestrictions(null, "pkg1", rest);
1147 fail("Didn't throw expected SecurityException");
1148 } catch (SecurityException expected) {
1149 MoreAsserts.assertContainsRegex(
1150 "caller cannot manage application restrictions", expected.getMessage());
1151 }
1152
1153 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1154 // too.
1155 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1156 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1157 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1158 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1159
1160 // Removing the ability for the package to manage app restrictions.
1161 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1162 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1163 mContext.binder.callingUid = appRestrictionsManagerUid;
1164 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1165 try {
1166 dpm.setApplicationRestrictions(null, "pkg1", null);
1167 fail("Didn't throw expected SecurityException");
1168 } catch (SecurityException expected) {
1169 MoreAsserts.assertContainsRegex(
1170 "caller cannot manage application restrictions", expected.getMessage());
1171 }
1172 }
1173
Makoto Onukia4f11972015-10-01 13:19:58 -07001174 public void testSetUserRestriction_asDo() throws Exception {
1175 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001176 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001177 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1178 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1179
1180 // First, set DO.
1181
1182 // Call from a process on the system user.
1183 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1184
1185 // Make sure admin1 is installed on system user.
1186 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001187
1188 // Call.
1189 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001190 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001191 UserHandle.USER_SYSTEM));
1192
Makoto Onuki068c54a2015-10-13 14:34:03 -07001193 DpmTestUtils.assertRestrictions(
1194 DpmTestUtils.newRestrictions(),
1195 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1196 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001197 DpmTestUtils.assertRestrictions(
1198 DpmTestUtils.newRestrictions(),
1199 dpm.getUserRestrictions(admin1)
1200 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001201
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001202 reset(mContext.userManagerInternal);
1203
1204 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1205 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1206 eq(UserHandle.USER_SYSTEM),
1207 MockUtils.checkUserRestrictions(),
1208 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001209 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001210 reset(mContext.userManagerInternal);
1211
Makoto Onukia4f11972015-10-01 13:19:58 -07001212 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001213 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1214 eq(UserHandle.USER_SYSTEM),
1215 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1216 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1217 );
1218 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001219
Makoto Onuki068c54a2015-10-13 14:34:03 -07001220 DpmTestUtils.assertRestrictions(
1221 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001222 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001223 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1224 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001225 DpmTestUtils.assertRestrictions(
1226 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001227 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001228 dpm.getUserRestrictions(admin1)
1229 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001230
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001231 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1232 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1233 eq(UserHandle.USER_SYSTEM),
1234 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1235 MockUtils.checkUserRestrictions()
1236 );
1237 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001238
Makoto Onuki068c54a2015-10-13 14:34:03 -07001239 DpmTestUtils.assertRestrictions(
1240 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1241 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1242 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001243 DpmTestUtils.assertRestrictions(
1244 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1245 dpm.getUserRestrictions(admin1)
1246 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001247
1248 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001249 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1250 eq(UserHandle.USER_SYSTEM),
1251 MockUtils.checkUserRestrictions(),
1252 MockUtils.checkUserRestrictions()
1253 );
1254 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001255
Makoto Onuki068c54a2015-10-13 14:34:03 -07001256 DpmTestUtils.assertRestrictions(
1257 DpmTestUtils.newRestrictions(),
1258 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1259 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001260 DpmTestUtils.assertRestrictions(
1261 DpmTestUtils.newRestrictions(),
1262 dpm.getUserRestrictions(admin1)
1263 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001264
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001265 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1266 // DO sets them, the scope is global.
1267 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1268 reset(mContext.userManagerInternal);
1269 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1270 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1271 eq(UserHandle.USER_SYSTEM),
1272 MockUtils.checkUserRestrictions(),
1273 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1274 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1275 );
1276 reset(mContext.userManagerInternal);
1277
1278 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1279 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1280
1281
1282 // More tests.
1283 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1284 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1285 eq(UserHandle.USER_SYSTEM),
1286 MockUtils.checkUserRestrictions(),
1287 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1288 );
1289 reset(mContext.userManagerInternal);
1290
1291 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1292 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1293 eq(UserHandle.USER_SYSTEM),
1294 MockUtils.checkUserRestrictions(),
1295 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1296 UserManager.DISALLOW_ADD_USER)
1297 );
1298 reset(mContext.userManagerInternal);
1299
1300 dpm.setCameraDisabled(admin1, true);
1301 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1302 eq(UserHandle.USER_SYSTEM),
1303 // DISALLOW_CAMERA will be applied to both local and global.
1304 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1305 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1306 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1307 );
1308 reset(mContext.userManagerInternal);
1309
1310 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1311 // locally.
1312 dpm.setCameraDisabled(admin1, false);
1313 reset(mContext.userManagerInternal);
1314
1315 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1316 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1317 dpm.setCameraDisabled(admin2, true);
1318
1319 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1320 eq(UserHandle.USER_SYSTEM),
1321 // DISALLOW_CAMERA will be applied to both local and global.
1322 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1323 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1324 UserManager.DISALLOW_ADD_USER)
1325 );
1326 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001327 // TODO Make sure restrictions are written to the file.
1328 }
1329
1330 public void testSetUserRestriction_asPo() {
1331 setAsProfileOwner(admin1);
1332
Makoto Onuki068c54a2015-10-13 14:34:03 -07001333 DpmTestUtils.assertRestrictions(
1334 DpmTestUtils.newRestrictions(),
1335 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1336 .ensureUserRestrictions()
1337 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001338
1339 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001340 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1341 eq(DpmMockContext.CALLER_USER_HANDLE),
1342 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1343 isNull(Bundle.class)
1344 );
1345 reset(mContext.userManagerInternal);
1346
Makoto Onukia4f11972015-10-01 13:19:58 -07001347 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001348 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1349 eq(DpmMockContext.CALLER_USER_HANDLE),
1350 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1351 UserManager.DISALLOW_OUTGOING_CALLS),
1352 isNull(Bundle.class)
1353 );
1354 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001355
Makoto Onuki068c54a2015-10-13 14:34:03 -07001356 DpmTestUtils.assertRestrictions(
1357 DpmTestUtils.newRestrictions(
1358 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1359 UserManager.DISALLOW_OUTGOING_CALLS
1360 ),
1361 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1362 .ensureUserRestrictions()
1363 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001364 DpmTestUtils.assertRestrictions(
1365 DpmTestUtils.newRestrictions(
1366 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1367 UserManager.DISALLOW_OUTGOING_CALLS
1368 ),
1369 dpm.getUserRestrictions(admin1)
1370 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001371
1372 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001373 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1374 eq(DpmMockContext.CALLER_USER_HANDLE),
1375 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1376 isNull(Bundle.class)
1377 );
1378 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001379
1380 DpmTestUtils.assertRestrictions(
1381 DpmTestUtils.newRestrictions(
1382 UserManager.DISALLOW_OUTGOING_CALLS
1383 ),
1384 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1385 .ensureUserRestrictions()
1386 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001387 DpmTestUtils.assertRestrictions(
1388 DpmTestUtils.newRestrictions(
1389 UserManager.DISALLOW_OUTGOING_CALLS
1390 ),
1391 dpm.getUserRestrictions(admin1)
1392 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001393
1394 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001395 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1396 eq(DpmMockContext.CALLER_USER_HANDLE),
1397 MockUtils.checkUserRestrictions(),
1398 isNull(Bundle.class)
1399 );
1400 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001401
Makoto Onuki068c54a2015-10-13 14:34:03 -07001402 DpmTestUtils.assertRestrictions(
1403 DpmTestUtils.newRestrictions(),
1404 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1405 .ensureUserRestrictions()
1406 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001407 DpmTestUtils.assertRestrictions(
1408 DpmTestUtils.newRestrictions(),
1409 dpm.getUserRestrictions(admin1)
1410 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001411
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001412 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1413 // though when DO sets them they'll be applied globally.
1414 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1415 reset(mContext.userManagerInternal);
1416 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1417 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1418 eq(DpmMockContext.CALLER_USER_HANDLE),
1419 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1420 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1421 isNull(Bundle.class)
1422 );
1423 reset(mContext.userManagerInternal);
1424
1425 dpm.setCameraDisabled(admin1, true);
1426 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1427 eq(DpmMockContext.CALLER_USER_HANDLE),
1428 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1429 UserManager.DISALLOW_ADJUST_VOLUME,
1430 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1431 isNull(Bundle.class)
1432 );
1433 reset(mContext.userManagerInternal);
1434
Makoto Onukia4f11972015-10-01 13:19:58 -07001435 // TODO Make sure restrictions are written to the file.
1436 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001437
1438 public void testGetMacAddress() throws Exception {
1439 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1440 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1441 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1442
1443 // In this test, change the caller user to "system".
1444 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1445
1446 // Make sure admin1 is installed on system user.
1447 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1448
1449 // Test 1. Caller doesn't have DO or DA.
1450 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001451 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001452 fail();
1453 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001454 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001455 }
1456
1457 // DO needs to be an DA.
1458 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1459 assertTrue(dpm.isAdminActive(admin1));
1460
1461 // Test 2. Caller has DA, but not DO.
1462 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001463 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001464 fail();
1465 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001466 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001467 }
1468
1469 // Test 3. Caller has PO, but not DO.
1470 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1471 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001472 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001473 fail();
1474 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001475 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001476 }
1477
1478 // Remove PO.
1479 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001480 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001481 // Test 4, Caller is DO now.
1482 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1483
1484 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001485 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001486
1487 // 4-2. Returns WifiInfo, but with the default MAC.
1488 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001489 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001490
1491 // 4-3. With a real MAC address.
1492 final WifiInfo wi = new WifiInfo();
1493 wi.setMacAddress("11:22:33:44:55:66");
1494 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001495 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001496 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001497
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001498 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001499 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1500 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1501
1502 // In this test, change the caller user to "system".
1503 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1504
1505 // Make sure admin1 is installed on system user.
1506 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1507
1508 // Set admin1 as DA.
1509 dpm.setActiveAdmin(admin1, false);
1510 assertTrue(dpm.isAdminActive(admin1));
1511 try {
1512 dpm.reboot(admin1);
1513 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1514 } catch (SecurityException expected) {
1515 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1516 }
1517
1518 // Set admin1 as PO.
1519 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1520 try {
1521 dpm.reboot(admin1);
1522 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1523 } catch (SecurityException expected) {
1524 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1525 }
1526
1527 // Remove PO and add DO.
1528 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001529 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001530 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1531
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001532 // admin1 is DO.
1533 // Set current call state of device to ringing.
1534 when(mContext.telephonyManager.getCallState())
1535 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1536 try {
1537 dpm.reboot(admin1);
1538 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1539 } catch (IllegalStateException expected) {
1540 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1541 }
1542
1543 // Set current call state of device to dialing/active.
1544 when(mContext.telephonyManager.getCallState())
1545 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1546 try {
1547 dpm.reboot(admin1);
1548 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1549 } catch (IllegalStateException expected) {
1550 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1551 }
1552
1553 // Set current call state of device to idle.
1554 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001555 dpm.reboot(admin1);
1556 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001557
1558 public void testSetGetSupportText() {
1559 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1560 dpm.setActiveAdmin(admin1, true);
1561 dpm.setActiveAdmin(admin2, true);
1562 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1563
1564 // Null default support messages.
1565 {
1566 assertNull(dpm.getLongSupportMessage(admin1));
1567 assertNull(dpm.getShortSupportMessage(admin1));
1568 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1569 assertNull(dpm.getShortSupportMessageForUser(admin1,
1570 DpmMockContext.CALLER_USER_HANDLE));
1571 assertNull(dpm.getLongSupportMessageForUser(admin1,
1572 DpmMockContext.CALLER_USER_HANDLE));
1573 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1574 }
1575
1576 // Only system can call the per user versions.
1577 {
1578 try {
1579 dpm.getShortSupportMessageForUser(admin1,
1580 DpmMockContext.CALLER_USER_HANDLE);
1581 fail("Only system should be able to call getXXXForUser versions");
1582 } catch (SecurityException expected) {
1583 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1584 }
1585 try {
1586 dpm.getLongSupportMessageForUser(admin1,
1587 DpmMockContext.CALLER_USER_HANDLE);
1588 fail("Only system should be able to call getXXXForUser versions");
1589 } catch (SecurityException expected) {
1590 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1591 }
1592 }
1593
1594 // Can't set message for admin in another uid.
1595 {
1596 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1597 try {
1598 dpm.setShortSupportMessage(admin1, "Some text");
1599 fail("Admins should only be able to change their own support text.");
1600 } catch (SecurityException expected) {
1601 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1602 }
1603 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1604 }
1605
1606 // Set/Get short returns what it sets and other admins text isn't changed.
1607 {
1608 final String supportText = "Some text to test with.";
1609 dpm.setShortSupportMessage(admin1, supportText);
1610 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1611 assertNull(dpm.getLongSupportMessage(admin1));
1612 assertNull(dpm.getShortSupportMessage(admin2));
1613
1614 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1615 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1616 DpmMockContext.CALLER_USER_HANDLE));
1617 assertNull(dpm.getShortSupportMessageForUser(admin2,
1618 DpmMockContext.CALLER_USER_HANDLE));
1619 assertNull(dpm.getLongSupportMessageForUser(admin1,
1620 DpmMockContext.CALLER_USER_HANDLE));
1621 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1622
1623 dpm.setShortSupportMessage(admin1, null);
1624 assertNull(dpm.getShortSupportMessage(admin1));
1625 }
1626
1627 // Set/Get long returns what it sets and other admins text isn't changed.
1628 {
1629 final String supportText = "Some text to test with.\nWith more text.";
1630 dpm.setLongSupportMessage(admin1, supportText);
1631 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1632 assertNull(dpm.getShortSupportMessage(admin1));
1633 assertNull(dpm.getLongSupportMessage(admin2));
1634
1635 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1636 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1637 DpmMockContext.CALLER_USER_HANDLE));
1638 assertNull(dpm.getLongSupportMessageForUser(admin2,
1639 DpmMockContext.CALLER_USER_HANDLE));
1640 assertNull(dpm.getShortSupportMessageForUser(admin1,
1641 DpmMockContext.CALLER_USER_HANDLE));
1642 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1643
1644 dpm.setLongSupportMessage(admin1, null);
1645 assertNull(dpm.getLongSupportMessage(admin1));
1646 }
1647 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001648
1649 /**
1650 * Test for:
1651 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001652 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001653 * {@link DevicePolicyManager#isAffiliatedUser}
1654 */
1655 public void testUserAffiliation() throws Exception {
1656 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1657 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1658 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1659
1660 // Check that the system user is unaffiliated.
1661 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1662 assertFalse(dpm.isAffiliatedUser());
1663
1664 // Set a device owner on the system user. Check that the system user becomes affiliated.
1665 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1666 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1667 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1668 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001669 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001670
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001671 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001672 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1673 setAsProfileOwner(admin2);
1674 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001675 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001676
1677 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1678 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001679 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001680 userAffiliationIds.add("red");
1681 userAffiliationIds.add("green");
1682 userAffiliationIds.add("blue");
1683 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001684 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001685 assertFalse(dpm.isAffiliatedUser());
1686
1687 // Have the device owner specify a set of affiliation ids that do not intersect with those
1688 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001689 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001690 deviceAffiliationIds.add("cyan");
1691 deviceAffiliationIds.add("yellow");
1692 deviceAffiliationIds.add("magenta");
1693 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1694 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001695 MoreAsserts.assertContentsInAnyOrder(
1696 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001697 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1698 assertFalse(dpm.isAffiliatedUser());
1699
1700 // Have the profile owner specify a set of affiliation ids that intersect with those
1701 // specified by the device owner. Check that the test user becomes affiliated.
1702 userAffiliationIds.add("yellow");
1703 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001704 MoreAsserts.assertContentsInAnyOrder(
1705 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001706 assertTrue(dpm.isAffiliatedUser());
1707
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001708 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
1709 dpm.setAffiliationIds(admin2, Collections.emptyList());
1710 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001711 assertFalse(dpm.isAffiliatedUser());
1712
1713 // Check that the system user remains affiliated.
1714 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1715 assertTrue(dpm.isAffiliatedUser());
1716 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001717
1718 public void testGetUserProvisioningState_defaultResult() {
1719 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1720 }
1721
1722 public void testSetUserProvisioningState_permission() throws Exception {
1723 setupProfileOwner();
1724 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1725
1726 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1727 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1728 }
1729
1730 public void testSetUserProvisioningState_unprivileged() throws Exception {
1731 setupProfileOwner();
1732 try {
1733 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1734 DpmMockContext.CALLER_USER_HANDLE);
1735 fail("Expected SecurityException");
1736 } catch (SecurityException expected) {
1737 }
1738 }
1739
1740 public void testSetUserProvisioningState_noManagement() {
1741 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1742 try {
1743 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1744 DpmMockContext.CALLER_USER_HANDLE);
1745 fail("IllegalStateException expected");
1746 } catch (IllegalStateException e) {
1747 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1748 e.getMessage());
1749 }
1750 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1751 }
1752
1753 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1754 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1755 setupDeviceOwner();
1756 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1757
1758 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1759 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1760 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1761 }
1762
1763 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1764 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_INCOMPLETE,
1771 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1772 }
1773
1774 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1775 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1776 setupDeviceOwner();
1777 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1778
1779 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1780 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1781 }
1782
1783 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
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_PROFILE_COMPLETE,
1790 DevicePolicyManager.STATE_USER_UNMANAGED);
1791 }
1792
1793 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1794 throws Exception {
1795 setupProfileOwner();
1796 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1797
1798 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1799 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1800 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1801 }
1802
1803 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1804 setupProfileOwner();
1805 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1806
1807 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1808 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1809 }
1810
1811 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
1812 setupProfileOwner();
1813 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1814
1815 try {
1816 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1817 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1818 DevicePolicyManager.STATE_USER_UNMANAGED);
1819 fail("Expected IllegalStateException");
1820 } catch (IllegalStateException e) {
1821 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1822 e.getMessage());
1823 }
1824 }
1825
1826 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
1827 throws Exception {
1828 setupProfileOwner();
1829 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1830
1831 try {
1832 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1833 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1834 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
1835 fail("Expected IllegalStateException");
1836 } catch (IllegalStateException e) {
1837 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1838 e.getMessage());
1839 }
1840 }
1841
1842 private void exerciseUserProvisioningTransitions(int userId, int... states) {
1843 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1844 for (int state : states) {
1845 dpm.setUserProvisioningState(state, userId);
1846 assertEquals(state, dpm.getUserProvisioningState());
1847 }
1848 }
1849
1850 private void setupProfileOwner() throws Exception {
1851 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1852
1853 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1854 dpm.setActiveAdmin(admin1, false);
1855 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
1856
1857 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1858 }
1859
1860 private void setupDeviceOwner() throws Exception {
1861 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1862
1863 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1864 dpm.setActiveAdmin(admin1, false);
1865 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1866
1867 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1868 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001869
1870 public void testSetMaximumTimeToLock() {
1871 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1872
1873 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1874 dpm.setActiveAdmin(admin2, /* replace =*/ false);
1875
1876 reset(mMockContext.powerManagerInternal);
1877 reset(mMockContext.settings);
1878
1879 dpm.setMaximumTimeToLock(admin1, 0);
1880 verifyScreenTimeoutCall(null, false);
1881 reset(mMockContext.powerManagerInternal);
1882 reset(mMockContext.settings);
1883
1884 dpm.setMaximumTimeToLock(admin1, 1);
1885 verifyScreenTimeoutCall(1, true);
1886 reset(mMockContext.powerManagerInternal);
1887 reset(mMockContext.settings);
1888
1889 dpm.setMaximumTimeToLock(admin2, 10);
1890 verifyScreenTimeoutCall(null, false);
1891 reset(mMockContext.powerManagerInternal);
1892 reset(mMockContext.settings);
1893
1894 dpm.setMaximumTimeToLock(admin1, 5);
1895 verifyScreenTimeoutCall(5, true);
1896 reset(mMockContext.powerManagerInternal);
1897 reset(mMockContext.settings);
1898
1899 dpm.setMaximumTimeToLock(admin2, 4);
1900 verifyScreenTimeoutCall(4, true);
1901 reset(mMockContext.powerManagerInternal);
1902 reset(mMockContext.settings);
1903
1904 dpm.setMaximumTimeToLock(admin1, 0);
1905 reset(mMockContext.powerManagerInternal);
1906 reset(mMockContext.settings);
1907
1908 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
1909 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1910 reset(mMockContext.powerManagerInternal);
1911 reset(mMockContext.settings);
1912
1913 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
1914 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1915 reset(mMockContext.powerManagerInternal);
1916 reset(mMockContext.settings);
1917
1918 dpm.setMaximumTimeToLock(admin2, 10);
1919 verifyScreenTimeoutCall(10, true);
1920 reset(mMockContext.powerManagerInternal);
1921 reset(mMockContext.settings);
1922
1923 // There's no restriction; shold be set to MAX.
1924 dpm.setMaximumTimeToLock(admin2, 0);
1925 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
1926 }
1927
Michal Karpinski943aabd2016-10-06 11:09:25 +01001928 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
1929 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1930 setupDeviceOwner();
1931 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1932
1933 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
1934 final long ONE_MINUTE = 60 * 1000;
1935
1936 // aggregation should be the default if unset by any admin
1937 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1938 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1939
1940 // admin not participating by default
1941 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1942
1943 //clamping from the top
1944 dpm.setRequiredStrongAuthTimeout(admin1,
1945 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1946 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
1947 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1948 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1949 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1950
1951 // 0 means default
1952 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1953 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1954 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1955 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1956
1957 // clamping from the bottom
1958 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
1959 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1960 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1961
1962 // value within range
1963 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1964 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1965 + ONE_MINUTE);
1966 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1967 + ONE_MINUTE);
1968
1969 // reset to default
1970 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1971 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1972 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1973 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1974
1975 // negative value
1976 try {
1977 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
1978 fail("Didn't throw IllegalArgumentException");
1979 } catch (IllegalArgumentException iae) {
1980 }
1981 }
1982
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001983 private void verifyScreenTimeoutCall(Integer expectedTimeout,
1984 boolean shouldStayOnWhilePluggedInBeCleared) {
1985 if (expectedTimeout == null) {
1986 verify(mMockContext.powerManagerInternal, times(0))
1987 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
1988 } else {
1989 verify(mMockContext.powerManagerInternal, times(1))
1990 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
1991 }
1992 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
1993 // UnfinishedVerificationException.
1994 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001995
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00001996 public void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00001997 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
1998 .thenReturn(false);
1999 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2000 .thenReturn(false);
2001 initializeDpms();
2002 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2003 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2004 .thenReturn(true);
2005 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2006
2007 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002008 }
Victor Chang3e794af2016-03-04 13:48:17 +00002009
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002010 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2011 setup_DeviceAdminFeatureOff();
Victor Chang3e794af2016-03-04 13:48:17 +00002012 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2013 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2014 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2015 false);
2016 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2017 }
2018
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002019 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2020 setup_DeviceAdminFeatureOff();
2021 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2022 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2023 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2024 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2025 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2026 assertCheckProvisioningPreCondition(
2027 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2028 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2029 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2030 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2031 }
2032
2033 public void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002034 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2035 .thenReturn(false);
2036 initializeDpms();
2037 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2038 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2039 .thenReturn(true);
2040 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2041
2042 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002043 }
Victor Chang3e794af2016-03-04 13:48:17 +00002044
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002045 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2046 setup_ManagedProfileFeatureOff();
Victor Chang3e794af2016-03-04 13:48:17 +00002047 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2048 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2049 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2050 false);
2051 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2052
2053 // Test again when split user is on
2054 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2055 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2056 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2057 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2058 true);
2059 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2060 }
2061
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002062 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2063 setup_ManagedProfileFeatureOff();
2064 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2065 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2066 DevicePolicyManager.CODE_OK);
2067 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2068 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2069 assertCheckProvisioningPreCondition(
2070 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2071 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2072 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2073 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2074
2075 // Test again when split user is on
2076 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2077 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2078 DevicePolicyManager.CODE_OK);
2079 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2080 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2081 assertCheckProvisioningPreCondition(
2082 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2083 DevicePolicyManager.CODE_OK);
2084 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2085 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2086 }
2087
2088 public void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002089 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2090 .thenReturn(true);
2091 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2092 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2093 .thenReturn(true);
2094 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2095
2096 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002097 }
Victor Chang3e794af2016-03-04 13:48:17 +00002098
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002099 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2100 setup_nonSplitUser_firstBoot_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002101 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2102 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2103 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2104 false /* because of non-split user */);
2105 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2106 false /* because of non-split user */);
2107 }
2108
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002109 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002110 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002111 setup_nonSplitUser_firstBoot_primaryUser();
2112 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2113 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2114 DevicePolicyManager.CODE_OK);
2115 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2116 DevicePolicyManager.CODE_OK);
2117 assertCheckProvisioningPreCondition(
2118 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2119 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2120 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2121 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2122 }
2123
2124 public void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002125 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2126 .thenReturn(true);
2127 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2128 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2129 .thenReturn(true);
2130 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2131
2132 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002133 }
Victor Chang3e794af2016-03-04 13:48:17 +00002134
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002135 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2136 throws Exception {
2137 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002138 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2139 false/* because of completed device setup */);
2140 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2141 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2142 false/* because of non-split user */);
2143 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2144 false/* because of non-split user */);
2145 }
2146
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002147 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2148 throws Exception {
2149 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2150 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2151 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2152 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2153 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2154 DevicePolicyManager.CODE_OK);
2155 assertCheckProvisioningPreCondition(
2156 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2157 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2158 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2159 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2160 }
2161
2162 public void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002163 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2164 .thenReturn(true);
2165 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2166 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2167 .thenReturn(false);
2168 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2169
2170 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002171 }
Victor Chang3e794af2016-03-04 13:48:17 +00002172
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002173 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2174 setup_splitUser_firstBoot_systemUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002175 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2176 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2177 false /* because canAddMoreManagedProfiles returns false */);
2178 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2179 true);
2180 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2181 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002182 }
2183
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002184 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2185 throws Exception {
2186 setup_splitUser_firstBoot_systemUser();
2187 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2188 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2189 DevicePolicyManager.CODE_OK);
2190 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2191 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2192 assertCheckProvisioningPreCondition(
2193 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2194 DevicePolicyManager.CODE_OK);
2195 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2196 DevicePolicyManager.CODE_SYSTEM_USER);
2197 }
2198
2199 public void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002200 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2201 .thenReturn(true);
2202 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2203 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2204 .thenReturn(false);
2205 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2206
2207 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002208 }
Victor Chang3e794af2016-03-04 13:48:17 +00002209
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002210 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2211 setup_splitUser_afterDeviceSetup_systemUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002212 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2213 true/* it's undefined behavior. Can be changed into false in the future */);
2214 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2215 false /* because canAddMoreManagedProfiles returns false */);
2216 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2217 true/* it's undefined behavior. Can be changed into false in the future */);
2218 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2219 false/* because calling uid is system user */);
2220 }
2221
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002222 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2223 throws Exception {
2224 setup_splitUser_afterDeviceSetup_systemUser();
2225 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2226 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2227 DevicePolicyManager.CODE_OK);
2228 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2229 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2230 assertCheckProvisioningPreCondition(
2231 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2232 DevicePolicyManager.CODE_OK);
2233 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2234 DevicePolicyManager.CODE_SYSTEM_USER);
2235 }
2236
2237 public void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002238 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2239 .thenReturn(true);
2240 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2241 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2242 true)).thenReturn(true);
2243 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2244
2245 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002246 }
Victor Chang3e794af2016-03-04 13:48:17 +00002247
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002248 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2249 setup_splitUser_firstBoot_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002250 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2251 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2252 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2253 true);
2254 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002255 }
2256
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002257 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002258 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002259 setup_splitUser_firstBoot_primaryUser();
2260 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2261 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2262 DevicePolicyManager.CODE_OK);
2263 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2264 DevicePolicyManager.CODE_OK);
2265 assertCheckProvisioningPreCondition(
2266 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2267 DevicePolicyManager.CODE_OK);
2268 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2269 DevicePolicyManager.CODE_OK);
2270 }
2271
2272 public void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002273 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2274 .thenReturn(true);
2275 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2276 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2277 true)).thenReturn(true);
2278 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2279
2280 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002281 }
Victor Chang3e794af2016-03-04 13:48:17 +00002282
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002283 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2284 throws Exception {
2285 setup_splitUser_afterDeviceSetup_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002286 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2287 true/* it's undefined behavior. Can be changed into false in the future */);
2288 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2289 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2290 true/* it's undefined behavior. Can be changed into false in the future */);
2291 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2292 false/* because user setup completed */);
2293 }
2294
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002295 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002296 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002297 setup_splitUser_afterDeviceSetup_primaryUser();
2298 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2299 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2300 DevicePolicyManager.CODE_OK);
2301 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2302 DevicePolicyManager.CODE_OK);
2303 assertCheckProvisioningPreCondition(
2304 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2305 DevicePolicyManager.CODE_OK);
2306 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2307 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2308 }
2309
2310 public void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002311 setDeviceOwner();
2312
2313 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2314 .thenReturn(true);
2315 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2316 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2317 .thenReturn(false);
2318 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2319
2320 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002321 }
Victor Chang3e794af2016-03-04 13:48:17 +00002322
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002323 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2324 throws Exception {
2325 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002326 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2327 false /* can't provision managed profile on system user */);
2328 }
2329
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002330 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002331 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002332 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2333 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2334 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2335 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2336 }
2337
2338 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002339 setDeviceOwner();
2340
2341 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2342 .thenReturn(true);
2343 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2344 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2345 true)).thenReturn(true);
2346 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2347
2348 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002349 }
Victor Chang3e794af2016-03-04 13:48:17 +00002350
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002351 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2352 throws Exception {
2353 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002354 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2355 }
2356
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002357 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002358 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002359 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2360 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2361 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2362 DevicePolicyManager.CODE_OK);
2363 }
2364
2365 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002366 setDeviceOwner();
2367
2368 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2369 .thenReturn(true);
2370 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2371 when(mContext.userManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_USER))
2372 .thenReturn(true);
2373 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002374 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002375 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2376 true)).thenReturn(true);
2377 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2378
2379 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002380 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002381
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002382 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2383 throws Exception {
2384 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Nicolas Prevot56400a42016-11-10 12:57:54 +00002385 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2386 }
2387
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002388 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2389 throws Exception {
2390 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2391 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2392 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2393 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2394 }
2395
2396 public void testCheckProvisioningPreCondition_permission() {
2397 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2398 try {
2399 dpm.checkProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE);
2400 fail("Didn't throw SecurityException");
2401 } catch (SecurityException expected) {
2402 }
2403 }
2404
Victor Chang3577ed22016-08-25 18:49:26 +01002405 public void testForceUpdateUserSetupComplete_permission() {
2406 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2407 try {
2408 dpm.forceUpdateUserSetupComplete();
2409 fail("Didn't throw SecurityException");
2410 } catch (SecurityException expected) {
2411 }
2412 }
2413
2414 public void testForceUpdateUserSetupComplete_systemUser() {
2415 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2416 // GIVEN calling from user 20
2417 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2418 try {
2419 dpm.forceUpdateUserSetupComplete();
2420 fail("Didn't throw SecurityException");
2421 } catch (SecurityException expected) {
2422 }
2423 }
2424
2425 public void testForceUpdateUserSetupComplete_userbuild() {
2426 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2427 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2428
2429 final int userId = UserHandle.USER_SYSTEM;
2430 // GIVEN userComplete is false in SettingsProvider
2431 setUserSetupCompleteForUser(false, userId);
2432
2433 // GIVEN userComplete is true in DPM
2434 DevicePolicyManagerService.DevicePolicyData userData =
2435 new DevicePolicyManagerService.DevicePolicyData(userId);
2436 userData.mUserSetupComplete = true;
2437 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2438
2439 // GIVEN it's user build
2440 mContext.buildMock.isDebuggable = false;
2441
2442 assertTrue(dpms.hasUserSetupCompleted());
2443
2444 dpm.forceUpdateUserSetupComplete();
2445
2446 // THEN the state in dpms is not changed
2447 assertTrue(dpms.hasUserSetupCompleted());
2448 }
2449
2450 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2451 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2452 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2453
2454 final int userId = UserHandle.USER_SYSTEM;
2455 // GIVEN userComplete is false in SettingsProvider
2456 setUserSetupCompleteForUser(false, userId);
2457
2458 // GIVEN userComplete is true in DPM
2459 DevicePolicyManagerService.DevicePolicyData userData =
2460 new DevicePolicyManagerService.DevicePolicyData(userId);
2461 userData.mUserSetupComplete = true;
2462 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2463
2464 // GIVEN it's userdebug build
2465 mContext.buildMock.isDebuggable = true;
2466
2467 assertTrue(dpms.hasUserSetupCompleted());
2468
2469 dpm.forceUpdateUserSetupComplete();
2470
2471 // THEN the state in dpms is not changed
2472 assertFalse(dpms.hasUserSetupCompleted());
2473 }
2474
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002475 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002476 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002477 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2478 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2479 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2480 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002481 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002482 }
2483
2484 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2485 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2486 setupDeviceOwner();
2487 when(mContext.userManager.getUserCount()).thenReturn(1);
2488 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2489 .thenReturn(true);
2490
2491 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002492 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002493
2494 // Enabling logging should not change the timestamp.
2495 dpm.setSecurityLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002496 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002497
2498 // Retrieving the logs should update the timestamp.
2499 final long beforeRetrieval = System.currentTimeMillis();
2500 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002501 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002502 final long afterRetrieval = System.currentTimeMillis();
2503 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2504 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2505
2506 // Retrieving the pre-boot logs should update the timestamp.
2507 Thread.sleep(2);
2508 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002509 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002510 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2511
2512 // Checking the timestamp again should not change it.
2513 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002514 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002515
2516 // Retrieving the logs again should update the timestamp.
2517 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002518 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002519 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2520
2521 // Disabling logging should not change the timestamp.
2522 Thread.sleep(2);
2523 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002524 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002525
2526 // Restarting the DPMS should not lose the timestamp.
2527 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002528 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002529
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002530 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2531 mContext.binder.callingUid = 1234567;
2532 mContext.callerPermissions.add(permission.MANAGE_USERS);
2533 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2534 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2535
2536 // System can retrieve the timestamp.
2537 mContext.binder.clearCallingIdentity();
2538 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2539
2540 // Removing the device owner should clear the timestamp.
2541 clearDeviceOwner();
2542 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002543 }
2544
2545 public void testGetLastBugReportRequestTime() throws Exception {
2546 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2547 setupDeviceOwner();
2548 when(mContext.userManager.getUserCount()).thenReturn(1);
2549 mContext.packageName = admin1.getPackageName();
2550 mContext.applicationInfo = new ApplicationInfo();
2551 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2552 .thenReturn(Color.WHITE);
2553 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2554 anyObject())).thenReturn(Color.WHITE);
2555
2556 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002557 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002558
2559 // Requesting a bug report should update the timestamp.
2560 final long beforeRequest = System.currentTimeMillis();
2561 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002562 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002563 final long afterRequest = System.currentTimeMillis();
2564 assertTrue(bugReportRequestTime >= beforeRequest);
2565 assertTrue(bugReportRequestTime <= afterRequest);
2566
2567 // Checking the timestamp again should not change it.
2568 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002569 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002570
2571 // Restarting the DPMS should not lose the timestamp.
2572 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002573 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002574
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002575 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2576 mContext.binder.callingUid = 1234567;
2577 mContext.callerPermissions.add(permission.MANAGE_USERS);
2578 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2579 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2580
2581 // System can retrieve the timestamp.
2582 mContext.binder.clearCallingIdentity();
2583 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2584
2585 // Removing the device owner should clear the timestamp.
2586 clearDeviceOwner();
2587 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002588 }
2589
2590 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2591 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2592 setupDeviceOwner();
2593 when(mContext.userManager.getUserCount()).thenReturn(1);
2594 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2595 .thenReturn(true);
2596
2597 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002598 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002599
2600 // Attempting to retrieve logs without enabling logging should not change the timestamp.
2601 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002602 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002603
2604 // Enabling logging should not change the timestamp.
2605 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002606 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002607
2608 // Retrieving the logs should update the timestamp.
2609 final long beforeRetrieval = System.currentTimeMillis();
2610 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002611 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002612 final long afterRetrieval = System.currentTimeMillis();
2613 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
2614 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
2615
2616 // Checking the timestamp again should not change it.
2617 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002618 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002619
2620 // Retrieving the logs again should update the timestamp.
2621 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002622 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002623 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
2624
2625 // Disabling logging should not change the timestamp.
2626 Thread.sleep(2);
2627 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002628 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002629
2630 // Restarting the DPMS should not lose the timestamp.
2631 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002632 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2633
2634 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2635 mContext.binder.callingUid = 1234567;
2636 mContext.callerPermissions.add(permission.MANAGE_USERS);
2637 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2638 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2639
2640 // System can retrieve the timestamp.
2641 mContext.binder.clearCallingIdentity();
2642 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2643
2644 // Removing the device owner should clear the timestamp.
2645 clearDeviceOwner();
2646 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002647 }
2648
Tony Mak2f26b792016-11-28 17:54:51 +00002649 public void testGetBindDeviceAdminTargetUsers() throws Exception {
2650 // Setup device owner.
2651 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2652 setupDeviceOwner();
2653
2654 // Only device owner is setup, the result list should be empty.
2655 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2656 MoreAsserts.assertEmpty(targetUsers);
2657
2658 // Setup a managed profile managed by the same admin.
2659 final int MANAGED_PROFILE_USER_ID = 15;
2660 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2661 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2662
2663 // Add a secondary user, it should never talk with.
2664 final int ANOTHER_USER_ID = 36;
2665 mContext.addUser(ANOTHER_USER_ID, 0);
2666
2667 // Calling from device owner admin, the result list should just contain the managed
2668 // profile user id.
2669 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2670 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
2671
2672 // Calling from managed profile admin, the result list should just contain the system
2673 // user id.
2674 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2675 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2676 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
2677 }
2678
2679 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
2680 // Setup a device owner.
2681 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2682 setupDeviceOwner();
2683
2684 // Set up a managed profile managed by different package.
2685 final int MANAGED_PROFILE_USER_ID = 15;
2686 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2687 final ComponentName adminDifferentPackage =
2688 new ComponentName("another.package", "whatever.class");
2689 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
2690
2691 // Calling from device owner admin, we should get zero bind device admin target users as
2692 // their packages are different.
2693 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2694 MoreAsserts.assertEmpty(targetUsers);
2695
2696 // Calling from managed profile admin, we should still get zero target users for the same
2697 // reason.
2698 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2699 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
2700 MoreAsserts.assertEmpty(targetUsers);
2701 }
2702
Victor Chang3e794af2016-03-04 13:48:17 +00002703 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
2704 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
2705 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
2706 dpms.notifyChangeToContentObserver(
2707 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
2708 }
2709
2710 private void assertProvisioningAllowed(String action, boolean expected) {
2711 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
2712 dpm.isProvisioningAllowed(action));
2713 }
Tony Mak2f26b792016-11-28 17:54:51 +00002714
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002715 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
2716 assertEquals("checkProvisioningPreCondition(" + action + ") returning unexpected result",
2717 provisioningCondition, dpm.checkProvisioningPreCondition(action));
2718 }
2719
Tony Mak2f26b792016-11-28 17:54:51 +00002720 /**
2721 * Setup a managed profile with the specified admin and its uid.
2722 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
2723 * @param adminUid uid of the admin package.
2724 * @param copyFromAdmin package information for {@code admin} will be built based on this
2725 * component's information.
2726 */
2727 private void addManagedProfile(
2728 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
2729 final int userId = UserHandle.getUserId(adminUid);
2730 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
2731 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2732 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
2733 dpm.setActiveAdmin(admin, false, userId);
2734 assertTrue(dpm.setProfileOwner(admin, null, userId));
2735 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2736 }
Victor Chang3e794af2016-03-04 13:48:17 +00002737}