blob: 8da47c8b7408386832c1125133b50308c5b2927e [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
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002361 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2362 throws Exception {
2363 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002364 mContext.packageName = admin1.getPackageName();
2365 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002366 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2367 false/* because of completed device setup */);
2368 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2369 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2370 false/* because of non-split user */);
2371 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2372 false/* because of non-split user */);
2373 }
2374
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002375 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2376 throws Exception {
2377 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2378 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2379 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2380 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2381 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2382 DevicePolicyManager.CODE_OK);
2383 assertCheckProvisioningPreCondition(
2384 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2385 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2386 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2387 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2388 }
2389
Esteban Talavera01576862016-12-15 11:16:44 +00002390 public void testIsProvisioningAllowed_nonSplitUser_withDo_primaryUser() throws Exception {
2391 setDeviceOwner();
2392 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2393 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2394 mContext.packageName = admin1.getPackageName();
2395
Nicolas Prevotc3bd7b72017-01-10 11:32:43 +00002396 final ComponentName adminDifferentPackage =
2397 new ComponentName("another.package", "whatever.random.class");
2398 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 948);
2399 setUpPackageManagerForFakeAdmin(adminDifferentPackage, ANOTHER_UID, admin2);
2400
Esteban Talavera01576862016-12-15 11:16:44 +00002401 // COMP mode is allowed.
2402 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2403
2404 when(mContext.userManager.hasUserRestriction(
2405 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2406 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2407 .thenReturn(true);
2408
2409 // The DO should be allowed to initiate provisioning if it set the restriction itself.
2410 when(mContext.userManager.getUserRestrictionSource(
2411 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2412 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2413 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2414 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2415
Nicolas Prevotc3bd7b72017-01-10 11:32:43 +00002416 // But another app should not
2417 mContext.binder.callingUid = ANOTHER_UID;
2418 mContext.packageName = adminDifferentPackage.getPackageName();
2419 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2420
Esteban Talavera01576862016-12-15 11:16:44 +00002421 // The DO should not be allowed to initiate provisioning if the restriction is set by
2422 // another entity.
2423 when(mContext.userManager.getUserRestrictionSource(
2424 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2425 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2426 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
Nicolas Prevotc3bd7b72017-01-10 11:32:43 +00002427 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2428 mContext.packageName = admin1.getPackageName();
2429 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2430
2431 mContext.binder.callingUid = ANOTHER_UID;
2432 mContext.packageName = adminDifferentPackage.getPackageName();
2433 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2434 }
2435
2436 public void testIsProvisioningAllowed_nonSplitUser_comp() throws Exception {
2437 setDeviceOwner();
2438 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2439 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2440
2441 final ComponentName adminDifferentPackage =
2442 new ComponentName("another.package", "whatever.class");
2443 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 948);
2444 setUpPackageManagerForFakeAdmin(adminDifferentPackage, ANOTHER_UID, admin2);
2445
2446 final int MANAGED_PROFILE_USER_ID = 18;
2447 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2448 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2449
2450 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2451 false /* we can't remove a managed profile */)).thenReturn(false);
2452 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2453 true)).thenReturn(true);
2454
2455 // We can delete the managed profile to create a new one, so provisioning is allowed.
2456 mContext.packageName = admin1.getPackageName();
2457 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2458 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2459
2460 mContext.packageName = adminDifferentPackage.getPackageName();
2461 mContext.binder.callingUid = ANOTHER_UID;
2462 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2463
2464 when(mContext.userManager.hasUserRestriction(
2465 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2466 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
2467 .thenReturn(true);
2468
2469 // Now, we can't remove the profile any more to create a new one.
2470 mContext.packageName = admin1.getPackageName();
2471 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2472 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2473
2474 mContext.packageName = adminDifferentPackage.getPackageName();
2475 mContext.binder.callingUid = ANOTHER_UID;
Esteban Talavera01576862016-12-15 11:16:44 +00002476 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2477 }
2478
2479 public void
2480 testCheckProvisioningPreCondition_nonSplitUser_withDo_primaryUser() throws Exception {
2481 setDeviceOwner();
2482 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2483 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2484
2485 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2486 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
2487
2488 // COMP mode is allowed.
2489 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2490 DevicePolicyManager.CODE_OK);
2491
2492 // And other DPCs can also provisioning a managed profile (DO + BYOD case).
2493 assertCheckProvisioningPreCondition(
2494 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2495 "some.other.dpc.package.name",
2496 DevicePolicyManager.CODE_OK);
2497
2498 when(mContext.userManager.hasUserRestriction(
2499 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2500 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2501 .thenReturn(true);
2502
2503 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2504 // other packages should be forbidden.
2505 when(mContext.userManager.getUserRestrictionSource(
2506 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2507 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2508 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2509 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2510 DevicePolicyManager.CODE_OK);
2511 assertCheckProvisioningPreCondition(
2512 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2513 "some.other.dpc.package.name",
2514 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2515
2516 // The DO should not be allowed to initiate provisioning if the restriction is set by
2517 // another entity.
2518 when(mContext.userManager.getUserRestrictionSource(
2519 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2520 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2521 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2522 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2523 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2524 assertCheckProvisioningPreCondition(
2525 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2526 "some.other.dpc.package.name",
2527 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2528 }
2529
2530 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002531 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2532 .thenReturn(true);
2533 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2534 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2535 .thenReturn(false);
2536 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2537
2538 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002539 }
Victor Chang3e794af2016-03-04 13:48:17 +00002540
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002541 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2542 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002543 mContext.packageName = admin1.getPackageName();
2544 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002545 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2546 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2547 false /* because canAddMoreManagedProfiles returns false */);
2548 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2549 true);
2550 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2551 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002552 }
2553
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002554 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2555 throws Exception {
2556 setup_splitUser_firstBoot_systemUser();
2557 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2558 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2559 DevicePolicyManager.CODE_OK);
2560 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002561 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002562 assertCheckProvisioningPreCondition(
2563 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2564 DevicePolicyManager.CODE_OK);
2565 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2566 DevicePolicyManager.CODE_SYSTEM_USER);
2567 }
2568
Esteban Talavera01576862016-12-15 11:16:44 +00002569 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002570 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2571 .thenReturn(true);
2572 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2573 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2574 .thenReturn(false);
2575 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2576
2577 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002578 }
Victor Chang3e794af2016-03-04 13:48:17 +00002579
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002580 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2581 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002582 mContext.packageName = admin1.getPackageName();
2583 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002584 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2585 true/* it's undefined behavior. Can be changed into false in the future */);
2586 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2587 false /* because canAddMoreManagedProfiles returns false */);
2588 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2589 true/* it's undefined behavior. Can be changed into false in the future */);
2590 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2591 false/* because calling uid is system user */);
2592 }
2593
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002594 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2595 throws Exception {
2596 setup_splitUser_afterDeviceSetup_systemUser();
2597 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2598 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2599 DevicePolicyManager.CODE_OK);
2600 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002601 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002602 assertCheckProvisioningPreCondition(
2603 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2604 DevicePolicyManager.CODE_OK);
2605 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2606 DevicePolicyManager.CODE_SYSTEM_USER);
2607 }
2608
Esteban Talavera01576862016-12-15 11:16:44 +00002609 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002610 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2611 .thenReturn(true);
2612 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2613 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2614 true)).thenReturn(true);
2615 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2616
2617 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002618 }
Victor Chang3e794af2016-03-04 13:48:17 +00002619
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002620 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2621 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002622 mContext.packageName = admin1.getPackageName();
2623 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002624 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2625 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2626 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2627 true);
2628 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002629 }
2630
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002631 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002632 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002633 setup_splitUser_firstBoot_primaryUser();
2634 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2635 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2636 DevicePolicyManager.CODE_OK);
2637 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2638 DevicePolicyManager.CODE_OK);
2639 assertCheckProvisioningPreCondition(
2640 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2641 DevicePolicyManager.CODE_OK);
2642 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2643 DevicePolicyManager.CODE_OK);
2644 }
2645
Esteban Talavera01576862016-12-15 11:16:44 +00002646 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002647 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2648 .thenReturn(true);
2649 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2650 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2651 true)).thenReturn(true);
2652 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2653
2654 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002655 }
Victor Chang3e794af2016-03-04 13:48:17 +00002656
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002657 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2658 throws Exception {
2659 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002660 mContext.packageName = admin1.getPackageName();
2661 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002662 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2663 true/* it's undefined behavior. Can be changed into false in the future */);
2664 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2665 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2666 true/* it's undefined behavior. Can be changed into false in the future */);
2667 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2668 false/* because user setup completed */);
2669 }
2670
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002671 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002672 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002673 setup_splitUser_afterDeviceSetup_primaryUser();
2674 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2675 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2676 DevicePolicyManager.CODE_OK);
2677 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2678 DevicePolicyManager.CODE_OK);
2679 assertCheckProvisioningPreCondition(
2680 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2681 DevicePolicyManager.CODE_OK);
2682 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2683 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2684 }
2685
Esteban Talavera01576862016-12-15 11:16:44 +00002686 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002687 setDeviceOwner();
2688
2689 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2690 .thenReturn(true);
2691 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2692 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2693 .thenReturn(false);
2694 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2695
2696 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002697 }
Victor Chang3e794af2016-03-04 13:48:17 +00002698
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002699 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2700 throws Exception {
2701 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002702 mContext.packageName = admin1.getPackageName();
2703 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002704 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2705 false /* can't provision managed profile on system user */);
2706 }
2707
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002708 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002709 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002710 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2711 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2712 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2713 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2714 }
2715
2716 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002717 setDeviceOwner();
2718
2719 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2720 .thenReturn(true);
2721 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2722 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2723 true)).thenReturn(true);
2724 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2725
2726 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002727 }
Victor Chang3e794af2016-03-04 13:48:17 +00002728
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002729 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2730 throws Exception {
2731 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002732 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2733 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002734 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2735 }
2736
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002737 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002738 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002739 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2740 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002741
2742 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002743 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2744 DevicePolicyManager.CODE_OK);
2745 }
2746
2747 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002748 setDeviceOwner();
2749
2750 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2751 .thenReturn(true);
2752 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002753 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002754 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2755 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002756 .thenReturn(true);
2757 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002758 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002759 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2760 true)).thenReturn(true);
2761 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2762
2763 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002764 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002765
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002766 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2767 throws Exception {
2768 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002769 mContext.packageName = admin1.getPackageName();
2770 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002771 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2772 }
2773
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002774 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2775 throws Exception {
2776 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2777 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2778 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2779 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2780 }
2781
2782 public void testCheckProvisioningPreCondition_permission() {
2783 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2784 try {
Esteban Talavera01576862016-12-15 11:16:44 +00002785 dpm.checkProvisioningPreCondition(
2786 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002787 fail("Didn't throw SecurityException");
2788 } catch (SecurityException expected) {
2789 }
2790 }
2791
Victor Chang3577ed22016-08-25 18:49:26 +01002792 public void testForceUpdateUserSetupComplete_permission() {
2793 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2794 try {
2795 dpm.forceUpdateUserSetupComplete();
2796 fail("Didn't throw SecurityException");
2797 } catch (SecurityException expected) {
2798 }
2799 }
2800
2801 public void testForceUpdateUserSetupComplete_systemUser() {
2802 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2803 // GIVEN calling from user 20
2804 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2805 try {
2806 dpm.forceUpdateUserSetupComplete();
2807 fail("Didn't throw SecurityException");
2808 } catch (SecurityException expected) {
2809 }
2810 }
2811
2812 public void testForceUpdateUserSetupComplete_userbuild() {
2813 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2814 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2815
2816 final int userId = UserHandle.USER_SYSTEM;
2817 // GIVEN userComplete is false in SettingsProvider
2818 setUserSetupCompleteForUser(false, userId);
2819
2820 // GIVEN userComplete is true in DPM
2821 DevicePolicyManagerService.DevicePolicyData userData =
2822 new DevicePolicyManagerService.DevicePolicyData(userId);
2823 userData.mUserSetupComplete = true;
2824 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2825
2826 // GIVEN it's user build
2827 mContext.buildMock.isDebuggable = false;
2828
2829 assertTrue(dpms.hasUserSetupCompleted());
2830
2831 dpm.forceUpdateUserSetupComplete();
2832
2833 // THEN the state in dpms is not changed
2834 assertTrue(dpms.hasUserSetupCompleted());
2835 }
2836
2837 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2838 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2839 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2840
2841 final int userId = UserHandle.USER_SYSTEM;
2842 // GIVEN userComplete is false in SettingsProvider
2843 setUserSetupCompleteForUser(false, userId);
2844
2845 // GIVEN userComplete is true in DPM
2846 DevicePolicyManagerService.DevicePolicyData userData =
2847 new DevicePolicyManagerService.DevicePolicyData(userId);
2848 userData.mUserSetupComplete = true;
2849 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2850
2851 // GIVEN it's userdebug build
2852 mContext.buildMock.isDebuggable = true;
2853
2854 assertTrue(dpms.hasUserSetupCompleted());
2855
2856 dpm.forceUpdateUserSetupComplete();
2857
2858 // THEN the state in dpms is not changed
2859 assertFalse(dpms.hasUserSetupCompleted());
2860 }
2861
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002862 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002863 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2865 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2866 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2867 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002868 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002869 }
2870
2871 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2872 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2873 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002874
2875 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2876 // feature is disabled because there are non-affiliated secondary users.
2877 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002878 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2879 .thenReturn(true);
2880
2881 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002882 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002883
2884 // Enabling logging should not change the timestamp.
2885 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00002886 verify(mContext.settings)
2887 .securityLogSetLoggingEnabledProperty(true);
2888 when(mContext.settings.securityLogGetLoggingEnabledProperty())
2889 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002890 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002891
2892 // Retrieving the logs should update the timestamp.
2893 final long beforeRetrieval = System.currentTimeMillis();
2894 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002895 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002896 final long afterRetrieval = System.currentTimeMillis();
2897 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2898 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2899
2900 // Retrieving the pre-boot logs should update the timestamp.
2901 Thread.sleep(2);
2902 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002903 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002904 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2905
2906 // Checking the timestamp again should not change it.
2907 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002908 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002909
2910 // Retrieving the logs again should update the timestamp.
2911 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002912 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002913 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2914
2915 // Disabling logging should not change the timestamp.
2916 Thread.sleep(2);
2917 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002918 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002919
2920 // Restarting the DPMS should not lose the timestamp.
2921 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002922 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002923
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002924 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2925 mContext.binder.callingUid = 1234567;
2926 mContext.callerPermissions.add(permission.MANAGE_USERS);
2927 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2928 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2929
2930 // System can retrieve the timestamp.
2931 mContext.binder.clearCallingIdentity();
2932 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2933
2934 // Removing the device owner should clear the timestamp.
2935 clearDeviceOwner();
2936 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002937 }
2938
2939 public void testGetLastBugReportRequestTime() throws Exception {
2940 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2941 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002942
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002943 mContext.packageName = admin1.getPackageName();
2944 mContext.applicationInfo = new ApplicationInfo();
2945 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2946 .thenReturn(Color.WHITE);
2947 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2948 anyObject())).thenReturn(Color.WHITE);
2949
Esteban Talaverad36dd152016-12-15 08:51:45 +00002950 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2951 // feature is disabled because there are non-affiliated secondary users.
2952 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
2953
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002954 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002955 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002956
2957 // Requesting a bug report should update the timestamp.
2958 final long beforeRequest = System.currentTimeMillis();
2959 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002960 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002961 final long afterRequest = System.currentTimeMillis();
2962 assertTrue(bugReportRequestTime >= beforeRequest);
2963 assertTrue(bugReportRequestTime <= afterRequest);
2964
2965 // Checking the timestamp again should not change it.
2966 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002967 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002968
2969 // Restarting the DPMS should not lose the timestamp.
2970 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002971 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002972
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002973 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2974 mContext.binder.callingUid = 1234567;
2975 mContext.callerPermissions.add(permission.MANAGE_USERS);
2976 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2977 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2978
2979 // System can retrieve the timestamp.
2980 mContext.binder.clearCallingIdentity();
2981 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2982
2983 // Removing the device owner should clear the timestamp.
2984 clearDeviceOwner();
2985 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002986 }
2987
2988 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2989 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2990 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002991 mContext.packageName = admin1.getPackageName();
2992 mContext.applicationInfo = new ApplicationInfo();
2993 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2994 .thenReturn(Color.WHITE);
2995 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2996 anyObject())).thenReturn(Color.WHITE);
2997
2998 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2999 // feature is disabled because there are non-affiliated secondary users.
3000 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003001 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3002 .thenReturn(true);
3003
3004 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003005 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003006
3007 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3008 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003009 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003010
3011 // Enabling logging should not change the timestamp.
3012 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003013 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003014
3015 // Retrieving the logs should update the timestamp.
3016 final long beforeRetrieval = System.currentTimeMillis();
3017 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003018 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003019 final long afterRetrieval = System.currentTimeMillis();
3020 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3021 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3022
3023 // Checking the timestamp again should not change it.
3024 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003025 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003026
3027 // Retrieving the logs again should update the timestamp.
3028 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003029 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003030 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3031
3032 // Disabling logging should not change the timestamp.
3033 Thread.sleep(2);
3034 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003035 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003036
3037 // Restarting the DPMS should not lose the timestamp.
3038 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003039 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3040
3041 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3042 mContext.binder.callingUid = 1234567;
3043 mContext.callerPermissions.add(permission.MANAGE_USERS);
3044 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3045 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3046
3047 // System can retrieve the timestamp.
3048 mContext.binder.clearCallingIdentity();
3049 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3050
3051 // Removing the device owner should clear the timestamp.
3052 clearDeviceOwner();
3053 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003054 }
3055
Tony Mak2f26b792016-11-28 17:54:51 +00003056 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3057 // Setup device owner.
3058 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3059 setupDeviceOwner();
3060
3061 // Only device owner is setup, the result list should be empty.
3062 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3063 MoreAsserts.assertEmpty(targetUsers);
3064
3065 // Setup a managed profile managed by the same admin.
3066 final int MANAGED_PROFILE_USER_ID = 15;
3067 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3068 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3069
3070 // Add a secondary user, it should never talk with.
3071 final int ANOTHER_USER_ID = 36;
3072 mContext.addUser(ANOTHER_USER_ID, 0);
3073
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003074 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3075 // other.
3076 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3077 MoreAsserts.assertEmpty(targetUsers);
3078
3079 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3080 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3081 MoreAsserts.assertEmpty(targetUsers);
3082
3083 // Setting affiliation ids
3084 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3085 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3086 dpm.setAffiliationIds(admin1, userAffiliationIds);
3087
3088 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3089 dpm.setAffiliationIds(admin1, userAffiliationIds);
3090
Tony Mak2f26b792016-11-28 17:54:51 +00003091 // Calling from device owner admin, the result list should just contain the managed
3092 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003093 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003094 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3095 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3096
3097 // Calling from managed profile admin, the result list should just contain the system
3098 // user id.
3099 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3100 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3101 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003102
3103 // Changing affiliation ids in one
3104 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3105
3106 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3107 // to each other.
3108 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3109 MoreAsserts.assertEmpty(targetUsers);
3110
3111 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3112 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3113 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003114 }
3115
3116 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3117 // Setup a device owner.
3118 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3119 setupDeviceOwner();
3120
3121 // Set up a managed profile managed by different package.
3122 final int MANAGED_PROFILE_USER_ID = 15;
3123 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3124 final ComponentName adminDifferentPackage =
3125 new ComponentName("another.package", "whatever.class");
3126 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3127
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003128 // Setting affiliation ids
3129 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3130 dpm.setAffiliationIds(admin1, userAffiliationIds);
3131
3132 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3133 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3134
Tony Mak2f26b792016-11-28 17:54:51 +00003135 // Calling from device owner admin, we should get zero bind device admin target users as
3136 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003137 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003138 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3139 MoreAsserts.assertEmpty(targetUsers);
3140
3141 // Calling from managed profile admin, we should still get zero target users for the same
3142 // reason.
3143 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3144 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3145 MoreAsserts.assertEmpty(targetUsers);
3146 }
3147
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003148 public void testIsDeviceManaged() throws Exception {
3149 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3150 setupDeviceOwner();
3151
3152 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3153 // find out that the device has a device owner.
3154 assertTrue(dpm.isDeviceManaged());
3155 mContext.binder.callingUid = 1234567;
3156 mContext.callerPermissions.add(permission.MANAGE_USERS);
3157 assertTrue(dpm.isDeviceManaged());
3158 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3159 mContext.binder.clearCallingIdentity();
3160 assertTrue(dpm.isDeviceManaged());
3161
3162 clearDeviceOwner();
3163
3164 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3165 // not have a device owner.
3166 mContext.binder.callingUid = 1234567;
3167 mContext.callerPermissions.add(permission.MANAGE_USERS);
3168 assertFalse(dpm.isDeviceManaged());
3169 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3170 mContext.binder.clearCallingIdentity();
3171 assertFalse(dpm.isDeviceManaged());
3172 }
3173
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003174 public void testDeviceOwnerOrganizationName() throws Exception {
3175 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3176 setupDeviceOwner();
3177
3178 dpm.setOrganizationName(admin1, "organization");
3179
3180 // Device owner can retrieve organization managing the device.
3181 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3182
3183 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3184 mContext.binder.callingUid = 1234567;
3185 mContext.callerPermissions.add(permission.MANAGE_USERS);
3186 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3187 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3188
3189 // System can retrieve organization managing the device.
3190 mContext.binder.clearCallingIdentity();
3191 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3192
3193 // Removing the device owner clears the organization managing the device.
3194 clearDeviceOwner();
3195 assertNull(dpm.getDeviceOwnerOrganizationName());
3196 }
3197
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003198 public void testWipeDataManagedProfile() throws Exception {
3199 final int MANAGED_PROFILE_USER_ID = 15;
3200 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3201 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3202 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3203
3204 // Even if the caller is the managed profile, the current user is the user 0
3205 when(mContext.iactivityManager.getCurrentUser())
3206 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3207
3208 dpm.wipeData(0);
3209 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3210 MANAGED_PROFILE_USER_ID);
3211 }
3212
3213 public void testWipeDataManagedProfileDisallowed() throws Exception {
3214 final int MANAGED_PROFILE_USER_ID = 15;
3215 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3216 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3217
3218 // Even if the caller is the managed profile, the current user is the user 0
3219 when(mContext.iactivityManager.getCurrentUser())
3220 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3221
3222 when(mContext.userManager.getUserRestrictionSource(
3223 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3224 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3225 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3226 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3227 try {
3228 // The PO is not allowed to remove the profile if the user restriction was set on the
3229 // profile by the system
3230 dpm.wipeData(0);
3231 fail("SecurityException not thrown");
3232 } catch (SecurityException expected) {
3233 }
3234 }
3235
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003236 public void testGetPermissionGrantState() throws Exception {
3237 final String permission = "some.permission";
3238 final String app1 = "com.example.app1";
3239 final String app2 = "com.example.app2";
3240
3241 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3242 .thenReturn(PackageManager.PERMISSION_GRANTED);
3243 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3244 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3245 when(mContext.packageManager.getPermissionFlags(permission, app1,
3246 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3247 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3248 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3249 .thenReturn(PackageManager.PERMISSION_DENIED);
3250 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3251 UserHandle.SYSTEM);
3252 when(mContext.packageManager.getPermissionFlags(permission, app2,
3253 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3254
3255 // System can retrieve permission grant state.
3256 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3257 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3258 dpm.getPermissionGrantState(null, app1, permission));
3259 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3260 dpm.getPermissionGrantState(null, app2, permission));
3261
3262 // A regular app cannot retrieve permission grant state.
3263 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
3264 try {
3265 dpm.getPermissionGrantState(null, app1, permission);
3266 fail("Didn't throw IllegalStateException");
3267 } catch (IllegalStateException expected) {
3268 }
3269
3270 // Profile owner can retrieve permission grant state.
3271 setAsProfileOwner(admin1);
3272 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3273 dpm.getPermissionGrantState(admin1, app1, permission));
3274 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3275 dpm.getPermissionGrantState(admin1, app2, permission));
3276 }
3277
Victor Chang3e794af2016-03-04 13:48:17 +00003278 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
3279 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
3280 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
3281 dpms.notifyChangeToContentObserver(
3282 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
3283 }
3284
3285 private void assertProvisioningAllowed(String action, boolean expected) {
3286 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
3287 dpm.isProvisioningAllowed(action));
3288 }
Tony Mak2f26b792016-11-28 17:54:51 +00003289
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003290 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00003291 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
3292 }
3293
3294 private void assertCheckProvisioningPreCondition(
3295 String action, String packageName, int provisioningCondition) {
3296 assertEquals("checkProvisioningPreCondition("
3297 + action + ", " + packageName + ") returning unexpected result",
3298 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003299 }
3300
Tony Mak2f26b792016-11-28 17:54:51 +00003301 /**
3302 * Setup a managed profile with the specified admin and its uid.
3303 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
3304 * @param adminUid uid of the admin package.
3305 * @param copyFromAdmin package information for {@code admin} will be built based on this
3306 * component's information.
3307 */
3308 private void addManagedProfile(
3309 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
3310 final int userId = UserHandle.getUserId(adminUid);
3311 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
3312 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3313 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
3314 dpm.setActiveAdmin(admin, false, userId);
3315 assertTrue(dpm.setProfileOwner(admin, null, userId));
3316 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3317 }
Victor Chang3e794af2016-03-04 13:48:17 +00003318}