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