blob: 8fad3eff38fad61413e4829bd4cbb2c76d108059 [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
Pavel Grafov6a40f092016-10-25 15:46:51 +010018import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
19import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
20import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
21
Makoto Onukif76b06a2015-09-22 15:03:44 -070022import android.Manifest.permission;
23import android.app.Activity;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070024import android.app.admin.DeviceAdminReceiver;
25import android.app.admin.DevicePolicyManager;
26import android.app.admin.DevicePolicyManagerInternal;
Makoto Onukif76b06a2015-09-22 15:03:44 -070027import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070028import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000029import android.content.Context;
30import android.content.Intent;
31import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000032import android.content.pm.ApplicationInfo;
33import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070034import android.content.pm.PackageManager;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010035import android.content.res.Resources;
36import android.graphics.Color;
37import android.net.IIpConnectivityMetrics;
Tony Mak2f26b792016-11-28 17:54:51 +000038import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080039import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080040import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070041import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000042import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080043import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070044import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070045import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010046import android.os.UserManagerInternal;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080047import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000048import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080049import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000050import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010051import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070052import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070053
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010054import com.android.internal.R;
Alan Treadwayafad8782016-01-19 15:15:08 +000055import com.android.server.LocalServices;
56import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000057import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000058
Makoto Onukib643fb02015-09-22 15:03:44 -070059import org.mockito.invocation.InvocationOnMock;
60import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061
Makoto Onukic8a5a552015-11-19 14:29:12 -080062import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000063import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000064import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070065import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070066import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070067import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010068import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000069import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070070
71import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070072import static org.mockito.Matchers.anyInt;
Michal Karpinskid084ca52017-01-18 15:54:18 +000073import static org.mockito.Matchers.anyLong;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010074import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070075import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070076import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070077import static org.mockito.Matchers.isNull;
Esteban Talavera548a04b2016-12-20 15:22:30 +000078import static org.mockito.Mockito.atLeast;
Makoto Onukib643fb02015-09-22 15:03:44 -070079import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070080import static org.mockito.Mockito.doReturn;
Robin Leed2a73ed2016-12-19 09:07:16 +000081import static org.mockito.Mockito.never;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080082import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070083import static org.mockito.Mockito.times;
84import static org.mockito.Mockito.verify;
85import static org.mockito.Mockito.when;
86
87/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070088 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +000089 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070090 m FrameworksServicesTests &&
91 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000092 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070093 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080094 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095
96 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +000097 *
98 * , or:
99 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000101@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700102public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000103 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
104 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
105 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
106
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107 private DpmMockContext mContext;
108 public DevicePolicyManager dpm;
109 public DevicePolicyManagerServiceTestable dpms;
110
111 @Override
112 protected void setUp() throws Exception {
113 super.setUp();
114
115 mContext = getContext();
116
117 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
118 .thenReturn(true);
119
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800120 // By default, pretend all users are running and unlocked.
121 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
122
Makoto Onukia52562c2015-10-01 16:12:31 -0700123 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700124
Makoto Onukid932f762015-09-29 16:53:38 -0700125 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
126 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
127 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800128 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700129
Makoto Onukib643fb02015-09-22 15:03:44 -0700130 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700131 }
132
Makoto Onukia52562c2015-10-01 16:12:31 -0700133 private void initializeDpms() {
134 // Need clearCallingIdentity() to pass permission checks.
135 final long ident = mContext.binder.clearCallingIdentity();
136 try {
137 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
138
139 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
140
141 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
142 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
143
144 dpm = new DevicePolicyManagerTestable(mContext, dpms);
145 } finally {
146 mContext.binder.restoreCallingIdentity(ident);
147 }
148 }
149
Makoto Onukib643fb02015-09-22 15:03:44 -0700150 private void setUpUserManager() {
151 // Emulate UserManager.set/getApplicationRestriction().
152 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
153
154 // UM.setApplicationRestrictions() will save to appRestrictions.
155 doAnswer(new Answer<Void>() {
156 @Override
157 public Void answer(InvocationOnMock invocation) throws Throwable {
158 String pkg = (String) invocation.getArguments()[0];
159 Bundle bundle = (Bundle) invocation.getArguments()[1];
160 UserHandle user = (UserHandle) invocation.getArguments()[2];
161
162 appRestrictions.put(Pair.create(pkg, user), bundle);
163
164 return null;
165 }
166 }).when(mContext.userManager).setApplicationRestrictions(
167 anyString(), any(Bundle.class), any(UserHandle.class));
168
169 // UM.getApplicationRestrictions() will read from appRestrictions.
170 doAnswer(new Answer<Bundle>() {
171 @Override
172 public Bundle answer(InvocationOnMock invocation) throws Throwable {
173 String pkg = (String) invocation.getArguments()[0];
174 UserHandle user = (UserHandle) invocation.getArguments()[1];
175
176 return appRestrictions.get(Pair.create(pkg, user));
177 }
178 }).when(mContext.userManager).getApplicationRestrictions(
179 anyString(), any(UserHandle.class));
180
Makoto Onukid932f762015-09-29 16:53:38 -0700181 // Add the first secondary user.
182 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700183 }
184
185 private void setAsProfileOwner(ComponentName admin) {
186 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
187 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
188
Makoto Onukia4f11972015-10-01 13:19:58 -0700189 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700190 dpm.setActiveAdmin(admin, /* replace =*/ false);
191
192 // Fire!
193 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
194
195 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700196 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700197 }
198
199 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700200 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
201 .thenReturn(false);
202
203 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
204 new DevicePolicyManagerServiceTestable(mContext, dataDir);
205
206 // If the device has no DPMS feature, it shouldn't register the local service.
207 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
208 }
209
210 /**
211 * Caller doesn't have proper permissions.
212 */
213 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700214 // 1. Failure cases.
215
216 // Caller doesn't have MANAGE_DEVICE_ADMINS.
217 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700218 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700219 fail("Didn't throw SecurityException");
220 } catch (SecurityException expected) {
221 }
222
223 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
224 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
225 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700226 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700227 fail("Didn't throw SecurityException");
228 } catch (SecurityException expected) {
229 }
230 }
231
Makoto Onukif76b06a2015-09-22 15:03:44 -0700232 /**
233 * Test for:
234 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800235 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700236 * {@link DevicePolicyManager#isAdminActive}
237 * {@link DevicePolicyManager#isAdminActiveAsUser}
238 * {@link DevicePolicyManager#getActiveAdmins}
239 * {@link DevicePolicyManager#getActiveAdminsAsUser}
240 */
241 public void testSetActiveAdmin() throws Exception {
242 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700243 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
244
Makoto Onukif76b06a2015-09-22 15:03:44 -0700245 // 2. Call the API.
246 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700247
248 // 3. Verify internal calls.
249
250 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700251 verify(mContext.spiedContext).sendBroadcastAsUser(
252 MockUtils.checkIntentAction(
253 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
254 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
255 verify(mContext.spiedContext).sendBroadcastAsUser(
256 MockUtils.checkIntentAction(
257 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700258 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
259
Makoto Onukif76b06a2015-09-22 15:03:44 -0700260 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
261 eq(admin1.getPackageName()),
262 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
263 eq(PackageManager.DONT_KILL_APP),
264 eq(DpmMockContext.CALLER_USER_HANDLE),
265 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700266
267 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700268
269 // Make sure it's active admin1.
270 assertTrue(dpm.isAdminActive(admin1));
271 assertFalse(dpm.isAdminActive(admin2));
272 assertFalse(dpm.isAdminActive(admin3));
273
274 // But not admin1 for a different user.
275
276 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
277 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
278 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
279
280 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
281 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
282
283 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
284
285 // Next, add one more admin.
286 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700287 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
288 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700289
290 dpm.setActiveAdmin(admin2, /* replace =*/ false);
291
292 // Now we have two admins.
293 assertTrue(dpm.isAdminActive(admin1));
294 assertTrue(dpm.isAdminActive(admin2));
295 assertFalse(dpm.isAdminActive(admin3));
296
297 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
298 // again. (times(1) because it was previously called for admin1)
299 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
300 eq(admin1.getPackageName()),
301 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
302 eq(PackageManager.DONT_KILL_APP),
303 eq(DpmMockContext.CALLER_USER_HANDLE),
304 anyString());
305
306 // 4. Add the same admin1 again without replace, which should throw.
307 try {
308 dpm.setActiveAdmin(admin1, /* replace =*/ false);
309 fail("Didn't throw");
310 } catch (IllegalArgumentException expected) {
311 }
312
313 // 5. Add the same admin1 again with replace, which should succeed.
314 dpm.setActiveAdmin(admin1, /* replace =*/ true);
315
316 // TODO make sure it's replaced.
317
318 // 6. Test getActiveAdmins()
319 List<ComponentName> admins = dpm.getActiveAdmins();
320 assertEquals(2, admins.size());
321 assertEquals(admin1, admins.get(0));
322 assertEquals(admin2, admins.get(1));
323
324 // Another user has no admins.
325 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
326
327 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
328 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
329
330 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
331 }
332
Makoto Onukid932f762015-09-29 16:53:38 -0700333 public void testSetActiveAdmin_multiUsers() throws Exception {
334
335 final int ANOTHER_USER_ID = 100;
336 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
337
338 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
339
340 // Set up pacakge manager for the other user.
341 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700342
343 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
344
345 dpm.setActiveAdmin(admin1, /* replace =*/ false);
346
347 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
348 dpm.setActiveAdmin(admin2, /* replace =*/ false);
349
350
351 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
352 assertTrue(dpm.isAdminActive(admin1));
353 assertFalse(dpm.isAdminActive(admin2));
354
355 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
356 assertFalse(dpm.isAdminActive(admin1));
357 assertTrue(dpm.isAdminActive(admin2));
358 }
359
Makoto Onukif76b06a2015-09-22 15:03:44 -0700360 /**
361 * Test for:
362 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800363 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700364 */
365 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
366 // 1. Make sure the caller has proper permissions.
367 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
368
369 dpm.setActiveAdmin(admin1, /* replace =*/ false);
370 assertTrue(dpm.isAdminActive(admin1));
371
372 // Add the same admin1 again without replace, which should throw.
373 try {
374 dpm.setActiveAdmin(admin1, /* replace =*/ false);
375 fail("Didn't throw");
376 } catch (IllegalArgumentException expected) {
377 }
378 }
379
380 /**
381 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800382 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
383 * BIND_DEVICE_ADMIN.
384 */
385 public void testSetActiveAdmin_permissionCheck() throws Exception {
386 // 1. Make sure the caller has proper permissions.
387 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
388
389 try {
390 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
391 fail();
392 } catch (IllegalArgumentException expected) {
393 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
394 }
395 assertFalse(dpm.isAdminActive(adminNoPerm));
396
397 // Change the target API level to MNC. Now it can be set as DA.
398 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
399 VERSION_CODES.M);
400 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
401 assertTrue(dpm.isAdminActive(adminNoPerm));
402
403 // TODO Test the "load from the file" case where DA will still be loaded even without
404 // BIND_DEVICE_ADMIN and target API is N.
405 }
406
407 /**
408 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700409 * {@link DevicePolicyManager#removeActiveAdmin}
410 */
411 public void testRemoveActiveAdmin_SecurityException() {
412 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
413
414 // Add admin.
415
416 dpm.setActiveAdmin(admin1, /* replace =*/ false);
417
418 assertTrue(dpm.isAdminActive(admin1));
419
420 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
421
422 // Directly call the DPMS method with a different userid, which should fail.
423 try {
424 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
425 fail("Didn't throw SecurityException");
426 } catch (SecurityException expected) {
427 }
428
429 // Try to remove active admin with a different caller userid should fail too, without
430 // having MANAGE_DEVICE_ADMINS.
431 mContext.callerPermissions.clear();
432
Makoto Onukid932f762015-09-29 16:53:38 -0700433 // Change the caller, and call into DPMS directly with a different user-id.
434
Makoto Onukif76b06a2015-09-22 15:03:44 -0700435 mContext.binder.callingUid = 1234567;
436 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700437 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700438 fail("Didn't throw SecurityException");
439 } catch (SecurityException expected) {
440 }
441 }
442
443 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800444 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
445 * (because we can't send the remove broadcast).
446 */
447 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
448 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
449
450 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
451
452 // Add admin.
453
454 dpm.setActiveAdmin(admin1, /* replace =*/ false);
455
456 assertTrue(dpm.isAdminActive(admin1));
457
458 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
459
460 // 1. User not unlocked.
461 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
462 .thenReturn(false);
463 try {
464 dpm.removeActiveAdmin(admin1);
465 fail("Didn't throw IllegalStateException");
466 } catch (IllegalStateException expected) {
467 MoreAsserts.assertContainsRegex(
468 "User must be running and unlocked", expected.getMessage());
469 }
470
471 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
472
473 // 2. User unlocked.
474 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
475 .thenReturn(true);
476
477 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700478 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800479 }
480
481 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700482 * Test for:
483 * {@link DevicePolicyManager#removeActiveAdmin}
484 */
Makoto Onukid932f762015-09-29 16:53:38 -0700485 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700486 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
487
488 // Add admin1.
489
490 dpm.setActiveAdmin(admin1, /* replace =*/ false);
491
492 assertTrue(dpm.isAdminActive(admin1));
493 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
494
495 // Different user, but should work, because caller has proper permissions.
496 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700497
498 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700499 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700500
501 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700502 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700503
504 // TODO DO Still can't be removed in this case.
505 }
506
507 /**
508 * Test for:
509 * {@link DevicePolicyManager#removeActiveAdmin}
510 */
511 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
512 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
513 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
514
515 // Add admin1.
516
517 dpm.setActiveAdmin(admin1, /* replace =*/ false);
518
519 assertTrue(dpm.isAdminActive(admin1));
520 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
521
522 // Broadcast from saveSettingsLocked().
523 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
524 MockUtils.checkIntentAction(
525 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
526 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
527
528 // Remove. No permissions, but same user, so it'll work.
529 mContext.callerPermissions.clear();
530 dpm.removeActiveAdmin(admin1);
531
Makoto Onukif76b06a2015-09-22 15:03:44 -0700532 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
533 MockUtils.checkIntentAction(
534 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
535 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
536 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700537 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700538 eq(dpms.mHandler),
539 eq(Activity.RESULT_OK),
540 isNull(String.class),
541 isNull(Bundle.class));
542
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700543 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700544
545 // Again broadcast from saveSettingsLocked().
546 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
547 MockUtils.checkIntentAction(
548 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
549 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
550
551 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700552 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700553
554 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000555 * Test for: @{link DevicePolicyManager#setActivePasswordState}
556 *
557 * Validates that when the password for a user changes, the notification broadcast intent
558 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
559 * addition to ones in the original user.
560 */
561 public void testSetActivePasswordState_sendToProfiles() throws Exception {
562 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
563
564 final int MANAGED_PROFILE_USER_ID = 78;
565 final int MANAGED_PROFILE_ADMIN_UID =
566 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
567
568 // Setup device owner.
569 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
570 mContext.packageName = admin1.getPackageName();
571 setupDeviceOwner();
572
573 // Add a managed profile belonging to the system user.
574 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
575
576 // Change the parent user's password.
577 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
578
579 // Both the device owner and the managed profile owner should receive this broadcast.
580 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
581 intent.setComponent(admin1);
582 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
583
584 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
585 MockUtils.checkIntent(intent),
586 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
587 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
588 MockUtils.checkIntent(intent),
589 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
590 }
591
592 /**
593 * Test for: @{link DevicePolicyManager#setActivePasswordState}
594 *
595 * Validates that when the password for a managed profile changes, the notification broadcast
596 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
597 * its parent.
598 */
599 public void testSetActivePasswordState_notSentToParent() throws Exception {
600 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
601
602 final int MANAGED_PROFILE_USER_ID = 78;
603 final int MANAGED_PROFILE_ADMIN_UID =
604 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
605
606 // Setup device owner.
607 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
608 mContext.packageName = admin1.getPackageName();
609 doReturn(true).when(mContext.lockPatternUtils)
610 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
611 setupDeviceOwner();
612
613 // Add a managed profile belonging to the system user.
614 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
615
616 // Change the profile's password.
617 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
618
619 // Both the device owner and the managed profile owner should receive this broadcast.
620 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
621 intent.setComponent(admin1);
622 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
623
624 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
625 MockUtils.checkIntent(intent),
626 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
627 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
628 MockUtils.checkIntent(intent),
629 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
630 }
631 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000632 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700633 */
634 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000635 setDeviceOwner();
636
637 // Try to set a profile owner on the same user, which should fail.
638 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
639 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
640 try {
641 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
642 fail("IllegalStateException not thrown");
643 } catch (IllegalStateException expected) {
644 assertTrue("Message was: " + expected.getMessage(),
645 expected.getMessage().contains("already has a device owner"));
646 }
647
648 // DO admin can't be deactivated.
649 dpm.removeActiveAdmin(admin1);
650 assertTrue(dpm.isAdminActive(admin1));
651
652 // TODO Test getDeviceOwnerName() too. To do so, we need to change
653 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
654 }
655
656 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700657 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800658 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700659 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
660 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
661
Makoto Onukid932f762015-09-29 16:53:38 -0700662 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700663 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
664
Makoto Onukid932f762015-09-29 16:53:38 -0700665 // Make sure admin1 is installed on system user.
666 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700667
Makoto Onukic8a5a552015-11-19 14:29:12 -0800668 // Check various get APIs.
669 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
670
Makoto Onukib643fb02015-09-22 15:03:44 -0700671 // DO needs to be an DA.
672 dpm.setActiveAdmin(admin1, /* replace =*/ false);
673
674 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700675 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700676
Makoto Onukic8a5a552015-11-19 14:29:12 -0800677 // getDeviceOwnerComponent should return the admin1 component.
678 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
679 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
680
681 // Check various get APIs.
682 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
683
684 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
685 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
686 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
687 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
688
689 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
690
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000691 // Verify internal calls.
692 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
693 eq(admin1.getPackageName()));
694
Makoto Onukib643fb02015-09-22 15:03:44 -0700695 // TODO We should check if the caller has called clearCallerIdentity().
696 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
697 eq(UserHandle.USER_SYSTEM), eq(false));
698
699 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
700 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
701 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
702
Makoto Onukic8a5a552015-11-19 14:29:12 -0800703 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700704 }
705
Makoto Onukic8a5a552015-11-19 14:29:12 -0800706 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
707 final int origCallingUser = mContext.binder.callingUid;
708 final List origPermissions = new ArrayList(mContext.callerPermissions);
709 mContext.callerPermissions.clear();
710
711 mContext.callerPermissions.add(permission.MANAGE_USERS);
712
713 mContext.binder.callingUid = Process.SYSTEM_UID;
714
715 // TODO Test getDeviceOwnerName() too. To do so, we need to change
716 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
717 if (hasDeviceOwner) {
718 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
719 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
720 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
721
722 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
723 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
724 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
725 } else {
726 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
727 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
728 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
729
730 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
731 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
732 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
733 }
734
735 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
736 if (hasDeviceOwner) {
737 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
738 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
739 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
740
741 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
742 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
743 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
744 } else {
745 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
746 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
747 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
748
749 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
750 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
751 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
752 }
753
754 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
755 // Still with MANAGE_USERS.
756 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
757 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
758 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
759
760 if (hasDeviceOwner) {
761 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
762 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
763 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
764 } else {
765 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
766 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
767 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
768 }
769
770 mContext.binder.callingUid = Process.SYSTEM_UID;
771 mContext.callerPermissions.remove(permission.MANAGE_USERS);
772 // System can still call "OnAnyUser" without MANAGE_USERS.
773 if (hasDeviceOwner) {
774 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
775 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
776 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
777
778 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
779 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
780 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
781 } else {
782 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
783 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
784 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
785
786 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
787 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
788 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
789 }
790
791 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
792 // Still no MANAGE_USERS.
793 if (hasDeviceOwner) {
794 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
795 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
796 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
797 } else {
798 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
799 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
800 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
801 }
802
803 try {
804 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
805 fail();
806 } catch (SecurityException expected) {
807 }
808 try {
809 dpm.getDeviceOwnerComponentOnAnyUser();
810 fail();
811 } catch (SecurityException expected) {
812 }
813 try {
814 dpm.getDeviceOwnerUserId();
815 fail();
816 } catch (SecurityException expected) {
817 }
818 try {
819 dpm.getDeviceOwnerNameOnAnyUser();
820 fail();
821 } catch (SecurityException expected) {
822 }
823
824 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
825 // Still no MANAGE_USERS.
826 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
827 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
828 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
829
830 try {
831 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
832 fail();
833 } catch (SecurityException expected) {
834 }
835 try {
836 dpm.getDeviceOwnerComponentOnAnyUser();
837 fail();
838 } catch (SecurityException expected) {
839 }
840 try {
841 dpm.getDeviceOwnerUserId();
842 fail();
843 } catch (SecurityException expected) {
844 }
845 try {
846 dpm.getDeviceOwnerNameOnAnyUser();
847 fail();
848 } catch (SecurityException expected) {
849 }
850
851 // Restore.
852 mContext.binder.callingUid = origCallingUser;
853 mContext.callerPermissions.addAll(origPermissions);
854 }
855
856
Makoto Onukib643fb02015-09-22 15:03:44 -0700857 /**
858 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
859 */
860 public void testSetDeviceOwner_noSuchPackage() {
861 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800862 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700863 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
864 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
865
866 // Call from a process on the system user.
867 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
868
Makoto Onukib643fb02015-09-22 15:03:44 -0700869 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700870 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700871 fail("Didn't throw IllegalArgumentException");
872 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700873 assertTrue("Message was: " + expected.getMessage(),
874 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700875 }
876 }
877
878 public void testSetDeviceOwner_failures() throws Exception {
879 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
880 }
881
Makoto Onukia52562c2015-10-01 16:12:31 -0700882 public void testClearDeviceOwner() throws Exception {
883 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800884 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700885 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
886 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
887
888 // Set admin1 as a DA to the secondary user.
889 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
890
891 dpm.setActiveAdmin(admin1, /* replace =*/ false);
892
893 // Set admin 1 as the DO to the system user.
894
895 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
896 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
897 dpm.setActiveAdmin(admin1, /* replace =*/ false);
898 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
899
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000900 // Verify internal calls.
901 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
902 eq(admin1.getPackageName()));
903
Makoto Onukic8a5a552015-11-19 14:29:12 -0800904 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700905
Makoto Onuki90b89652016-01-28 14:44:18 -0800906 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
907
908 assertTrue(dpm.isAdminActive(admin1));
909 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
910
Makoto Onukia52562c2015-10-01 16:12:31 -0700911 // Set up other mocks.
912 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
913
914 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700915 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700916 eq(admin1.getPackageName()),
917 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800918
919 // But first pretend the user is locked. Then it should fail.
920 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
921 try {
922 dpm.clearDeviceOwnerApp(admin1.getPackageName());
923 fail("Didn't throw IllegalStateException");
924 } catch (IllegalStateException expected) {
925 MoreAsserts.assertContainsRegex(
926 "User must be running and unlocked", expected.getMessage());
927 }
928
929 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800930 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700931 dpm.clearDeviceOwnerApp(admin1.getPackageName());
932
933 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800934 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700935
Makoto Onuki90b89652016-01-28 14:44:18 -0800936 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
937 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100938 eq(null),
939 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800940
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700941 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100942
943 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
944 // and once for clearing it.
945 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
946 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
947 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700948 // TODO Check other calls.
949 }
950
951 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
952 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800953 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700954 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
955 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
956
957 // Set admin1 as a DA to the secondary user.
958 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
959
960 dpm.setActiveAdmin(admin1, /* replace =*/ false);
961
962 // Set admin 1 as the DO to the system user.
963
964 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
965 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
966 dpm.setActiveAdmin(admin1, /* replace =*/ false);
967 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
968
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000969 // Verify internal calls.
970 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
971 eq(admin1.getPackageName()));
972
Makoto Onukic8a5a552015-11-19 14:29:12 -0800973 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700974
975 // Now call clear from the secondary user, which should throw.
976 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
977
978 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700979 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700980 eq(admin1.getPackageName()),
981 anyInt());
982 try {
983 dpm.clearDeviceOwnerApp(admin1.getPackageName());
984 fail("Didn't throw");
985 } catch (SecurityException e) {
986 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
987 }
988
Makoto Onukic8a5a552015-11-19 14:29:12 -0800989 // DO shouldn't be removed.
990 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700991 }
992
Makoto Onukib643fb02015-09-22 15:03:44 -0700993 public void testSetProfileOwner() throws Exception {
994 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700995
Makoto Onuki90b89652016-01-28 14:44:18 -0800996 // PO admin can't be deactivated.
997 dpm.removeActiveAdmin(admin1);
998 assertTrue(dpm.isAdminActive(admin1));
999
Makoto Onuki803d6752015-10-30 12:58:39 -07001000 // Try setting DO on the same user, which should fail.
1001 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1002 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1003 try {
1004 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1005 fail("IllegalStateException not thrown");
1006 } catch (IllegalStateException expected) {
1007 assertTrue("Message was: " + expected.getMessage(),
1008 expected.getMessage().contains("already has a profile owner"));
1009 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001010 }
1011
Makoto Onuki90b89652016-01-28 14:44:18 -08001012 public void testClearProfileOwner() throws Exception {
1013 setAsProfileOwner(admin1);
1014
1015 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1016
1017 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1018 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1019
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001020 // First try when the user is locked, which should fail.
1021 when(mContext.userManager.isUserUnlocked(anyInt()))
1022 .thenReturn(false);
1023 try {
1024 dpm.clearProfileOwner(admin1);
1025 fail("Didn't throw IllegalStateException");
1026 } catch (IllegalStateException expected) {
1027 MoreAsserts.assertContainsRegex(
1028 "User must be running and unlocked", expected.getMessage());
1029 }
1030 // Clear, really.
1031 when(mContext.userManager.isUserUnlocked(anyInt()))
1032 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001033 dpm.clearProfileOwner(admin1);
1034
1035 // Check
1036 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001037 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001038 }
1039
Makoto Onukib643fb02015-09-22 15:03:44 -07001040 public void testSetProfileOwner_failures() throws Exception {
1041 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1042 }
1043
Makoto Onukia52562c2015-10-01 16:12:31 -07001044 public void testGetDeviceOwnerAdminLocked() throws Exception {
1045 checkDeviceOwnerWithMultipleDeviceAdmins();
1046 }
1047
1048 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1049 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1050 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1051 // make sure it gets the right component from the right user.
1052
1053 final int ANOTHER_USER_ID = 100;
1054 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1055
1056 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1057
1058 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001059 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001060 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1061 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1062
1063 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1064
Victor Change29cd472016-03-02 20:57:42 +00001065 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1066
Makoto Onukia52562c2015-10-01 16:12:31 -07001067 // Make sure the admin packge is installed to each user.
1068 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1069 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1070
1071 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1072 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1073
1074 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1075
1076
1077 // Set active admins to the users.
1078 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1079 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1080
1081 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1082 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1083
1084 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1085
1086 // Set DO on the first non-system user.
1087 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1088 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1089
Makoto Onukic8a5a552015-11-19 14:29:12 -08001090 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001091
1092 // Then check getDeviceOwnerAdminLocked().
1093 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1094 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1095 }
1096
1097 /**
1098 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001099 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1100 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001101 *
1102 * We didn't use to persist the DO component class name, but now we do, and the above method
1103 * finds the right component from a package name upon migration.
1104 */
1105 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001106 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001107 checkDeviceOwnerWithMultipleDeviceAdmins();
1108
1109 // Overwrite the device owner setting and clears the clas name.
1110 dpms.mOwners.setDeviceOwner(
1111 new ComponentName(admin2.getPackageName(), ""),
1112 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1113 dpms.mOwners.writeDeviceOwner();
1114
1115 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001116 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001117
1118 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001119 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1120 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001121 initializeDpms();
1122
1123 // Now the DO component name is a full name.
1124 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1125 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001126 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001127 }
1128
Makoto Onukib643fb02015-09-22 15:03:44 -07001129 public void testSetGetApplicationRestriction() {
1130 setAsProfileOwner(admin1);
1131
1132 {
1133 Bundle rest = new Bundle();
1134 rest.putString("KEY_STRING", "Foo1");
1135 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1136 }
1137
1138 {
1139 Bundle rest = new Bundle();
1140 rest.putString("KEY_STRING", "Foo2");
1141 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1142 }
1143
1144 {
1145 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1146 assertNotNull(returned);
1147 assertEquals(returned.size(), 1);
1148 assertEquals(returned.get("KEY_STRING"), "Foo1");
1149 }
1150
1151 {
1152 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1153 assertNotNull(returned);
1154 assertEquals(returned.size(), 1);
1155 assertEquals(returned.get("KEY_STRING"), "Foo2");
1156 }
1157
1158 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1159 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1160 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001161
Esteban Talaverabf60f722015-12-10 16:26:44 +00001162 public void testApplicationRestrictionsManagingApp() throws Exception {
1163 setAsProfileOwner(admin1);
1164
Rubin Xued1928a2016-02-11 17:23:06 +00001165 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001166 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1167 final int appRestrictionsManagerAppId = 20987;
1168 final int appRestrictionsManagerUid = UserHandle.getUid(
1169 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001170 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001171 eq(appRestrictionsManagerPackage),
1172 eq(DpmMockContext.CALLER_USER_HANDLE));
1173 mContext.binder.callingUid = appRestrictionsManagerUid;
1174
Rubin Xued1928a2016-02-11 17:23:06 +00001175 final PackageInfo pi = new PackageInfo();
1176 pi.applicationInfo = new ApplicationInfo();
1177 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1178 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1179 eq(appRestrictionsManagerPackage),
1180 anyInt(),
1181 eq(DpmMockContext.CALLER_USER_HANDLE));
1182
Esteban Talaverabf60f722015-12-10 16:26:44 +00001183 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1184 // delegated that permission yet.
1185 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1186 Bundle rest = new Bundle();
1187 rest.putString("KEY_STRING", "Foo1");
1188 try {
1189 dpm.setApplicationRestrictions(null, "pkg1", rest);
1190 fail("Didn't throw expected SecurityException");
1191 } catch (SecurityException expected) {
1192 MoreAsserts.assertContainsRegex(
1193 "caller cannot manage application restrictions", expected.getMessage());
1194 }
1195 try {
1196 dpm.getApplicationRestrictions(null, "pkg1");
1197 fail("Didn't throw expected SecurityException");
1198 } catch (SecurityException expected) {
1199 MoreAsserts.assertContainsRegex(
1200 "caller cannot manage application restrictions", expected.getMessage());
1201 }
1202
1203 // Check via the profile owner that no restrictions were set.
1204 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1205 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1206
Rubin Xued1928a2016-02-11 17:23:06 +00001207 // Check the API does not allow setting a non-existent package
1208 try {
1209 dpm.setApplicationRestrictionsManagingPackage(admin1,
1210 nonExistAppRestrictionsManagerPackage);
1211 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001212 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001213 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001214 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001215 }
1216
Esteban Talaverabf60f722015-12-10 16:26:44 +00001217 // Let appRestrictionsManagerPackage manage app restrictions
1218 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1219 assertEquals(appRestrictionsManagerPackage,
1220 dpm.getApplicationRestrictionsManagingPackage(admin1));
1221
1222 // Now that package should be able to set and retrieve app restrictions.
1223 mContext.binder.callingUid = appRestrictionsManagerUid;
1224 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1225 dpm.setApplicationRestrictions(null, "pkg1", rest);
1226 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1227 assertEquals(1, returned.size(), 1);
1228 assertEquals("Foo1", returned.get("KEY_STRING"));
1229
1230 // The same app running on a separate user shouldn't be able to manage app restrictions.
1231 mContext.binder.callingUid = UserHandle.getUid(
1232 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1233 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1234 try {
1235 dpm.setApplicationRestrictions(null, "pkg1", rest);
1236 fail("Didn't throw expected SecurityException");
1237 } catch (SecurityException expected) {
1238 MoreAsserts.assertContainsRegex(
1239 "caller cannot manage application restrictions", expected.getMessage());
1240 }
1241
1242 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1243 // too.
1244 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1245 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1246 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1247 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1248
1249 // Removing the ability for the package to manage app restrictions.
1250 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1251 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1252 mContext.binder.callingUid = appRestrictionsManagerUid;
1253 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1254 try {
1255 dpm.setApplicationRestrictions(null, "pkg1", null);
1256 fail("Didn't throw expected SecurityException");
1257 } catch (SecurityException expected) {
1258 MoreAsserts.assertContainsRegex(
1259 "caller cannot manage application restrictions", expected.getMessage());
1260 }
1261 }
1262
Makoto Onukia4f11972015-10-01 13:19:58 -07001263 public void testSetUserRestriction_asDo() throws Exception {
1264 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001265 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001266 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1267 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1268
1269 // First, set DO.
1270
1271 // Call from a process on the system user.
1272 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1273
1274 // Make sure admin1 is installed on system user.
1275 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001276
1277 // Call.
1278 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001279 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001280 UserHandle.USER_SYSTEM));
1281
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001282 // Check that the user restrictions that are enabled by default are set. Then unset them.
1283 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001284 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001285 DpmTestUtils.assertRestrictions(
1286 DpmTestUtils.newRestrictions(defaultRestrictions),
1287 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1288 );
1289 DpmTestUtils.assertRestrictions(
1290 DpmTestUtils.newRestrictions(defaultRestrictions),
1291 dpm.getUserRestrictions(admin1)
1292 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001293 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1294 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001295 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001296 eq(true) /* isDeviceOwner */,
1297 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001298 );
1299 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001300
1301 for (String restriction : defaultRestrictions) {
1302 dpm.clearUserRestriction(admin1, restriction);
1303 }
1304
Esteban Talavera548a04b2016-12-20 15:22:30 +00001305 assertNoDeviceOwnerRestrictions();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001306 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001307
1308 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1309 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1310 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001311 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1312 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001313 reset(mContext.userManagerInternal);
1314
Makoto Onukia4f11972015-10-01 13:19:58 -07001315 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001316 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1317 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001318 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1319 UserManager.DISALLOW_ADD_USER),
1320 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001321 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001322
Makoto Onuki068c54a2015-10-13 14:34:03 -07001323 DpmTestUtils.assertRestrictions(
1324 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001325 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001326 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1327 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001328 DpmTestUtils.assertRestrictions(
1329 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001330 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001331 dpm.getUserRestrictions(admin1)
1332 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001333
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001334 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1335 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1336 eq(UserHandle.USER_SYSTEM),
1337 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001338 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001339 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001340
Makoto Onuki068c54a2015-10-13 14:34:03 -07001341 DpmTestUtils.assertRestrictions(
1342 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1343 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1344 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001345 DpmTestUtils.assertRestrictions(
1346 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1347 dpm.getUserRestrictions(admin1)
1348 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001349
1350 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001351 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1352 eq(UserHandle.USER_SYSTEM),
1353 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001354 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001355 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001356
Esteban Talavera548a04b2016-12-20 15:22:30 +00001357 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001358
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001359 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1360 // DO sets them, the scope is global.
1361 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1362 reset(mContext.userManagerInternal);
1363 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1364 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1365 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001366 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001367 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1368 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001369 reset(mContext.userManagerInternal);
1370
1371 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1372 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov6a40f092016-10-25 15:46:51 +01001373 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001374
1375 // More tests.
1376 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1377 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1378 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001379 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1380 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001381 reset(mContext.userManagerInternal);
1382
1383 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1384 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1385 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001386 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001387 UserManager.DISALLOW_ADD_USER),
1388 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001389 reset(mContext.userManagerInternal);
1390
1391 dpm.setCameraDisabled(admin1, true);
1392 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1393 eq(UserHandle.USER_SYSTEM),
1394 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001395 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001396 UserManager.DISALLOW_ADD_USER),
1397 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001398 reset(mContext.userManagerInternal);
1399
1400 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1401 // locally.
1402 dpm.setCameraDisabled(admin1, false);
1403 reset(mContext.userManagerInternal);
1404
1405 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1406 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1407 dpm.setCameraDisabled(admin2, true);
1408
1409 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1410 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001411 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001412 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001413 UserManager.DISALLOW_ADD_USER),
1414 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001415 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001416 // TODO Make sure restrictions are written to the file.
1417 }
1418
1419 public void testSetUserRestriction_asPo() {
1420 setAsProfileOwner(admin1);
1421
Makoto Onuki068c54a2015-10-13 14:34:03 -07001422 DpmTestUtils.assertRestrictions(
1423 DpmTestUtils.newRestrictions(),
1424 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1425 .ensureUserRestrictions()
1426 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001427
1428 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001429 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1430 eq(DpmMockContext.CALLER_USER_HANDLE),
1431 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001432 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001433 reset(mContext.userManagerInternal);
1434
Makoto Onukia4f11972015-10-01 13:19:58 -07001435 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001436 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1437 eq(DpmMockContext.CALLER_USER_HANDLE),
1438 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1439 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001440 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001441 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001442
Makoto Onuki068c54a2015-10-13 14:34:03 -07001443 DpmTestUtils.assertRestrictions(
1444 DpmTestUtils.newRestrictions(
1445 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1446 UserManager.DISALLOW_OUTGOING_CALLS
1447 ),
1448 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1449 .ensureUserRestrictions()
1450 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001451 DpmTestUtils.assertRestrictions(
1452 DpmTestUtils.newRestrictions(
1453 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1454 UserManager.DISALLOW_OUTGOING_CALLS
1455 ),
1456 dpm.getUserRestrictions(admin1)
1457 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001458
1459 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001460 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1461 eq(DpmMockContext.CALLER_USER_HANDLE),
1462 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001463 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001464 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001465
1466 DpmTestUtils.assertRestrictions(
1467 DpmTestUtils.newRestrictions(
1468 UserManager.DISALLOW_OUTGOING_CALLS
1469 ),
1470 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1471 .ensureUserRestrictions()
1472 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001473 DpmTestUtils.assertRestrictions(
1474 DpmTestUtils.newRestrictions(
1475 UserManager.DISALLOW_OUTGOING_CALLS
1476 ),
1477 dpm.getUserRestrictions(admin1)
1478 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001479
1480 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001481 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1482 eq(DpmMockContext.CALLER_USER_HANDLE),
1483 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001484 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001485 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001486
Makoto Onuki068c54a2015-10-13 14:34:03 -07001487 DpmTestUtils.assertRestrictions(
1488 DpmTestUtils.newRestrictions(),
1489 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1490 .ensureUserRestrictions()
1491 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001492 DpmTestUtils.assertRestrictions(
1493 DpmTestUtils.newRestrictions(),
1494 dpm.getUserRestrictions(admin1)
1495 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001496
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001497 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1498 // though when DO sets them they'll be applied globally.
1499 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1500 reset(mContext.userManagerInternal);
1501 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1502 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1503 eq(DpmMockContext.CALLER_USER_HANDLE),
1504 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1505 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001506 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001507 reset(mContext.userManagerInternal);
1508
1509 dpm.setCameraDisabled(admin1, true);
1510 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1511 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001512 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001513 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001514 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001515 reset(mContext.userManagerInternal);
1516
Makoto Onukia4f11972015-10-01 13:19:58 -07001517 // TODO Make sure restrictions are written to the file.
1518 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001519
Esteban Talavera548a04b2016-12-20 15:22:30 +00001520
1521 public void testDefaultEnabledUserRestrictions() throws Exception {
1522 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1523 mContext.callerPermissions.add(permission.MANAGE_USERS);
1524 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1525 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1526
1527 // First, set DO.
1528
1529 // Call from a process on the system user.
1530 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1531
1532 // Make sure admin1 is installed on system user.
1533 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1534
1535 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1536 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1537 UserHandle.USER_SYSTEM));
1538
1539 // Check that the user restrictions that are enabled by default are set. Then unset them.
1540 String[] defaultRestrictions = UserRestrictionsUtils
1541 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1542 assertTrue(defaultRestrictions.length > 0);
1543 DpmTestUtils.assertRestrictions(
1544 DpmTestUtils.newRestrictions(defaultRestrictions),
1545 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1546 );
1547 DpmTestUtils.assertRestrictions(
1548 DpmTestUtils.newRestrictions(defaultRestrictions),
1549 dpm.getUserRestrictions(admin1)
1550 );
1551 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1552 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001553 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001554 eq(true) /* isDeviceOwner */,
1555 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001556 );
1557 reset(mContext.userManagerInternal);
1558
1559 for (String restriction : defaultRestrictions) {
1560 dpm.clearUserRestriction(admin1, restriction);
1561 }
1562
1563 assertNoDeviceOwnerRestrictions();
1564
1565 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1566 reset(mContext.userManagerInternal);
1567 initializeDpms();
1568 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1569 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1570
1571 assertNoDeviceOwnerRestrictions();
1572
1573 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1574 // is set as it wasn't enabled during setDeviceOwner.
1575 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1576 assertFalse(UserRestrictionsUtils
1577 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1578 UserRestrictionsUtils
1579 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1580 try {
1581 reset(mContext.userManagerInternal);
1582 initializeDpms();
1583 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1584 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1585
1586 DpmTestUtils.assertRestrictions(
1587 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1588 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1589 );
1590 DpmTestUtils.assertRestrictions(
1591 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1592 dpm.getUserRestrictions(admin1)
1593 );
1594 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1595 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001596 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001597 eq(true) /* isDeviceOwner */,
1598 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001599 );
1600 reset(mContext.userManagerInternal);
1601
1602 // Remove the restriction.
1603 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1604
1605 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1606 initializeDpms();
1607 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1608 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1609 assertNoDeviceOwnerRestrictions();
1610 } finally {
1611 UserRestrictionsUtils
1612 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1613 }
1614 }
1615
1616 private void assertNoDeviceOwnerRestrictions() {
1617 DpmTestUtils.assertRestrictions(
1618 DpmTestUtils.newRestrictions(),
1619 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1620 );
1621 DpmTestUtils.assertRestrictions(
1622 DpmTestUtils.newRestrictions(),
1623 dpm.getUserRestrictions(admin1)
1624 );
1625 }
1626
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001627 public void testGetMacAddress() throws Exception {
1628 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1629 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1630 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1631
1632 // In this test, change the caller user to "system".
1633 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1634
1635 // Make sure admin1 is installed on system user.
1636 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1637
1638 // Test 1. Caller doesn't have DO or DA.
1639 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001640 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001641 fail();
1642 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001643 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001644 }
1645
1646 // DO needs to be an DA.
1647 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1648 assertTrue(dpm.isAdminActive(admin1));
1649
1650 // Test 2. Caller has DA, but not DO.
1651 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001652 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001653 fail();
1654 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001655 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001656 }
1657
1658 // Test 3. Caller has PO, but not DO.
1659 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1660 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001661 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001662 fail();
1663 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001664 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001665 }
1666
1667 // Remove PO.
1668 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001669 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001670 // Test 4, Caller is DO now.
1671 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1672
1673 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001674 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001675
1676 // 4-2. Returns WifiInfo, but with the default MAC.
1677 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001678 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001679
1680 // 4-3. With a real MAC address.
1681 final WifiInfo wi = new WifiInfo();
1682 wi.setMacAddress("11:22:33:44:55:66");
1683 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001684 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001685 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001686
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001687 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001688 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1689 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1690
1691 // In this test, change the caller user to "system".
1692 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1693
1694 // Make sure admin1 is installed on system user.
1695 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1696
1697 // Set admin1 as DA.
1698 dpm.setActiveAdmin(admin1, false);
1699 assertTrue(dpm.isAdminActive(admin1));
1700 try {
1701 dpm.reboot(admin1);
1702 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1703 } catch (SecurityException expected) {
1704 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1705 }
1706
1707 // Set admin1 as PO.
1708 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1709 try {
1710 dpm.reboot(admin1);
1711 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1712 } catch (SecurityException expected) {
1713 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1714 }
1715
1716 // Remove PO and add DO.
1717 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001718 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001719 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1720
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001721 // admin1 is DO.
1722 // Set current call state of device to ringing.
1723 when(mContext.telephonyManager.getCallState())
1724 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1725 try {
1726 dpm.reboot(admin1);
1727 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1728 } catch (IllegalStateException expected) {
1729 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1730 }
1731
1732 // Set current call state of device to dialing/active.
1733 when(mContext.telephonyManager.getCallState())
1734 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1735 try {
1736 dpm.reboot(admin1);
1737 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1738 } catch (IllegalStateException expected) {
1739 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1740 }
1741
1742 // Set current call state of device to idle.
1743 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001744 dpm.reboot(admin1);
1745 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001746
1747 public void testSetGetSupportText() {
1748 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1749 dpm.setActiveAdmin(admin1, true);
1750 dpm.setActiveAdmin(admin2, true);
1751 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1752
1753 // Null default support messages.
1754 {
1755 assertNull(dpm.getLongSupportMessage(admin1));
1756 assertNull(dpm.getShortSupportMessage(admin1));
1757 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1758 assertNull(dpm.getShortSupportMessageForUser(admin1,
1759 DpmMockContext.CALLER_USER_HANDLE));
1760 assertNull(dpm.getLongSupportMessageForUser(admin1,
1761 DpmMockContext.CALLER_USER_HANDLE));
1762 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1763 }
1764
1765 // Only system can call the per user versions.
1766 {
1767 try {
1768 dpm.getShortSupportMessageForUser(admin1,
1769 DpmMockContext.CALLER_USER_HANDLE);
1770 fail("Only system should be able to call getXXXForUser versions");
1771 } catch (SecurityException expected) {
1772 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1773 }
1774 try {
1775 dpm.getLongSupportMessageForUser(admin1,
1776 DpmMockContext.CALLER_USER_HANDLE);
1777 fail("Only system should be able to call getXXXForUser versions");
1778 } catch (SecurityException expected) {
1779 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1780 }
1781 }
1782
1783 // Can't set message for admin in another uid.
1784 {
1785 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1786 try {
1787 dpm.setShortSupportMessage(admin1, "Some text");
1788 fail("Admins should only be able to change their own support text.");
1789 } catch (SecurityException expected) {
1790 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1791 }
1792 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1793 }
1794
1795 // Set/Get short returns what it sets and other admins text isn't changed.
1796 {
1797 final String supportText = "Some text to test with.";
1798 dpm.setShortSupportMessage(admin1, supportText);
1799 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1800 assertNull(dpm.getLongSupportMessage(admin1));
1801 assertNull(dpm.getShortSupportMessage(admin2));
1802
1803 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1804 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1805 DpmMockContext.CALLER_USER_HANDLE));
1806 assertNull(dpm.getShortSupportMessageForUser(admin2,
1807 DpmMockContext.CALLER_USER_HANDLE));
1808 assertNull(dpm.getLongSupportMessageForUser(admin1,
1809 DpmMockContext.CALLER_USER_HANDLE));
1810 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1811
1812 dpm.setShortSupportMessage(admin1, null);
1813 assertNull(dpm.getShortSupportMessage(admin1));
1814 }
1815
1816 // Set/Get long returns what it sets and other admins text isn't changed.
1817 {
1818 final String supportText = "Some text to test with.\nWith more text.";
1819 dpm.setLongSupportMessage(admin1, supportText);
1820 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1821 assertNull(dpm.getShortSupportMessage(admin1));
1822 assertNull(dpm.getLongSupportMessage(admin2));
1823
1824 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1825 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1826 DpmMockContext.CALLER_USER_HANDLE));
1827 assertNull(dpm.getLongSupportMessageForUser(admin2,
1828 DpmMockContext.CALLER_USER_HANDLE));
1829 assertNull(dpm.getShortSupportMessageForUser(admin1,
1830 DpmMockContext.CALLER_USER_HANDLE));
1831 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1832
1833 dpm.setLongSupportMessage(admin1, null);
1834 assertNull(dpm.getLongSupportMessage(admin1));
1835 }
1836 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001837
1838 /**
1839 * Test for:
1840 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001841 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001842 * {@link DevicePolicyManager#isAffiliatedUser}
1843 */
1844 public void testUserAffiliation() throws Exception {
1845 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1846 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1847 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1848
1849 // Check that the system user is unaffiliated.
1850 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1851 assertFalse(dpm.isAffiliatedUser());
1852
1853 // Set a device owner on the system user. Check that the system user becomes affiliated.
1854 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1855 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1856 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1857 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001858 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001859
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001860 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001861 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1862 setAsProfileOwner(admin2);
1863 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001864 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001865
1866 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1867 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001868 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001869 userAffiliationIds.add("red");
1870 userAffiliationIds.add("green");
1871 userAffiliationIds.add("blue");
1872 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001873 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001874 assertFalse(dpm.isAffiliatedUser());
1875
1876 // Have the device owner specify a set of affiliation ids that do not intersect with those
1877 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001878 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001879 deviceAffiliationIds.add("cyan");
1880 deviceAffiliationIds.add("yellow");
1881 deviceAffiliationIds.add("magenta");
1882 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1883 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001884 MoreAsserts.assertContentsInAnyOrder(
1885 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001886 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1887 assertFalse(dpm.isAffiliatedUser());
1888
1889 // Have the profile owner specify a set of affiliation ids that intersect with those
1890 // specified by the device owner. Check that the test user becomes affiliated.
1891 userAffiliationIds.add("yellow");
1892 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001893 MoreAsserts.assertContentsInAnyOrder(
1894 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001895 assertTrue(dpm.isAffiliatedUser());
1896
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001897 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
1898 dpm.setAffiliationIds(admin2, Collections.emptyList());
1899 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001900 assertFalse(dpm.isAffiliatedUser());
1901
1902 // Check that the system user remains affiliated.
1903 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1904 assertTrue(dpm.isAffiliatedUser());
1905 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001906
1907 public void testGetUserProvisioningState_defaultResult() {
1908 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1909 }
1910
1911 public void testSetUserProvisioningState_permission() throws Exception {
1912 setupProfileOwner();
1913 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1914
1915 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1916 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1917 }
1918
1919 public void testSetUserProvisioningState_unprivileged() throws Exception {
1920 setupProfileOwner();
1921 try {
1922 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1923 DpmMockContext.CALLER_USER_HANDLE);
1924 fail("Expected SecurityException");
1925 } catch (SecurityException expected) {
1926 }
1927 }
1928
1929 public void testSetUserProvisioningState_noManagement() {
1930 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1931 try {
1932 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1933 DpmMockContext.CALLER_USER_HANDLE);
1934 fail("IllegalStateException expected");
1935 } catch (IllegalStateException e) {
1936 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1937 e.getMessage());
1938 }
1939 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1940 }
1941
1942 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1943 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1944 setupDeviceOwner();
1945 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1946
1947 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1948 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1949 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1950 }
1951
1952 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1953 throws Exception {
1954 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1955 setupDeviceOwner();
1956 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1957
1958 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1959 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1960 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1961 }
1962
1963 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1964 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1965 setupDeviceOwner();
1966 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1967
1968 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1969 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1970 }
1971
1972 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1973 throws Exception {
1974 setupProfileOwner();
1975 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1976
1977 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1978 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1979 DevicePolicyManager.STATE_USER_UNMANAGED);
1980 }
1981
1982 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1983 throws Exception {
1984 setupProfileOwner();
1985 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1986
1987 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1988 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1989 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1990 }
1991
1992 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1993 setupProfileOwner();
1994 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1995
1996 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1997 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1998 }
1999
2000 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2001 setupProfileOwner();
2002 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2003
2004 try {
2005 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2006 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2007 DevicePolicyManager.STATE_USER_UNMANAGED);
2008 fail("Expected IllegalStateException");
2009 } catch (IllegalStateException e) {
2010 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2011 e.getMessage());
2012 }
2013 }
2014
2015 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2016 throws Exception {
2017 setupProfileOwner();
2018 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2019
2020 try {
2021 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2022 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2023 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2024 fail("Expected IllegalStateException");
2025 } catch (IllegalStateException e) {
2026 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2027 e.getMessage());
2028 }
2029 }
2030
2031 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2032 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2033 for (int state : states) {
2034 dpm.setUserProvisioningState(state, userId);
2035 assertEquals(state, dpm.getUserProvisioningState());
2036 }
2037 }
2038
2039 private void setupProfileOwner() throws Exception {
2040 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2041
2042 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2043 dpm.setActiveAdmin(admin1, false);
2044 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2045
2046 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2047 }
2048
2049 private void setupDeviceOwner() throws Exception {
2050 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2051
2052 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2053 dpm.setActiveAdmin(admin1, false);
2054 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2055
2056 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2057 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002058
2059 public void testSetMaximumTimeToLock() {
2060 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2061
2062 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2063 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2064
2065 reset(mMockContext.powerManagerInternal);
2066 reset(mMockContext.settings);
2067
2068 dpm.setMaximumTimeToLock(admin1, 0);
2069 verifyScreenTimeoutCall(null, false);
2070 reset(mMockContext.powerManagerInternal);
2071 reset(mMockContext.settings);
2072
2073 dpm.setMaximumTimeToLock(admin1, 1);
2074 verifyScreenTimeoutCall(1, true);
2075 reset(mMockContext.powerManagerInternal);
2076 reset(mMockContext.settings);
2077
2078 dpm.setMaximumTimeToLock(admin2, 10);
2079 verifyScreenTimeoutCall(null, false);
2080 reset(mMockContext.powerManagerInternal);
2081 reset(mMockContext.settings);
2082
2083 dpm.setMaximumTimeToLock(admin1, 5);
2084 verifyScreenTimeoutCall(5, true);
2085 reset(mMockContext.powerManagerInternal);
2086 reset(mMockContext.settings);
2087
2088 dpm.setMaximumTimeToLock(admin2, 4);
2089 verifyScreenTimeoutCall(4, true);
2090 reset(mMockContext.powerManagerInternal);
2091 reset(mMockContext.settings);
2092
2093 dpm.setMaximumTimeToLock(admin1, 0);
2094 reset(mMockContext.powerManagerInternal);
2095 reset(mMockContext.settings);
2096
2097 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2098 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2099 reset(mMockContext.powerManagerInternal);
2100 reset(mMockContext.settings);
2101
2102 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2103 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2104 reset(mMockContext.powerManagerInternal);
2105 reset(mMockContext.settings);
2106
2107 dpm.setMaximumTimeToLock(admin2, 10);
2108 verifyScreenTimeoutCall(10, true);
2109 reset(mMockContext.powerManagerInternal);
2110 reset(mMockContext.settings);
2111
2112 // There's no restriction; shold be set to MAX.
2113 dpm.setMaximumTimeToLock(admin2, 0);
2114 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2115 }
2116
Michal Karpinski943aabd2016-10-06 11:09:25 +01002117 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2118 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2119 setupDeviceOwner();
2120 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2121
Michal Karpinskid084ca52017-01-18 15:54:18 +00002122 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2123 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2124 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2125 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2126 - ONE_MINUTE;
2127
2128 // verify that the minimum timeout cannot be modified on user builds (system property is
2129 // not being read)
2130 mContext.buildMock.isDebuggable = false;
2131
2132 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2133 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2134 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2135
2136 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2137
2138 // restore to the debuggable build state
2139 mContext.buildMock.isDebuggable = true;
2140
2141 // Always return the default (second arg) when getting system property for long type
2142 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2143 new Answer<Long>() {
2144 @Override
2145 public Long answer(InvocationOnMock invocation) throws Throwable {
2146 return (Long) invocation.getArguments()[1];
2147 }
2148 }
2149 );
2150
2151 // reset to default (0 means the admin is not participating, so default should be returned)
2152 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002153
2154 // aggregation should be the default if unset by any admin
2155 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2156 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2157
2158 // admin not participating by default
2159 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2160
2161 //clamping from the top
2162 dpm.setRequiredStrongAuthTimeout(admin1,
2163 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2164 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2165 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2166 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2167 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2168
Michal Karpinskid084ca52017-01-18 15:54:18 +00002169 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002170 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2171 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2172 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2173 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2174
2175 // clamping from the bottom
2176 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2177 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2178 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2179
Michal Karpinskid084ca52017-01-18 15:54:18 +00002180 // values within range
2181 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2182 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2183 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2184
2185 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2186 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2187 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002188
2189 // reset to default
2190 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2191 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2192 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2193 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2194
2195 // negative value
2196 try {
2197 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2198 fail("Didn't throw IllegalArgumentException");
2199 } catch (IllegalArgumentException iae) {
2200 }
2201 }
2202
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002203 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2204 boolean shouldStayOnWhilePluggedInBeCleared) {
2205 if (expectedTimeout == null) {
2206 verify(mMockContext.powerManagerInternal, times(0))
2207 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2208 } else {
2209 verify(mMockContext.powerManagerInternal, times(1))
2210 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2211 }
2212 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2213 // UnfinishedVerificationException.
2214 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002215
Esteban Talavera01576862016-12-15 11:16:44 +00002216 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002217 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2218 .thenReturn(false);
2219 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2220 .thenReturn(false);
2221 initializeDpms();
2222 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2223 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2224 .thenReturn(true);
2225 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2226
2227 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002228 }
Victor Chang3e794af2016-03-04 13:48:17 +00002229
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002230 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2231 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002232 mContext.packageName = admin1.getPackageName();
2233 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002234 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2235 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2236 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2237 false);
2238 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2239 }
2240
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002241 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2242 setup_DeviceAdminFeatureOff();
2243 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2244 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2245 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2246 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2247 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2248 assertCheckProvisioningPreCondition(
2249 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2250 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2251 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2252 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2253 }
2254
Esteban Talavera01576862016-12-15 11:16:44 +00002255 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002256 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2257 .thenReturn(false);
2258 initializeDpms();
2259 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2260 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2261 .thenReturn(true);
2262 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2263
2264 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002265 }
Victor Chang3e794af2016-03-04 13:48:17 +00002266
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002267 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2268 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002269 mContext.packageName = admin1.getPackageName();
2270 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002271 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2272 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2273 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2274 false);
2275 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2276
2277 // Test again when split user is on
2278 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2279 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2280 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2281 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2282 true);
2283 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2284 }
2285
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002286 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2287 setup_ManagedProfileFeatureOff();
2288 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2289 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2290 DevicePolicyManager.CODE_OK);
2291 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2292 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2293 assertCheckProvisioningPreCondition(
2294 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2295 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2296 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2297 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2298
2299 // Test again when split user is on
2300 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2301 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2302 DevicePolicyManager.CODE_OK);
2303 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2304 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2305 assertCheckProvisioningPreCondition(
2306 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2307 DevicePolicyManager.CODE_OK);
2308 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2309 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2310 }
2311
Esteban Talavera01576862016-12-15 11:16:44 +00002312 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002313 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2314 .thenReturn(true);
2315 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2316 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2317 .thenReturn(true);
2318 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2319
2320 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002321 }
Victor Chang3e794af2016-03-04 13:48:17 +00002322
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002323 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2324 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002325 mContext.packageName = admin1.getPackageName();
2326 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002327 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2328 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2329 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2330 false /* because of non-split user */);
2331 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2332 false /* because of non-split user */);
2333 }
2334
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002335 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002336 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002337 setup_nonSplitUser_firstBoot_primaryUser();
2338 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2339 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2340 DevicePolicyManager.CODE_OK);
2341 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2342 DevicePolicyManager.CODE_OK);
2343 assertCheckProvisioningPreCondition(
2344 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2345 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2346 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2347 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2348 }
2349
Esteban Talavera01576862016-12-15 11:16:44 +00002350 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002351 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2352 .thenReturn(true);
2353 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2354 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2355 .thenReturn(true);
2356 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2357
2358 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002359 }
Victor Chang3e794af2016-03-04 13:48:17 +00002360
Nicolas Prevot45d29072017-01-18 16:11:19 +00002361 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2362 setDeviceOwner();
2363 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2364 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2365 }
2366
2367 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2368 setup_nonSplitUser_withDo_primaryUser();
2369 final int MANAGED_PROFILE_USER_ID = 18;
2370 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2371 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2372 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2373 false /* we can't remove a managed profile */)).thenReturn(false);
2374 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2375 true)).thenReturn(true);
2376 }
2377
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002378 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2379 throws Exception {
2380 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002381 mContext.packageName = admin1.getPackageName();
2382 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002383 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2384 false/* because of completed device setup */);
2385 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2386 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2387 false/* because of non-split user */);
2388 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2389 false/* because of non-split user */);
2390 }
2391
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002392 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2393 throws Exception {
2394 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2395 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2396 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2397 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2398 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2399 DevicePolicyManager.CODE_OK);
2400 assertCheckProvisioningPreCondition(
2401 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2402 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2403 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2404 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2405 }
2406
Nicolas Prevot45d29072017-01-18 16:11:19 +00002407 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2408 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002409 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002410 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2411
2412 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2413 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002414 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002415
2416 // COMP mode is allowed.
2417 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2418 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002419 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002420
Nicolas Prevot45d29072017-01-18 16:11:19 +00002421 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002422 assertCheckProvisioningPreCondition(
2423 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002424 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002425 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002426 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2427 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2428 }
Esteban Talavera01576862016-12-15 11:16:44 +00002429
Nicolas Prevot45d29072017-01-18 16:11:19 +00002430 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2431 setup_nonSplitUser_withDo_primaryUser();
2432 mContext.packageName = admin1.getPackageName();
2433 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2434 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2435 // other packages should be forbidden.
Esteban Talavera01576862016-12-15 11:16:44 +00002436 when(mContext.userManager.hasUserRestriction(
2437 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2438 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2439 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002440 when(mContext.userManager.getUserRestrictionSource(
2441 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2442 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2443 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2444 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2445 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002446 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002447 assertCheckProvisioningPreCondition(
2448 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002449 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002450 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002451 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2452 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2453 }
Esteban Talavera01576862016-12-15 11:16:44 +00002454
Nicolas Prevot45d29072017-01-18 16:11:19 +00002455 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2456 throws Exception {
2457 setup_nonSplitUser_withDo_primaryUser();
2458 mContext.packageName = admin1.getPackageName();
2459 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002460 // The DO should not be allowed to initiate provisioning if the restriction is set by
2461 // another entity.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002462 when(mContext.userManager.hasUserRestriction(
2463 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2464 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2465 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002466 when(mContext.userManager.getUserRestrictionSource(
2467 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2468 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2469 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2470 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2471 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002472 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2473
2474 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002475 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002476 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002477 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002478 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2479 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2480 }
2481
2482 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2483 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2484 mContext.packageName = admin1.getPackageName();
2485 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2486
2487 // We can delete the managed profile to create a new one, so provisioning is allowed.
2488 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2489 DevicePolicyManager.CODE_OK);
2490 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2491 assertCheckProvisioningPreCondition(
2492 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2493 DpmMockContext.ANOTHER_PACKAGE_NAME,
2494 DevicePolicyManager.CODE_OK);
2495 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2496 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2497 }
2498
2499 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2500 throws Exception {
2501 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2502 mContext.packageName = admin1.getPackageName();
2503 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2504 when(mContext.userManager.hasUserRestriction(
2505 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2506 eq(UserHandle.SYSTEM)))
2507 .thenReturn(true);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002508 when(mContext.userManager.getUserRestrictionSource(
2509 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2510 eq(UserHandle.SYSTEM)))
2511 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002512
2513 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002514 assertCheckProvisioningPreCondition(
2515 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2516 DpmMockContext.ANOTHER_PACKAGE_NAME,
2517 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2518 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2519 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002520
2521 // But the device owner can still do it because it has set the restriction itself.
2522 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2523 DevicePolicyManager.CODE_OK);
2524 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002525 }
2526
2527 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002528 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2529 .thenReturn(true);
2530 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2531 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2532 .thenReturn(false);
2533 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2534
2535 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002536 }
Victor Chang3e794af2016-03-04 13:48:17 +00002537
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002538 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2539 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002540 mContext.packageName = admin1.getPackageName();
2541 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002542 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2543 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2544 false /* because canAddMoreManagedProfiles returns false */);
2545 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2546 true);
2547 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2548 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002549 }
2550
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002551 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2552 throws Exception {
2553 setup_splitUser_firstBoot_systemUser();
2554 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2555 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2556 DevicePolicyManager.CODE_OK);
2557 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002558 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002559 assertCheckProvisioningPreCondition(
2560 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2561 DevicePolicyManager.CODE_OK);
2562 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2563 DevicePolicyManager.CODE_SYSTEM_USER);
2564 }
2565
Esteban Talavera01576862016-12-15 11:16:44 +00002566 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002567 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2568 .thenReturn(true);
2569 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2570 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2571 .thenReturn(false);
2572 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2573
2574 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002575 }
Victor Chang3e794af2016-03-04 13:48:17 +00002576
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002577 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2578 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002579 mContext.packageName = admin1.getPackageName();
2580 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002581 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2582 true/* it's undefined behavior. Can be changed into false in the future */);
2583 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2584 false /* because canAddMoreManagedProfiles returns false */);
2585 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2586 true/* it's undefined behavior. Can be changed into false in the future */);
2587 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2588 false/* because calling uid is system user */);
2589 }
2590
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002591 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2592 throws Exception {
2593 setup_splitUser_afterDeviceSetup_systemUser();
2594 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2595 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2596 DevicePolicyManager.CODE_OK);
2597 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002598 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002599 assertCheckProvisioningPreCondition(
2600 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2601 DevicePolicyManager.CODE_OK);
2602 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2603 DevicePolicyManager.CODE_SYSTEM_USER);
2604 }
2605
Esteban Talavera01576862016-12-15 11:16:44 +00002606 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002607 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2608 .thenReturn(true);
2609 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2610 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2611 true)).thenReturn(true);
2612 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2613
2614 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002615 }
Victor Chang3e794af2016-03-04 13:48:17 +00002616
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002617 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2618 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002619 mContext.packageName = admin1.getPackageName();
2620 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002621 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2622 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2623 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2624 true);
2625 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002626 }
2627
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002628 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002629 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002630 setup_splitUser_firstBoot_primaryUser();
2631 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2632 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2633 DevicePolicyManager.CODE_OK);
2634 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2635 DevicePolicyManager.CODE_OK);
2636 assertCheckProvisioningPreCondition(
2637 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2638 DevicePolicyManager.CODE_OK);
2639 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2640 DevicePolicyManager.CODE_OK);
2641 }
2642
Esteban Talavera01576862016-12-15 11:16:44 +00002643 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002644 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2645 .thenReturn(true);
2646 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2647 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2648 true)).thenReturn(true);
2649 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2650
2651 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002652 }
Victor Chang3e794af2016-03-04 13:48:17 +00002653
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002654 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2655 throws Exception {
2656 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002657 mContext.packageName = admin1.getPackageName();
2658 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002659 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2660 true/* it's undefined behavior. Can be changed into false in the future */);
2661 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2662 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2663 true/* it's undefined behavior. Can be changed into false in the future */);
2664 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2665 false/* because user setup completed */);
2666 }
2667
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002668 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002669 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002670 setup_splitUser_afterDeviceSetup_primaryUser();
2671 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2672 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2673 DevicePolicyManager.CODE_OK);
2674 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2675 DevicePolicyManager.CODE_OK);
2676 assertCheckProvisioningPreCondition(
2677 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2678 DevicePolicyManager.CODE_OK);
2679 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2680 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2681 }
2682
Esteban Talavera01576862016-12-15 11:16:44 +00002683 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002684 setDeviceOwner();
2685
2686 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2687 .thenReturn(true);
2688 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2689 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2690 .thenReturn(false);
2691 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2692
2693 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002694 }
Victor Chang3e794af2016-03-04 13:48:17 +00002695
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002696 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2697 throws Exception {
2698 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002699 mContext.packageName = admin1.getPackageName();
2700 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002701 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2702 false /* can't provision managed profile on system user */);
2703 }
2704
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002705 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002706 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002707 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2708 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2709 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2710 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2711 }
2712
2713 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002714 setDeviceOwner();
2715
2716 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2717 .thenReturn(true);
2718 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2719 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2720 true)).thenReturn(true);
2721 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2722
2723 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002724 }
Victor Chang3e794af2016-03-04 13:48:17 +00002725
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002726 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2727 throws Exception {
2728 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002729 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2730 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002731 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2732 }
2733
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002734 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002735 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002736 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2737 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002738
2739 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002740 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2741 DevicePolicyManager.CODE_OK);
2742 }
2743
2744 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002745 setDeviceOwner();
2746
2747 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2748 .thenReturn(true);
2749 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002750 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002751 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2752 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002753 .thenReturn(true);
2754 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002755 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002756 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2757 true)).thenReturn(true);
2758 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2759
2760 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002761 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002762
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002763 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2764 throws Exception {
2765 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002766 mContext.packageName = admin1.getPackageName();
2767 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002768 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2769 }
2770
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002771 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2772 throws Exception {
2773 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2774 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2775 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2776 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2777 }
2778
2779 public void testCheckProvisioningPreCondition_permission() {
2780 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2781 try {
Esteban Talavera01576862016-12-15 11:16:44 +00002782 dpm.checkProvisioningPreCondition(
2783 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002784 fail("Didn't throw SecurityException");
2785 } catch (SecurityException expected) {
2786 }
2787 }
2788
Victor Chang3577ed22016-08-25 18:49:26 +01002789 public void testForceUpdateUserSetupComplete_permission() {
2790 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2791 try {
2792 dpm.forceUpdateUserSetupComplete();
2793 fail("Didn't throw SecurityException");
2794 } catch (SecurityException expected) {
2795 }
2796 }
2797
2798 public void testForceUpdateUserSetupComplete_systemUser() {
2799 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2800 // GIVEN calling from user 20
2801 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2802 try {
2803 dpm.forceUpdateUserSetupComplete();
2804 fail("Didn't throw SecurityException");
2805 } catch (SecurityException expected) {
2806 }
2807 }
2808
2809 public void testForceUpdateUserSetupComplete_userbuild() {
2810 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2811 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2812
2813 final int userId = UserHandle.USER_SYSTEM;
2814 // GIVEN userComplete is false in SettingsProvider
2815 setUserSetupCompleteForUser(false, userId);
2816
2817 // GIVEN userComplete is true in DPM
2818 DevicePolicyManagerService.DevicePolicyData userData =
2819 new DevicePolicyManagerService.DevicePolicyData(userId);
2820 userData.mUserSetupComplete = true;
2821 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2822
2823 // GIVEN it's user build
2824 mContext.buildMock.isDebuggable = false;
2825
2826 assertTrue(dpms.hasUserSetupCompleted());
2827
2828 dpm.forceUpdateUserSetupComplete();
2829
2830 // THEN the state in dpms is not changed
2831 assertTrue(dpms.hasUserSetupCompleted());
2832 }
2833
2834 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2835 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2836 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2837
2838 final int userId = UserHandle.USER_SYSTEM;
2839 // GIVEN userComplete is false in SettingsProvider
2840 setUserSetupCompleteForUser(false, userId);
2841
2842 // GIVEN userComplete is true in DPM
2843 DevicePolicyManagerService.DevicePolicyData userData =
2844 new DevicePolicyManagerService.DevicePolicyData(userId);
2845 userData.mUserSetupComplete = true;
2846 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2847
2848 // GIVEN it's userdebug build
2849 mContext.buildMock.isDebuggable = true;
2850
2851 assertTrue(dpms.hasUserSetupCompleted());
2852
2853 dpm.forceUpdateUserSetupComplete();
2854
2855 // THEN the state in dpms is not changed
2856 assertFalse(dpms.hasUserSetupCompleted());
2857 }
2858
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002859 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002860 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002861 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2862 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2863 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2864 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002865 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002866 }
2867
2868 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2869 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2870 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002871
2872 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2873 // feature is disabled because there are non-affiliated secondary users.
2874 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002875 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2876 .thenReturn(true);
2877
2878 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002879 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002880
2881 // Enabling logging should not change the timestamp.
2882 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00002883 verify(mContext.settings)
2884 .securityLogSetLoggingEnabledProperty(true);
2885 when(mContext.settings.securityLogGetLoggingEnabledProperty())
2886 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002887 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002888
2889 // Retrieving the logs should update the timestamp.
2890 final long beforeRetrieval = System.currentTimeMillis();
2891 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002892 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002893 final long afterRetrieval = System.currentTimeMillis();
2894 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2895 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2896
2897 // Retrieving the pre-boot logs should update the timestamp.
2898 Thread.sleep(2);
2899 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002900 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002901 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2902
2903 // Checking the timestamp again should not change it.
2904 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002905 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002906
2907 // Retrieving the logs again should update the timestamp.
2908 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002909 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002910 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2911
2912 // Disabling logging should not change the timestamp.
2913 Thread.sleep(2);
2914 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002915 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002916
2917 // Restarting the DPMS should not lose the timestamp.
2918 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002919 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002920
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002921 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2922 mContext.binder.callingUid = 1234567;
2923 mContext.callerPermissions.add(permission.MANAGE_USERS);
2924 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2925 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2926
2927 // System can retrieve the timestamp.
2928 mContext.binder.clearCallingIdentity();
2929 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2930
2931 // Removing the device owner should clear the timestamp.
2932 clearDeviceOwner();
2933 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002934 }
2935
2936 public void testGetLastBugReportRequestTime() throws Exception {
2937 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2938 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002939
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002940 mContext.packageName = admin1.getPackageName();
2941 mContext.applicationInfo = new ApplicationInfo();
2942 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2943 .thenReturn(Color.WHITE);
2944 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2945 anyObject())).thenReturn(Color.WHITE);
2946
Esteban Talaverad36dd152016-12-15 08:51:45 +00002947 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2948 // feature is disabled because there are non-affiliated secondary users.
2949 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
2950
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002951 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002952 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002953
2954 // Requesting a bug report should update the timestamp.
2955 final long beforeRequest = System.currentTimeMillis();
2956 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002957 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002958 final long afterRequest = System.currentTimeMillis();
2959 assertTrue(bugReportRequestTime >= beforeRequest);
2960 assertTrue(bugReportRequestTime <= afterRequest);
2961
2962 // Checking the timestamp again should not change it.
2963 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002964 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002965
2966 // Restarting the DPMS should not lose the timestamp.
2967 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002968 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002969
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002970 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2971 mContext.binder.callingUid = 1234567;
2972 mContext.callerPermissions.add(permission.MANAGE_USERS);
2973 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2974 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2975
2976 // System can retrieve the timestamp.
2977 mContext.binder.clearCallingIdentity();
2978 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2979
2980 // Removing the device owner should clear the timestamp.
2981 clearDeviceOwner();
2982 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002983 }
2984
2985 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2986 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2987 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002988 mContext.packageName = admin1.getPackageName();
2989 mContext.applicationInfo = new ApplicationInfo();
2990 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2991 .thenReturn(Color.WHITE);
2992 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2993 anyObject())).thenReturn(Color.WHITE);
2994
2995 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2996 // feature is disabled because there are non-affiliated secondary users.
2997 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002998 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2999 .thenReturn(true);
3000
3001 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003002 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003003
3004 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3005 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003006 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003007
3008 // Enabling logging should not change the timestamp.
3009 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003010 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003011
3012 // Retrieving the logs should update the timestamp.
3013 final long beforeRetrieval = System.currentTimeMillis();
3014 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003015 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003016 final long afterRetrieval = System.currentTimeMillis();
3017 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3018 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3019
3020 // Checking the timestamp again should not change it.
3021 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003022 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003023
3024 // Retrieving the logs again should update the timestamp.
3025 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003026 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003027 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3028
3029 // Disabling logging should not change the timestamp.
3030 Thread.sleep(2);
3031 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003032 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003033
3034 // Restarting the DPMS should not lose the timestamp.
3035 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003036 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3037
3038 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3039 mContext.binder.callingUid = 1234567;
3040 mContext.callerPermissions.add(permission.MANAGE_USERS);
3041 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3042 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3043
3044 // System can retrieve the timestamp.
3045 mContext.binder.clearCallingIdentity();
3046 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3047
3048 // Removing the device owner should clear the timestamp.
3049 clearDeviceOwner();
3050 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003051 }
3052
Tony Mak2f26b792016-11-28 17:54:51 +00003053 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3054 // Setup device owner.
3055 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3056 setupDeviceOwner();
3057
3058 // Only device owner is setup, the result list should be empty.
3059 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3060 MoreAsserts.assertEmpty(targetUsers);
3061
3062 // Setup a managed profile managed by the same admin.
3063 final int MANAGED_PROFILE_USER_ID = 15;
3064 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3065 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3066
3067 // Add a secondary user, it should never talk with.
3068 final int ANOTHER_USER_ID = 36;
3069 mContext.addUser(ANOTHER_USER_ID, 0);
3070
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003071 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3072 // other.
3073 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3074 MoreAsserts.assertEmpty(targetUsers);
3075
3076 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3077 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3078 MoreAsserts.assertEmpty(targetUsers);
3079
3080 // Setting affiliation ids
3081 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3082 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3083 dpm.setAffiliationIds(admin1, userAffiliationIds);
3084
3085 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3086 dpm.setAffiliationIds(admin1, userAffiliationIds);
3087
Tony Mak2f26b792016-11-28 17:54:51 +00003088 // Calling from device owner admin, the result list should just contain the managed
3089 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003090 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003091 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3092 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3093
3094 // Calling from managed profile admin, the result list should just contain the system
3095 // user id.
3096 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3097 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3098 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003099
3100 // Changing affiliation ids in one
3101 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3102
3103 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3104 // to each other.
3105 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3106 MoreAsserts.assertEmpty(targetUsers);
3107
3108 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3109 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3110 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003111 }
3112
3113 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3114 // Setup a device owner.
3115 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3116 setupDeviceOwner();
3117
3118 // Set up a managed profile managed by different package.
3119 final int MANAGED_PROFILE_USER_ID = 15;
3120 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3121 final ComponentName adminDifferentPackage =
3122 new ComponentName("another.package", "whatever.class");
3123 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3124
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003125 // Setting affiliation ids
3126 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3127 dpm.setAffiliationIds(admin1, userAffiliationIds);
3128
3129 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3130 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3131
Tony Mak2f26b792016-11-28 17:54:51 +00003132 // Calling from device owner admin, we should get zero bind device admin target users as
3133 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003134 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003135 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3136 MoreAsserts.assertEmpty(targetUsers);
3137
3138 // Calling from managed profile admin, we should still get zero target users for the same
3139 // reason.
3140 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3141 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3142 MoreAsserts.assertEmpty(targetUsers);
3143 }
3144
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003145 public void testIsDeviceManaged() throws Exception {
3146 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3147 setupDeviceOwner();
3148
3149 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3150 // find out that the device has a device owner.
3151 assertTrue(dpm.isDeviceManaged());
3152 mContext.binder.callingUid = 1234567;
3153 mContext.callerPermissions.add(permission.MANAGE_USERS);
3154 assertTrue(dpm.isDeviceManaged());
3155 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3156 mContext.binder.clearCallingIdentity();
3157 assertTrue(dpm.isDeviceManaged());
3158
3159 clearDeviceOwner();
3160
3161 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3162 // not have a device owner.
3163 mContext.binder.callingUid = 1234567;
3164 mContext.callerPermissions.add(permission.MANAGE_USERS);
3165 assertFalse(dpm.isDeviceManaged());
3166 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3167 mContext.binder.clearCallingIdentity();
3168 assertFalse(dpm.isDeviceManaged());
3169 }
3170
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003171 public void testDeviceOwnerOrganizationName() throws Exception {
3172 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3173 setupDeviceOwner();
3174
3175 dpm.setOrganizationName(admin1, "organization");
3176
3177 // Device owner can retrieve organization managing the device.
3178 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3179
3180 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3181 mContext.binder.callingUid = 1234567;
3182 mContext.callerPermissions.add(permission.MANAGE_USERS);
3183 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3184 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3185
3186 // System can retrieve organization managing the device.
3187 mContext.binder.clearCallingIdentity();
3188 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3189
3190 // Removing the device owner clears the organization managing the device.
3191 clearDeviceOwner();
3192 assertNull(dpm.getDeviceOwnerOrganizationName());
3193 }
3194
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003195 public void testWipeDataManagedProfile() throws Exception {
3196 final int MANAGED_PROFILE_USER_ID = 15;
3197 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3198 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3199 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3200
3201 // Even if the caller is the managed profile, the current user is the user 0
3202 when(mContext.iactivityManager.getCurrentUser())
3203 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3204
3205 dpm.wipeData(0);
3206 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3207 MANAGED_PROFILE_USER_ID);
3208 }
3209
3210 public void testWipeDataManagedProfileDisallowed() throws Exception {
3211 final int MANAGED_PROFILE_USER_ID = 15;
3212 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3213 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3214
3215 // Even if the caller is the managed profile, the current user is the user 0
3216 when(mContext.iactivityManager.getCurrentUser())
3217 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3218
3219 when(mContext.userManager.getUserRestrictionSource(
3220 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3221 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3222 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3223 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3224 try {
3225 // The PO is not allowed to remove the profile if the user restriction was set on the
3226 // profile by the system
3227 dpm.wipeData(0);
3228 fail("SecurityException not thrown");
3229 } catch (SecurityException expected) {
3230 }
3231 }
3232
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003233 public void testGetPermissionGrantState() throws Exception {
3234 final String permission = "some.permission";
3235 final String app1 = "com.example.app1";
3236 final String app2 = "com.example.app2";
3237
3238 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3239 .thenReturn(PackageManager.PERMISSION_GRANTED);
3240 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3241 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3242 when(mContext.packageManager.getPermissionFlags(permission, app1,
3243 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3244 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3245 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3246 .thenReturn(PackageManager.PERMISSION_DENIED);
3247 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3248 UserHandle.SYSTEM);
3249 when(mContext.packageManager.getPermissionFlags(permission, app2,
3250 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3251
3252 // System can retrieve permission grant state.
3253 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3254 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3255 dpm.getPermissionGrantState(null, app1, permission));
3256 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3257 dpm.getPermissionGrantState(null, app2, permission));
3258
3259 // A regular app cannot retrieve permission grant state.
3260 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
3261 try {
3262 dpm.getPermissionGrantState(null, app1, permission);
3263 fail("Didn't throw IllegalStateException");
3264 } catch (IllegalStateException expected) {
3265 }
3266
3267 // Profile owner can retrieve permission grant state.
3268 setAsProfileOwner(admin1);
3269 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3270 dpm.getPermissionGrantState(admin1, app1, permission));
3271 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3272 dpm.getPermissionGrantState(admin1, app2, permission));
3273 }
3274
Victor Chang3e794af2016-03-04 13:48:17 +00003275 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
3276 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
3277 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
3278 dpms.notifyChangeToContentObserver(
3279 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
3280 }
3281
3282 private void assertProvisioningAllowed(String action, boolean expected) {
3283 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
3284 dpm.isProvisioningAllowed(action));
3285 }
Tony Mak2f26b792016-11-28 17:54:51 +00003286
Nicolas Prevot45d29072017-01-18 16:11:19 +00003287 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
3288 int uid) {
3289 String previousPackageName = mContext.packageName;
3290 int previousUid = mMockContext.binder.callingUid;
3291
3292 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
3293 mContext.packageName = packageName;
3294 mMockContext.binder.callingUid = uid;
3295 assertProvisioningAllowed(action, expected);
3296
3297 // Set the previous package name / calling uid to go back to the initial state.
3298 mContext.packageName = previousPackageName;
3299 mMockContext.binder.callingUid = previousUid;
3300 }
3301
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003302 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00003303 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
3304 }
3305
3306 private void assertCheckProvisioningPreCondition(
3307 String action, String packageName, int provisioningCondition) {
3308 assertEquals("checkProvisioningPreCondition("
3309 + action + ", " + packageName + ") returning unexpected result",
3310 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003311 }
3312
Tony Mak2f26b792016-11-28 17:54:51 +00003313 /**
3314 * Setup a managed profile with the specified admin and its uid.
3315 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
3316 * @param adminUid uid of the admin package.
3317 * @param copyFromAdmin package information for {@code admin} will be built based on this
3318 * component's information.
3319 */
3320 private void addManagedProfile(
3321 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
3322 final int userId = UserHandle.getUserId(adminUid);
3323 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
3324 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3325 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
3326 dpm.setActiveAdmin(admin, false, userId);
3327 assertTrue(dpm.setProfileOwner(admin, null, userId));
3328 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3329 }
Victor Chang3e794af2016-03-04 13:48:17 +00003330}