blob: e61a7b058091a1118ba7412a2ea85fbf75f40f37 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Makoto Onukif76b06a2015-09-22 15:03:44 -070018import android.Manifest.permission;
19import android.app.Activity;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070020import android.app.admin.DeviceAdminReceiver;
21import android.app.admin.DevicePolicyManager;
22import android.app.admin.DevicePolicyManagerInternal;
Makoto Onukif76b06a2015-09-22 15:03:44 -070023import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070024import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000025import android.content.Context;
26import android.content.Intent;
27import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000028import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070030import android.content.pm.PackageManager;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010031import android.content.res.Resources;
32import android.graphics.Color;
33import android.net.IIpConnectivityMetrics;
Tony Mak2f26b792016-11-28 17:54:51 +000034import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080035import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080036import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070037import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000038import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080039import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070040import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070041import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080042import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000043import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080044import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000045import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010046import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070047import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070048
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010049import com.android.internal.R;
Alan Treadwayafad8782016-01-19 15:15:08 +000050import com.android.server.LocalServices;
51import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000052import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000053
Makoto Onukib643fb02015-09-22 15:03:44 -070054import org.mockito.invocation.InvocationOnMock;
55import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070056
Makoto Onukic8a5a552015-11-19 14:29:12 -080057import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000058import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000059import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070060import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070062import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010063import java.util.Set;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070064
65import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070066import static org.mockito.Matchers.anyInt;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010067import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070068import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070069import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070070import static org.mockito.Matchers.isNull;
Esteban Talavera548a04b2016-12-20 15:22:30 +000071import static org.mockito.Mockito.atLeast;
Makoto Onukib643fb02015-09-22 15:03:44 -070072import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070073import static org.mockito.Mockito.doReturn;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080074import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070075import static org.mockito.Mockito.times;
76import static org.mockito.Mockito.verify;
77import static org.mockito.Mockito.when;
78
79/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070080 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070081 *
82 m FrameworksServicesTests &&
83 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000084 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070085 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080086 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070087
88 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
89 */
Benjamin Franz6d009032016-01-25 18:56:38 +000090@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070091public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000092 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
93 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
94 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
95
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070096 private DpmMockContext mContext;
97 public DevicePolicyManager dpm;
98 public DevicePolicyManagerServiceTestable dpms;
99
100 @Override
101 protected void setUp() throws Exception {
102 super.setUp();
103
104 mContext = getContext();
105
106 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
107 .thenReturn(true);
108
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800109 // By default, pretend all users are running and unlocked.
110 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
111
Makoto Onukia52562c2015-10-01 16:12:31 -0700112 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700113
Makoto Onukid932f762015-09-29 16:53:38 -0700114 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
115 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
116 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800117 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700118
Makoto Onukib643fb02015-09-22 15:03:44 -0700119 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700120 }
121
Makoto Onukia52562c2015-10-01 16:12:31 -0700122 private void initializeDpms() {
123 // Need clearCallingIdentity() to pass permission checks.
124 final long ident = mContext.binder.clearCallingIdentity();
125 try {
126 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
127
128 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
129
130 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
131 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
132
133 dpm = new DevicePolicyManagerTestable(mContext, dpms);
134 } finally {
135 mContext.binder.restoreCallingIdentity(ident);
136 }
137 }
138
Makoto Onukib643fb02015-09-22 15:03:44 -0700139 private void setUpUserManager() {
140 // Emulate UserManager.set/getApplicationRestriction().
141 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
142
143 // UM.setApplicationRestrictions() will save to appRestrictions.
144 doAnswer(new Answer<Void>() {
145 @Override
146 public Void answer(InvocationOnMock invocation) throws Throwable {
147 String pkg = (String) invocation.getArguments()[0];
148 Bundle bundle = (Bundle) invocation.getArguments()[1];
149 UserHandle user = (UserHandle) invocation.getArguments()[2];
150
151 appRestrictions.put(Pair.create(pkg, user), bundle);
152
153 return null;
154 }
155 }).when(mContext.userManager).setApplicationRestrictions(
156 anyString(), any(Bundle.class), any(UserHandle.class));
157
158 // UM.getApplicationRestrictions() will read from appRestrictions.
159 doAnswer(new Answer<Bundle>() {
160 @Override
161 public Bundle answer(InvocationOnMock invocation) throws Throwable {
162 String pkg = (String) invocation.getArguments()[0];
163 UserHandle user = (UserHandle) invocation.getArguments()[1];
164
165 return appRestrictions.get(Pair.create(pkg, user));
166 }
167 }).when(mContext.userManager).getApplicationRestrictions(
168 anyString(), any(UserHandle.class));
169
Makoto Onukid932f762015-09-29 16:53:38 -0700170 // Add the first secondary user.
171 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700172 }
173
174 private void setAsProfileOwner(ComponentName admin) {
175 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
176 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
177
Makoto Onukia4f11972015-10-01 13:19:58 -0700178 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700179 dpm.setActiveAdmin(admin, /* replace =*/ false);
180
181 // Fire!
182 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
183
184 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700185 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700186 }
187
188 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700189 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
190 .thenReturn(false);
191
192 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
193 new DevicePolicyManagerServiceTestable(mContext, dataDir);
194
195 // If the device has no DPMS feature, it shouldn't register the local service.
196 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
197 }
198
199 /**
200 * Caller doesn't have proper permissions.
201 */
202 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700203 // 1. Failure cases.
204
205 // Caller doesn't have MANAGE_DEVICE_ADMINS.
206 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700207 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700208 fail("Didn't throw SecurityException");
209 } catch (SecurityException expected) {
210 }
211
212 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
213 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
214 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700215 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700216 fail("Didn't throw SecurityException");
217 } catch (SecurityException expected) {
218 }
219 }
220
Makoto Onukif76b06a2015-09-22 15:03:44 -0700221 /**
222 * Test for:
223 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800224 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700225 * {@link DevicePolicyManager#isAdminActive}
226 * {@link DevicePolicyManager#isAdminActiveAsUser}
227 * {@link DevicePolicyManager#getActiveAdmins}
228 * {@link DevicePolicyManager#getActiveAdminsAsUser}
229 */
230 public void testSetActiveAdmin() throws Exception {
231 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700232 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
233
Makoto Onukif76b06a2015-09-22 15:03:44 -0700234 // 2. Call the API.
235 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700236
237 // 3. Verify internal calls.
238
239 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700240 verify(mContext.spiedContext).sendBroadcastAsUser(
241 MockUtils.checkIntentAction(
242 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
243 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
244 verify(mContext.spiedContext).sendBroadcastAsUser(
245 MockUtils.checkIntentAction(
246 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700247 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
248
Makoto Onukif76b06a2015-09-22 15:03:44 -0700249 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
250 eq(admin1.getPackageName()),
251 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
252 eq(PackageManager.DONT_KILL_APP),
253 eq(DpmMockContext.CALLER_USER_HANDLE),
254 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700255
256 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700257
258 // Make sure it's active admin1.
259 assertTrue(dpm.isAdminActive(admin1));
260 assertFalse(dpm.isAdminActive(admin2));
261 assertFalse(dpm.isAdminActive(admin3));
262
263 // But not admin1 for a different user.
264
265 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
266 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
267 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
268
269 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
270 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
271
272 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
273
274 // Next, add one more admin.
275 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700276 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
277 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700278
279 dpm.setActiveAdmin(admin2, /* replace =*/ false);
280
281 // Now we have two admins.
282 assertTrue(dpm.isAdminActive(admin1));
283 assertTrue(dpm.isAdminActive(admin2));
284 assertFalse(dpm.isAdminActive(admin3));
285
286 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
287 // again. (times(1) because it was previously called for admin1)
288 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
289 eq(admin1.getPackageName()),
290 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
291 eq(PackageManager.DONT_KILL_APP),
292 eq(DpmMockContext.CALLER_USER_HANDLE),
293 anyString());
294
295 // 4. Add the same admin1 again without replace, which should throw.
296 try {
297 dpm.setActiveAdmin(admin1, /* replace =*/ false);
298 fail("Didn't throw");
299 } catch (IllegalArgumentException expected) {
300 }
301
302 // 5. Add the same admin1 again with replace, which should succeed.
303 dpm.setActiveAdmin(admin1, /* replace =*/ true);
304
305 // TODO make sure it's replaced.
306
307 // 6. Test getActiveAdmins()
308 List<ComponentName> admins = dpm.getActiveAdmins();
309 assertEquals(2, admins.size());
310 assertEquals(admin1, admins.get(0));
311 assertEquals(admin2, admins.get(1));
312
313 // Another user has no admins.
314 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
315
316 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
317 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
318
319 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
320 }
321
Makoto Onukid932f762015-09-29 16:53:38 -0700322 public void testSetActiveAdmin_multiUsers() throws Exception {
323
324 final int ANOTHER_USER_ID = 100;
325 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
326
327 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
328
329 // Set up pacakge manager for the other user.
330 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700331
332 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
333
334 dpm.setActiveAdmin(admin1, /* replace =*/ false);
335
336 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
337 dpm.setActiveAdmin(admin2, /* replace =*/ false);
338
339
340 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
341 assertTrue(dpm.isAdminActive(admin1));
342 assertFalse(dpm.isAdminActive(admin2));
343
344 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
345 assertFalse(dpm.isAdminActive(admin1));
346 assertTrue(dpm.isAdminActive(admin2));
347 }
348
Makoto Onukif76b06a2015-09-22 15:03:44 -0700349 /**
350 * Test for:
351 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800352 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700353 */
354 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
355 // 1. Make sure the caller has proper permissions.
356 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
357
358 dpm.setActiveAdmin(admin1, /* replace =*/ false);
359 assertTrue(dpm.isAdminActive(admin1));
360
361 // Add the same admin1 again without replace, which should throw.
362 try {
363 dpm.setActiveAdmin(admin1, /* replace =*/ false);
364 fail("Didn't throw");
365 } catch (IllegalArgumentException expected) {
366 }
367 }
368
369 /**
370 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800371 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
372 * BIND_DEVICE_ADMIN.
373 */
374 public void testSetActiveAdmin_permissionCheck() throws Exception {
375 // 1. Make sure the caller has proper permissions.
376 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
377
378 try {
379 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
380 fail();
381 } catch (IllegalArgumentException expected) {
382 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
383 }
384 assertFalse(dpm.isAdminActive(adminNoPerm));
385
386 // Change the target API level to MNC. Now it can be set as DA.
387 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
388 VERSION_CODES.M);
389 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
390 assertTrue(dpm.isAdminActive(adminNoPerm));
391
392 // TODO Test the "load from the file" case where DA will still be loaded even without
393 // BIND_DEVICE_ADMIN and target API is N.
394 }
395
396 /**
397 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700398 * {@link DevicePolicyManager#removeActiveAdmin}
399 */
400 public void testRemoveActiveAdmin_SecurityException() {
401 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
402
403 // Add admin.
404
405 dpm.setActiveAdmin(admin1, /* replace =*/ false);
406
407 assertTrue(dpm.isAdminActive(admin1));
408
409 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
410
411 // Directly call the DPMS method with a different userid, which should fail.
412 try {
413 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
414 fail("Didn't throw SecurityException");
415 } catch (SecurityException expected) {
416 }
417
418 // Try to remove active admin with a different caller userid should fail too, without
419 // having MANAGE_DEVICE_ADMINS.
420 mContext.callerPermissions.clear();
421
Makoto Onukid932f762015-09-29 16:53:38 -0700422 // Change the caller, and call into DPMS directly with a different user-id.
423
Makoto Onukif76b06a2015-09-22 15:03:44 -0700424 mContext.binder.callingUid = 1234567;
425 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700426 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700427 fail("Didn't throw SecurityException");
428 } catch (SecurityException expected) {
429 }
430 }
431
432 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800433 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
434 * (because we can't send the remove broadcast).
435 */
436 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
437 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
438
439 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
440
441 // Add admin.
442
443 dpm.setActiveAdmin(admin1, /* replace =*/ false);
444
445 assertTrue(dpm.isAdminActive(admin1));
446
447 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
448
449 // 1. User not unlocked.
450 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
451 .thenReturn(false);
452 try {
453 dpm.removeActiveAdmin(admin1);
454 fail("Didn't throw IllegalStateException");
455 } catch (IllegalStateException expected) {
456 MoreAsserts.assertContainsRegex(
457 "User must be running and unlocked", expected.getMessage());
458 }
459
460 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
461
462 // 2. User unlocked.
463 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
464 .thenReturn(true);
465
466 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700467 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800468 }
469
470 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700471 * Test for:
472 * {@link DevicePolicyManager#removeActiveAdmin}
473 */
Makoto Onukid932f762015-09-29 16:53:38 -0700474 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700475 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
476
477 // Add admin1.
478
479 dpm.setActiveAdmin(admin1, /* replace =*/ false);
480
481 assertTrue(dpm.isAdminActive(admin1));
482 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
483
484 // Different user, but should work, because caller has proper permissions.
485 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700486
487 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700488 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700489
490 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700491 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700492
493 // TODO DO Still can't be removed in this case.
494 }
495
496 /**
497 * Test for:
498 * {@link DevicePolicyManager#removeActiveAdmin}
499 */
500 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
501 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
502 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
503
504 // Add admin1.
505
506 dpm.setActiveAdmin(admin1, /* replace =*/ false);
507
508 assertTrue(dpm.isAdminActive(admin1));
509 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
510
511 // Broadcast from saveSettingsLocked().
512 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
513 MockUtils.checkIntentAction(
514 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
515 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
516
517 // Remove. No permissions, but same user, so it'll work.
518 mContext.callerPermissions.clear();
519 dpm.removeActiveAdmin(admin1);
520
Makoto Onukif76b06a2015-09-22 15:03:44 -0700521 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
522 MockUtils.checkIntentAction(
523 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
524 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
525 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700526 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700527 eq(dpms.mHandler),
528 eq(Activity.RESULT_OK),
529 isNull(String.class),
530 isNull(Bundle.class));
531
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700532 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700533
534 // Again broadcast from saveSettingsLocked().
535 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
536 MockUtils.checkIntentAction(
537 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
538 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
539
540 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700541 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700542
543 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000544 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700545 */
546 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000547 setDeviceOwner();
548
549 // Try to set a profile owner on the same user, which should fail.
550 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
551 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
552 try {
553 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
554 fail("IllegalStateException not thrown");
555 } catch (IllegalStateException expected) {
556 assertTrue("Message was: " + expected.getMessage(),
557 expected.getMessage().contains("already has a device owner"));
558 }
559
560 // DO admin can't be deactivated.
561 dpm.removeActiveAdmin(admin1);
562 assertTrue(dpm.isAdminActive(admin1));
563
564 // TODO Test getDeviceOwnerName() too. To do so, we need to change
565 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
566 }
567
568 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700569 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800570 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700571 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
572 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
573
Makoto Onukid932f762015-09-29 16:53:38 -0700574 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700575 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
576
Makoto Onukid932f762015-09-29 16:53:38 -0700577 // Make sure admin1 is installed on system user.
578 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700579
Makoto Onukic8a5a552015-11-19 14:29:12 -0800580 // Check various get APIs.
581 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
582
Makoto Onukib643fb02015-09-22 15:03:44 -0700583 // DO needs to be an DA.
584 dpm.setActiveAdmin(admin1, /* replace =*/ false);
585
586 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700587 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700588
Makoto Onukic8a5a552015-11-19 14:29:12 -0800589 // getDeviceOwnerComponent should return the admin1 component.
590 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
591 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
592
593 // Check various get APIs.
594 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
595
596 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
597 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
598 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
599 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
600
601 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
602
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000603 // Verify internal calls.
604 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
605 eq(admin1.getPackageName()));
606
Makoto Onukib643fb02015-09-22 15:03:44 -0700607 // TODO We should check if the caller has called clearCallerIdentity().
608 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
609 eq(UserHandle.USER_SYSTEM), eq(false));
610
611 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
612 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
613 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
614
Makoto Onukic8a5a552015-11-19 14:29:12 -0800615 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700616 }
617
Makoto Onukic8a5a552015-11-19 14:29:12 -0800618 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
619 final int origCallingUser = mContext.binder.callingUid;
620 final List origPermissions = new ArrayList(mContext.callerPermissions);
621 mContext.callerPermissions.clear();
622
623 mContext.callerPermissions.add(permission.MANAGE_USERS);
624
625 mContext.binder.callingUid = Process.SYSTEM_UID;
626
627 // TODO Test getDeviceOwnerName() too. To do so, we need to change
628 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
629 if (hasDeviceOwner) {
630 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
631 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
632 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
633
634 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
635 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
636 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
637 } else {
638 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
639 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
640 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
641
642 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
643 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
644 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
645 }
646
647 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
648 if (hasDeviceOwner) {
649 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
650 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
651 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
652
653 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
654 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
655 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
656 } else {
657 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
658 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
659 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
660
661 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
662 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
663 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
664 }
665
666 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
667 // Still with MANAGE_USERS.
668 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
669 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
670 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
671
672 if (hasDeviceOwner) {
673 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
674 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
675 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
676 } else {
677 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
678 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
679 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
680 }
681
682 mContext.binder.callingUid = Process.SYSTEM_UID;
683 mContext.callerPermissions.remove(permission.MANAGE_USERS);
684 // System can still call "OnAnyUser" without MANAGE_USERS.
685 if (hasDeviceOwner) {
686 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
687 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
688 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
689
690 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
691 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
692 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
693 } else {
694 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
695 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
696 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
697
698 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
699 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
700 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
701 }
702
703 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
704 // Still no MANAGE_USERS.
705 if (hasDeviceOwner) {
706 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
707 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
708 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
709 } else {
710 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
711 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
712 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
713 }
714
715 try {
716 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
717 fail();
718 } catch (SecurityException expected) {
719 }
720 try {
721 dpm.getDeviceOwnerComponentOnAnyUser();
722 fail();
723 } catch (SecurityException expected) {
724 }
725 try {
726 dpm.getDeviceOwnerUserId();
727 fail();
728 } catch (SecurityException expected) {
729 }
730 try {
731 dpm.getDeviceOwnerNameOnAnyUser();
732 fail();
733 } catch (SecurityException expected) {
734 }
735
736 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
737 // Still no MANAGE_USERS.
738 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
739 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
740 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
741
742 try {
743 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
744 fail();
745 } catch (SecurityException expected) {
746 }
747 try {
748 dpm.getDeviceOwnerComponentOnAnyUser();
749 fail();
750 } catch (SecurityException expected) {
751 }
752 try {
753 dpm.getDeviceOwnerUserId();
754 fail();
755 } catch (SecurityException expected) {
756 }
757 try {
758 dpm.getDeviceOwnerNameOnAnyUser();
759 fail();
760 } catch (SecurityException expected) {
761 }
762
763 // Restore.
764 mContext.binder.callingUid = origCallingUser;
765 mContext.callerPermissions.addAll(origPermissions);
766 }
767
768
Makoto Onukib643fb02015-09-22 15:03:44 -0700769 /**
770 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
771 */
772 public void testSetDeviceOwner_noSuchPackage() {
773 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800774 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700775 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
776 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
777
778 // Call from a process on the system user.
779 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
780
Makoto Onukib643fb02015-09-22 15:03:44 -0700781 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700782 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700783 fail("Didn't throw IllegalArgumentException");
784 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700785 assertTrue("Message was: " + expected.getMessage(),
786 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700787 }
788 }
789
790 public void testSetDeviceOwner_failures() throws Exception {
791 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
792 }
793
Makoto Onukia52562c2015-10-01 16:12:31 -0700794 public void testClearDeviceOwner() throws Exception {
795 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800796 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700797 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
798 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
799
800 // Set admin1 as a DA to the secondary user.
801 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
802
803 dpm.setActiveAdmin(admin1, /* replace =*/ false);
804
805 // Set admin 1 as the DO to the system user.
806
807 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
808 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
809 dpm.setActiveAdmin(admin1, /* replace =*/ false);
810 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
811
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000812 // Verify internal calls.
813 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
814 eq(admin1.getPackageName()));
815
Makoto Onukic8a5a552015-11-19 14:29:12 -0800816 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700817
Makoto Onuki90b89652016-01-28 14:44:18 -0800818 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
819
820 assertTrue(dpm.isAdminActive(admin1));
821 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
822
Makoto Onukia52562c2015-10-01 16:12:31 -0700823 // Set up other mocks.
824 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
825
826 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700827 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700828 eq(admin1.getPackageName()),
829 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800830
831 // But first pretend the user is locked. Then it should fail.
832 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
833 try {
834 dpm.clearDeviceOwnerApp(admin1.getPackageName());
835 fail("Didn't throw IllegalStateException");
836 } catch (IllegalStateException expected) {
837 MoreAsserts.assertContainsRegex(
838 "User must be running and unlocked", expected.getMessage());
839 }
840
841 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800842 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700843 dpm.clearDeviceOwnerApp(admin1.getPackageName());
844
845 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800846 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700847
Makoto Onuki90b89652016-01-28 14:44:18 -0800848 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
849 eq(UserHandle.USER_SYSTEM),
850 MockUtils.checkUserRestrictions(),
851 MockUtils.checkUserRestrictions()
852 );
853
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700854 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100855
856 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
857 // and once for clearing it.
858 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
859 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
860 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700861 // TODO Check other calls.
862 }
863
864 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
865 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800866 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700867 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
868 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
869
870 // Set admin1 as a DA to the secondary user.
871 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
872
873 dpm.setActiveAdmin(admin1, /* replace =*/ false);
874
875 // Set admin 1 as the DO to the system user.
876
877 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
878 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
879 dpm.setActiveAdmin(admin1, /* replace =*/ false);
880 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
881
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000882 // Verify internal calls.
883 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
884 eq(admin1.getPackageName()));
885
Makoto Onukic8a5a552015-11-19 14:29:12 -0800886 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700887
888 // Now call clear from the secondary user, which should throw.
889 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
890
891 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700892 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700893 eq(admin1.getPackageName()),
894 anyInt());
895 try {
896 dpm.clearDeviceOwnerApp(admin1.getPackageName());
897 fail("Didn't throw");
898 } catch (SecurityException e) {
899 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
900 }
901
Makoto Onukic8a5a552015-11-19 14:29:12 -0800902 // DO shouldn't be removed.
903 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700904 }
905
Makoto Onukib643fb02015-09-22 15:03:44 -0700906 public void testSetProfileOwner() throws Exception {
907 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700908
Makoto Onuki90b89652016-01-28 14:44:18 -0800909 // PO admin can't be deactivated.
910 dpm.removeActiveAdmin(admin1);
911 assertTrue(dpm.isAdminActive(admin1));
912
Makoto Onuki803d6752015-10-30 12:58:39 -0700913 // Try setting DO on the same user, which should fail.
914 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
915 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
916 try {
917 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
918 fail("IllegalStateException not thrown");
919 } catch (IllegalStateException expected) {
920 assertTrue("Message was: " + expected.getMessage(),
921 expected.getMessage().contains("already has a profile owner"));
922 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700923 }
924
Makoto Onuki90b89652016-01-28 14:44:18 -0800925 public void testClearProfileOwner() throws Exception {
926 setAsProfileOwner(admin1);
927
928 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
929
930 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
931 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
932
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800933 // First try when the user is locked, which should fail.
934 when(mContext.userManager.isUserUnlocked(anyInt()))
935 .thenReturn(false);
936 try {
937 dpm.clearProfileOwner(admin1);
938 fail("Didn't throw IllegalStateException");
939 } catch (IllegalStateException expected) {
940 MoreAsserts.assertContainsRegex(
941 "User must be running and unlocked", expected.getMessage());
942 }
943 // Clear, really.
944 when(mContext.userManager.isUserUnlocked(anyInt()))
945 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800946 dpm.clearProfileOwner(admin1);
947
948 // Check
949 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700950 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -0800951 }
952
Makoto Onukib643fb02015-09-22 15:03:44 -0700953 public void testSetProfileOwner_failures() throws Exception {
954 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
955 }
956
Makoto Onukia52562c2015-10-01 16:12:31 -0700957 public void testGetDeviceOwnerAdminLocked() throws Exception {
958 checkDeviceOwnerWithMultipleDeviceAdmins();
959 }
960
961 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
962 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
963 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
964 // make sure it gets the right component from the right user.
965
966 final int ANOTHER_USER_ID = 100;
967 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
968
969 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
970
971 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800972 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700973 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
974 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
975
976 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
977
Victor Change29cd472016-03-02 20:57:42 +0000978 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
979
Makoto Onukia52562c2015-10-01 16:12:31 -0700980 // Make sure the admin packge is installed to each user.
981 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
982 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
983
984 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
985 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
986
987 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
988
989
990 // Set active admins to the users.
991 dpm.setActiveAdmin(admin1, /* replace =*/ false);
992 dpm.setActiveAdmin(admin3, /* replace =*/ false);
993
994 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
995 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
996
997 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
998
999 // Set DO on the first non-system user.
1000 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1001 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1002
Makoto Onukic8a5a552015-11-19 14:29:12 -08001003 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001004
1005 // Then check getDeviceOwnerAdminLocked().
1006 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1007 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1008 }
1009
1010 /**
1011 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001012 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1013 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001014 *
1015 * We didn't use to persist the DO component class name, but now we do, and the above method
1016 * finds the right component from a package name upon migration.
1017 */
1018 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001019 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001020 checkDeviceOwnerWithMultipleDeviceAdmins();
1021
1022 // Overwrite the device owner setting and clears the clas name.
1023 dpms.mOwners.setDeviceOwner(
1024 new ComponentName(admin2.getPackageName(), ""),
1025 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1026 dpms.mOwners.writeDeviceOwner();
1027
1028 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001029 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001030
1031 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001032 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1033 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001034 initializeDpms();
1035
1036 // Now the DO component name is a full name.
1037 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1038 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001039 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001040 }
1041
Makoto Onukib643fb02015-09-22 15:03:44 -07001042 public void testSetGetApplicationRestriction() {
1043 setAsProfileOwner(admin1);
1044
1045 {
1046 Bundle rest = new Bundle();
1047 rest.putString("KEY_STRING", "Foo1");
1048 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1049 }
1050
1051 {
1052 Bundle rest = new Bundle();
1053 rest.putString("KEY_STRING", "Foo2");
1054 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1055 }
1056
1057 {
1058 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1059 assertNotNull(returned);
1060 assertEquals(returned.size(), 1);
1061 assertEquals(returned.get("KEY_STRING"), "Foo1");
1062 }
1063
1064 {
1065 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1066 assertNotNull(returned);
1067 assertEquals(returned.size(), 1);
1068 assertEquals(returned.get("KEY_STRING"), "Foo2");
1069 }
1070
1071 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1072 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1073 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001074
Esteban Talaverabf60f722015-12-10 16:26:44 +00001075 public void testApplicationRestrictionsManagingApp() throws Exception {
1076 setAsProfileOwner(admin1);
1077
Rubin Xued1928a2016-02-11 17:23:06 +00001078 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001079 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1080 final int appRestrictionsManagerAppId = 20987;
1081 final int appRestrictionsManagerUid = UserHandle.getUid(
1082 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001083 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001084 eq(appRestrictionsManagerPackage),
1085 eq(DpmMockContext.CALLER_USER_HANDLE));
1086 mContext.binder.callingUid = appRestrictionsManagerUid;
1087
Rubin Xued1928a2016-02-11 17:23:06 +00001088 final PackageInfo pi = new PackageInfo();
1089 pi.applicationInfo = new ApplicationInfo();
1090 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1091 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1092 eq(appRestrictionsManagerPackage),
1093 anyInt(),
1094 eq(DpmMockContext.CALLER_USER_HANDLE));
1095
Esteban Talaverabf60f722015-12-10 16:26:44 +00001096 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1097 // delegated that permission yet.
1098 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1099 Bundle rest = new Bundle();
1100 rest.putString("KEY_STRING", "Foo1");
1101 try {
1102 dpm.setApplicationRestrictions(null, "pkg1", rest);
1103 fail("Didn't throw expected SecurityException");
1104 } catch (SecurityException expected) {
1105 MoreAsserts.assertContainsRegex(
1106 "caller cannot manage application restrictions", expected.getMessage());
1107 }
1108 try {
1109 dpm.getApplicationRestrictions(null, "pkg1");
1110 fail("Didn't throw expected SecurityException");
1111 } catch (SecurityException expected) {
1112 MoreAsserts.assertContainsRegex(
1113 "caller cannot manage application restrictions", expected.getMessage());
1114 }
1115
1116 // Check via the profile owner that no restrictions were set.
1117 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1118 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1119
Rubin Xued1928a2016-02-11 17:23:06 +00001120 // Check the API does not allow setting a non-existent package
1121 try {
1122 dpm.setApplicationRestrictionsManagingPackage(admin1,
1123 nonExistAppRestrictionsManagerPackage);
1124 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001125 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001126 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001127 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001128 }
1129
Esteban Talaverabf60f722015-12-10 16:26:44 +00001130 // Let appRestrictionsManagerPackage manage app restrictions
1131 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1132 assertEquals(appRestrictionsManagerPackage,
1133 dpm.getApplicationRestrictionsManagingPackage(admin1));
1134
1135 // Now that package should be able to set and retrieve app restrictions.
1136 mContext.binder.callingUid = appRestrictionsManagerUid;
1137 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1138 dpm.setApplicationRestrictions(null, "pkg1", rest);
1139 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1140 assertEquals(1, returned.size(), 1);
1141 assertEquals("Foo1", returned.get("KEY_STRING"));
1142
1143 // The same app running on a separate user shouldn't be able to manage app restrictions.
1144 mContext.binder.callingUid = UserHandle.getUid(
1145 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1146 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1147 try {
1148 dpm.setApplicationRestrictions(null, "pkg1", rest);
1149 fail("Didn't throw expected SecurityException");
1150 } catch (SecurityException expected) {
1151 MoreAsserts.assertContainsRegex(
1152 "caller cannot manage application restrictions", expected.getMessage());
1153 }
1154
1155 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1156 // too.
1157 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1158 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1159 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1160 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1161
1162 // Removing the ability for the package to manage app restrictions.
1163 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1164 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1165 mContext.binder.callingUid = appRestrictionsManagerUid;
1166 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1167 try {
1168 dpm.setApplicationRestrictions(null, "pkg1", null);
1169 fail("Didn't throw expected SecurityException");
1170 } catch (SecurityException expected) {
1171 MoreAsserts.assertContainsRegex(
1172 "caller cannot manage application restrictions", expected.getMessage());
1173 }
1174 }
1175
Makoto Onukia4f11972015-10-01 13:19:58 -07001176 public void testSetUserRestriction_asDo() throws Exception {
1177 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001178 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001179 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1180 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1181
1182 // First, set DO.
1183
1184 // Call from a process on the system user.
1185 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1186
1187 // Make sure admin1 is installed on system user.
1188 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001189
1190 // Call.
1191 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001192 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001193 UserHandle.USER_SYSTEM));
1194
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001195 // Check that the user restrictions that are enabled by default are set. Then unset them.
1196 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001197 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001198 DpmTestUtils.assertRestrictions(
1199 DpmTestUtils.newRestrictions(defaultRestrictions),
1200 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1201 );
1202 DpmTestUtils.assertRestrictions(
1203 DpmTestUtils.newRestrictions(defaultRestrictions),
1204 dpm.getUserRestrictions(admin1)
1205 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001206 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1207 eq(UserHandle.USER_SYSTEM),
1208 MockUtils.checkUserRestrictions(),
1209 MockUtils.checkUserRestrictions(defaultRestrictions)
1210 );
1211 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001212
1213 for (String restriction : defaultRestrictions) {
1214 dpm.clearUserRestriction(admin1, restriction);
1215 }
1216
Esteban Talavera548a04b2016-12-20 15:22:30 +00001217 assertNoDeviceOwnerRestrictions();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001218
1219 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1220 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1221 eq(UserHandle.USER_SYSTEM),
1222 MockUtils.checkUserRestrictions(),
1223 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001224 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001225 reset(mContext.userManagerInternal);
1226
Makoto Onukia4f11972015-10-01 13:19:58 -07001227 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001228 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1229 eq(UserHandle.USER_SYSTEM),
1230 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1231 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1232 );
1233 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001234
Makoto Onuki068c54a2015-10-13 14:34:03 -07001235 DpmTestUtils.assertRestrictions(
1236 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001237 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001238 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1239 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001240 DpmTestUtils.assertRestrictions(
1241 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001242 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001243 dpm.getUserRestrictions(admin1)
1244 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001245
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001246 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1247 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1248 eq(UserHandle.USER_SYSTEM),
1249 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1250 MockUtils.checkUserRestrictions()
1251 );
1252 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001253
Makoto Onuki068c54a2015-10-13 14:34:03 -07001254 DpmTestUtils.assertRestrictions(
1255 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1256 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1257 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001258 DpmTestUtils.assertRestrictions(
1259 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1260 dpm.getUserRestrictions(admin1)
1261 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001262
1263 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001264 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1265 eq(UserHandle.USER_SYSTEM),
1266 MockUtils.checkUserRestrictions(),
1267 MockUtils.checkUserRestrictions()
1268 );
1269 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001270
Esteban Talavera548a04b2016-12-20 15:22:30 +00001271 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001272
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001273 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1274 // DO sets them, the scope is global.
1275 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1276 reset(mContext.userManagerInternal);
1277 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1278 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1279 eq(UserHandle.USER_SYSTEM),
1280 MockUtils.checkUserRestrictions(),
1281 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1282 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1283 );
1284 reset(mContext.userManagerInternal);
1285
1286 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1287 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1288
1289
1290 // More tests.
1291 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1292 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1293 eq(UserHandle.USER_SYSTEM),
1294 MockUtils.checkUserRestrictions(),
1295 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1296 );
1297 reset(mContext.userManagerInternal);
1298
1299 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1300 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1301 eq(UserHandle.USER_SYSTEM),
1302 MockUtils.checkUserRestrictions(),
1303 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1304 UserManager.DISALLOW_ADD_USER)
1305 );
1306 reset(mContext.userManagerInternal);
1307
1308 dpm.setCameraDisabled(admin1, true);
1309 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1310 eq(UserHandle.USER_SYSTEM),
1311 // DISALLOW_CAMERA will be applied to both local and global.
1312 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1313 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1314 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1315 );
1316 reset(mContext.userManagerInternal);
1317
1318 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1319 // locally.
1320 dpm.setCameraDisabled(admin1, false);
1321 reset(mContext.userManagerInternal);
1322
1323 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1324 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1325 dpm.setCameraDisabled(admin2, true);
1326
1327 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1328 eq(UserHandle.USER_SYSTEM),
1329 // DISALLOW_CAMERA will be applied to both local and global.
1330 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1331 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1332 UserManager.DISALLOW_ADD_USER)
1333 );
1334 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001335 // TODO Make sure restrictions are written to the file.
1336 }
1337
1338 public void testSetUserRestriction_asPo() {
1339 setAsProfileOwner(admin1);
1340
Makoto Onuki068c54a2015-10-13 14:34:03 -07001341 DpmTestUtils.assertRestrictions(
1342 DpmTestUtils.newRestrictions(),
1343 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1344 .ensureUserRestrictions()
1345 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001346
1347 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001348 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1349 eq(DpmMockContext.CALLER_USER_HANDLE),
1350 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1351 isNull(Bundle.class)
1352 );
1353 reset(mContext.userManagerInternal);
1354
Makoto Onukia4f11972015-10-01 13:19:58 -07001355 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001356 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1357 eq(DpmMockContext.CALLER_USER_HANDLE),
1358 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1359 UserManager.DISALLOW_OUTGOING_CALLS),
1360 isNull(Bundle.class)
1361 );
1362 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001363
Makoto Onuki068c54a2015-10-13 14:34:03 -07001364 DpmTestUtils.assertRestrictions(
1365 DpmTestUtils.newRestrictions(
1366 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1367 UserManager.DISALLOW_OUTGOING_CALLS
1368 ),
1369 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1370 .ensureUserRestrictions()
1371 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001372 DpmTestUtils.assertRestrictions(
1373 DpmTestUtils.newRestrictions(
1374 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1375 UserManager.DISALLOW_OUTGOING_CALLS
1376 ),
1377 dpm.getUserRestrictions(admin1)
1378 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001379
1380 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001381 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1382 eq(DpmMockContext.CALLER_USER_HANDLE),
1383 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1384 isNull(Bundle.class)
1385 );
1386 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001387
1388 DpmTestUtils.assertRestrictions(
1389 DpmTestUtils.newRestrictions(
1390 UserManager.DISALLOW_OUTGOING_CALLS
1391 ),
1392 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1393 .ensureUserRestrictions()
1394 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001395 DpmTestUtils.assertRestrictions(
1396 DpmTestUtils.newRestrictions(
1397 UserManager.DISALLOW_OUTGOING_CALLS
1398 ),
1399 dpm.getUserRestrictions(admin1)
1400 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001401
1402 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001403 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1404 eq(DpmMockContext.CALLER_USER_HANDLE),
1405 MockUtils.checkUserRestrictions(),
1406 isNull(Bundle.class)
1407 );
1408 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001409
Makoto Onuki068c54a2015-10-13 14:34:03 -07001410 DpmTestUtils.assertRestrictions(
1411 DpmTestUtils.newRestrictions(),
1412 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1413 .ensureUserRestrictions()
1414 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001415 DpmTestUtils.assertRestrictions(
1416 DpmTestUtils.newRestrictions(),
1417 dpm.getUserRestrictions(admin1)
1418 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001419
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001420 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1421 // though when DO sets them they'll be applied globally.
1422 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1423 reset(mContext.userManagerInternal);
1424 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1425 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1426 eq(DpmMockContext.CALLER_USER_HANDLE),
1427 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1428 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1429 isNull(Bundle.class)
1430 );
1431 reset(mContext.userManagerInternal);
1432
1433 dpm.setCameraDisabled(admin1, true);
1434 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1435 eq(DpmMockContext.CALLER_USER_HANDLE),
1436 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1437 UserManager.DISALLOW_ADJUST_VOLUME,
1438 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1439 isNull(Bundle.class)
1440 );
1441 reset(mContext.userManagerInternal);
1442
Makoto Onukia4f11972015-10-01 13:19:58 -07001443 // TODO Make sure restrictions are written to the file.
1444 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001445
Esteban Talavera548a04b2016-12-20 15:22:30 +00001446
1447 public void testDefaultEnabledUserRestrictions() throws Exception {
1448 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1449 mContext.callerPermissions.add(permission.MANAGE_USERS);
1450 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1451 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1452
1453 // First, set DO.
1454
1455 // Call from a process on the system user.
1456 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1457
1458 // Make sure admin1 is installed on system user.
1459 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1460
1461 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1462 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1463 UserHandle.USER_SYSTEM));
1464
1465 // Check that the user restrictions that are enabled by default are set. Then unset them.
1466 String[] defaultRestrictions = UserRestrictionsUtils
1467 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1468 assertTrue(defaultRestrictions.length > 0);
1469 DpmTestUtils.assertRestrictions(
1470 DpmTestUtils.newRestrictions(defaultRestrictions),
1471 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1472 );
1473 DpmTestUtils.assertRestrictions(
1474 DpmTestUtils.newRestrictions(defaultRestrictions),
1475 dpm.getUserRestrictions(admin1)
1476 );
1477 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1478 eq(UserHandle.USER_SYSTEM),
1479 MockUtils.checkUserRestrictions(),
1480 MockUtils.checkUserRestrictions(defaultRestrictions)
1481 );
1482 reset(mContext.userManagerInternal);
1483
1484 for (String restriction : defaultRestrictions) {
1485 dpm.clearUserRestriction(admin1, restriction);
1486 }
1487
1488 assertNoDeviceOwnerRestrictions();
1489
1490 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1491 reset(mContext.userManagerInternal);
1492 initializeDpms();
1493 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1494 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1495
1496 assertNoDeviceOwnerRestrictions();
1497
1498 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1499 // is set as it wasn't enabled during setDeviceOwner.
1500 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1501 assertFalse(UserRestrictionsUtils
1502 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1503 UserRestrictionsUtils
1504 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1505 try {
1506 reset(mContext.userManagerInternal);
1507 initializeDpms();
1508 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1509 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1510
1511 DpmTestUtils.assertRestrictions(
1512 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1513 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1514 );
1515 DpmTestUtils.assertRestrictions(
1516 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1517 dpm.getUserRestrictions(admin1)
1518 );
1519 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1520 eq(UserHandle.USER_SYSTEM),
1521 MockUtils.checkUserRestrictions(),
1522 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction)
1523 );
1524 reset(mContext.userManagerInternal);
1525
1526 // Remove the restriction.
1527 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1528
1529 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1530 initializeDpms();
1531 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1532 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1533 assertNoDeviceOwnerRestrictions();
1534 } finally {
1535 UserRestrictionsUtils
1536 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1537 }
1538 }
1539
1540 private void assertNoDeviceOwnerRestrictions() {
1541 DpmTestUtils.assertRestrictions(
1542 DpmTestUtils.newRestrictions(),
1543 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1544 );
1545 DpmTestUtils.assertRestrictions(
1546 DpmTestUtils.newRestrictions(),
1547 dpm.getUserRestrictions(admin1)
1548 );
1549 }
1550
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001551 public void testGetMacAddress() throws Exception {
1552 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1553 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1554 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1555
1556 // In this test, change the caller user to "system".
1557 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1558
1559 // Make sure admin1 is installed on system user.
1560 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1561
1562 // Test 1. Caller doesn't have DO or DA.
1563 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001564 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001565 fail();
1566 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001567 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001568 }
1569
1570 // DO needs to be an DA.
1571 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1572 assertTrue(dpm.isAdminActive(admin1));
1573
1574 // Test 2. Caller has DA, but not DO.
1575 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001576 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001577 fail();
1578 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001579 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001580 }
1581
1582 // Test 3. Caller has PO, but not DO.
1583 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1584 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001585 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001586 fail();
1587 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001588 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001589 }
1590
1591 // Remove PO.
1592 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001593 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001594 // Test 4, Caller is DO now.
1595 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1596
1597 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001598 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001599
1600 // 4-2. Returns WifiInfo, but with the default MAC.
1601 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001602 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001603
1604 // 4-3. With a real MAC address.
1605 final WifiInfo wi = new WifiInfo();
1606 wi.setMacAddress("11:22:33:44:55:66");
1607 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001608 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001609 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001610
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001611 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001612 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1613 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1614
1615 // In this test, change the caller user to "system".
1616 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1617
1618 // Make sure admin1 is installed on system user.
1619 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1620
1621 // Set admin1 as DA.
1622 dpm.setActiveAdmin(admin1, false);
1623 assertTrue(dpm.isAdminActive(admin1));
1624 try {
1625 dpm.reboot(admin1);
1626 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1627 } catch (SecurityException expected) {
1628 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1629 }
1630
1631 // Set admin1 as PO.
1632 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1633 try {
1634 dpm.reboot(admin1);
1635 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1636 } catch (SecurityException expected) {
1637 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1638 }
1639
1640 // Remove PO and add DO.
1641 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001642 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001643 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1644
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001645 // admin1 is DO.
1646 // Set current call state of device to ringing.
1647 when(mContext.telephonyManager.getCallState())
1648 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1649 try {
1650 dpm.reboot(admin1);
1651 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1652 } catch (IllegalStateException expected) {
1653 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1654 }
1655
1656 // Set current call state of device to dialing/active.
1657 when(mContext.telephonyManager.getCallState())
1658 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1659 try {
1660 dpm.reboot(admin1);
1661 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1662 } catch (IllegalStateException expected) {
1663 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1664 }
1665
1666 // Set current call state of device to idle.
1667 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001668 dpm.reboot(admin1);
1669 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001670
1671 public void testSetGetSupportText() {
1672 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1673 dpm.setActiveAdmin(admin1, true);
1674 dpm.setActiveAdmin(admin2, true);
1675 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1676
1677 // Null default support messages.
1678 {
1679 assertNull(dpm.getLongSupportMessage(admin1));
1680 assertNull(dpm.getShortSupportMessage(admin1));
1681 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1682 assertNull(dpm.getShortSupportMessageForUser(admin1,
1683 DpmMockContext.CALLER_USER_HANDLE));
1684 assertNull(dpm.getLongSupportMessageForUser(admin1,
1685 DpmMockContext.CALLER_USER_HANDLE));
1686 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1687 }
1688
1689 // Only system can call the per user versions.
1690 {
1691 try {
1692 dpm.getShortSupportMessageForUser(admin1,
1693 DpmMockContext.CALLER_USER_HANDLE);
1694 fail("Only system should be able to call getXXXForUser versions");
1695 } catch (SecurityException expected) {
1696 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1697 }
1698 try {
1699 dpm.getLongSupportMessageForUser(admin1,
1700 DpmMockContext.CALLER_USER_HANDLE);
1701 fail("Only system should be able to call getXXXForUser versions");
1702 } catch (SecurityException expected) {
1703 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1704 }
1705 }
1706
1707 // Can't set message for admin in another uid.
1708 {
1709 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1710 try {
1711 dpm.setShortSupportMessage(admin1, "Some text");
1712 fail("Admins should only be able to change their own support text.");
1713 } catch (SecurityException expected) {
1714 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1715 }
1716 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1717 }
1718
1719 // Set/Get short returns what it sets and other admins text isn't changed.
1720 {
1721 final String supportText = "Some text to test with.";
1722 dpm.setShortSupportMessage(admin1, supportText);
1723 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1724 assertNull(dpm.getLongSupportMessage(admin1));
1725 assertNull(dpm.getShortSupportMessage(admin2));
1726
1727 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1728 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1729 DpmMockContext.CALLER_USER_HANDLE));
1730 assertNull(dpm.getShortSupportMessageForUser(admin2,
1731 DpmMockContext.CALLER_USER_HANDLE));
1732 assertNull(dpm.getLongSupportMessageForUser(admin1,
1733 DpmMockContext.CALLER_USER_HANDLE));
1734 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1735
1736 dpm.setShortSupportMessage(admin1, null);
1737 assertNull(dpm.getShortSupportMessage(admin1));
1738 }
1739
1740 // Set/Get long returns what it sets and other admins text isn't changed.
1741 {
1742 final String supportText = "Some text to test with.\nWith more text.";
1743 dpm.setLongSupportMessage(admin1, supportText);
1744 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1745 assertNull(dpm.getShortSupportMessage(admin1));
1746 assertNull(dpm.getLongSupportMessage(admin2));
1747
1748 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1749 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1750 DpmMockContext.CALLER_USER_HANDLE));
1751 assertNull(dpm.getLongSupportMessageForUser(admin2,
1752 DpmMockContext.CALLER_USER_HANDLE));
1753 assertNull(dpm.getShortSupportMessageForUser(admin1,
1754 DpmMockContext.CALLER_USER_HANDLE));
1755 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1756
1757 dpm.setLongSupportMessage(admin1, null);
1758 assertNull(dpm.getLongSupportMessage(admin1));
1759 }
1760 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001761
1762 /**
1763 * Test for:
1764 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001765 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001766 * {@link DevicePolicyManager#isAffiliatedUser}
1767 */
1768 public void testUserAffiliation() throws Exception {
1769 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1770 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1771 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1772
1773 // Check that the system user is unaffiliated.
1774 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1775 assertFalse(dpm.isAffiliatedUser());
1776
1777 // Set a device owner on the system user. Check that the system user becomes affiliated.
1778 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1779 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1780 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1781 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001782 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001783
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001784 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001785 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1786 setAsProfileOwner(admin2);
1787 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001788 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001789
1790 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1791 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001792 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001793 userAffiliationIds.add("red");
1794 userAffiliationIds.add("green");
1795 userAffiliationIds.add("blue");
1796 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001797 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001798 assertFalse(dpm.isAffiliatedUser());
1799
1800 // Have the device owner specify a set of affiliation ids that do not intersect with those
1801 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001802 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001803 deviceAffiliationIds.add("cyan");
1804 deviceAffiliationIds.add("yellow");
1805 deviceAffiliationIds.add("magenta");
1806 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1807 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001808 MoreAsserts.assertContentsInAnyOrder(
1809 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001810 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1811 assertFalse(dpm.isAffiliatedUser());
1812
1813 // Have the profile owner specify a set of affiliation ids that intersect with those
1814 // specified by the device owner. Check that the test user becomes affiliated.
1815 userAffiliationIds.add("yellow");
1816 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001817 MoreAsserts.assertContentsInAnyOrder(
1818 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001819 assertTrue(dpm.isAffiliatedUser());
1820
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001821 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
1822 dpm.setAffiliationIds(admin2, Collections.emptyList());
1823 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001824 assertFalse(dpm.isAffiliatedUser());
1825
1826 // Check that the system user remains affiliated.
1827 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1828 assertTrue(dpm.isAffiliatedUser());
1829 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001830
1831 public void testGetUserProvisioningState_defaultResult() {
1832 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1833 }
1834
1835 public void testSetUserProvisioningState_permission() throws Exception {
1836 setupProfileOwner();
1837 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1838
1839 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1840 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1841 }
1842
1843 public void testSetUserProvisioningState_unprivileged() throws Exception {
1844 setupProfileOwner();
1845 try {
1846 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1847 DpmMockContext.CALLER_USER_HANDLE);
1848 fail("Expected SecurityException");
1849 } catch (SecurityException expected) {
1850 }
1851 }
1852
1853 public void testSetUserProvisioningState_noManagement() {
1854 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1855 try {
1856 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1857 DpmMockContext.CALLER_USER_HANDLE);
1858 fail("IllegalStateException expected");
1859 } catch (IllegalStateException e) {
1860 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1861 e.getMessage());
1862 }
1863 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1864 }
1865
1866 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1867 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1868 setupDeviceOwner();
1869 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1870
1871 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1872 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1873 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1874 }
1875
1876 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1877 throws Exception {
1878 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1879 setupDeviceOwner();
1880 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1881
1882 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1883 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1884 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1885 }
1886
1887 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1888 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1889 setupDeviceOwner();
1890 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1891
1892 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1893 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1894 }
1895
1896 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1897 throws Exception {
1898 setupProfileOwner();
1899 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1900
1901 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1902 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1903 DevicePolicyManager.STATE_USER_UNMANAGED);
1904 }
1905
1906 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1907 throws Exception {
1908 setupProfileOwner();
1909 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1910
1911 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1912 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1913 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1914 }
1915
1916 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1917 setupProfileOwner();
1918 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1919
1920 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1921 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1922 }
1923
1924 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
1925 setupProfileOwner();
1926 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1927
1928 try {
1929 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1930 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1931 DevicePolicyManager.STATE_USER_UNMANAGED);
1932 fail("Expected IllegalStateException");
1933 } catch (IllegalStateException e) {
1934 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1935 e.getMessage());
1936 }
1937 }
1938
1939 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
1940 throws Exception {
1941 setupProfileOwner();
1942 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1943
1944 try {
1945 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1946 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1947 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
1948 fail("Expected IllegalStateException");
1949 } catch (IllegalStateException e) {
1950 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1951 e.getMessage());
1952 }
1953 }
1954
1955 private void exerciseUserProvisioningTransitions(int userId, int... states) {
1956 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1957 for (int state : states) {
1958 dpm.setUserProvisioningState(state, userId);
1959 assertEquals(state, dpm.getUserProvisioningState());
1960 }
1961 }
1962
1963 private void setupProfileOwner() throws Exception {
1964 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1965
1966 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1967 dpm.setActiveAdmin(admin1, false);
1968 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
1969
1970 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1971 }
1972
1973 private void setupDeviceOwner() throws Exception {
1974 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1975
1976 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1977 dpm.setActiveAdmin(admin1, false);
1978 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1979
1980 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1981 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001982
1983 public void testSetMaximumTimeToLock() {
1984 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1985
1986 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1987 dpm.setActiveAdmin(admin2, /* replace =*/ false);
1988
1989 reset(mMockContext.powerManagerInternal);
1990 reset(mMockContext.settings);
1991
1992 dpm.setMaximumTimeToLock(admin1, 0);
1993 verifyScreenTimeoutCall(null, false);
1994 reset(mMockContext.powerManagerInternal);
1995 reset(mMockContext.settings);
1996
1997 dpm.setMaximumTimeToLock(admin1, 1);
1998 verifyScreenTimeoutCall(1, true);
1999 reset(mMockContext.powerManagerInternal);
2000 reset(mMockContext.settings);
2001
2002 dpm.setMaximumTimeToLock(admin2, 10);
2003 verifyScreenTimeoutCall(null, false);
2004 reset(mMockContext.powerManagerInternal);
2005 reset(mMockContext.settings);
2006
2007 dpm.setMaximumTimeToLock(admin1, 5);
2008 verifyScreenTimeoutCall(5, true);
2009 reset(mMockContext.powerManagerInternal);
2010 reset(mMockContext.settings);
2011
2012 dpm.setMaximumTimeToLock(admin2, 4);
2013 verifyScreenTimeoutCall(4, true);
2014 reset(mMockContext.powerManagerInternal);
2015 reset(mMockContext.settings);
2016
2017 dpm.setMaximumTimeToLock(admin1, 0);
2018 reset(mMockContext.powerManagerInternal);
2019 reset(mMockContext.settings);
2020
2021 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2022 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2023 reset(mMockContext.powerManagerInternal);
2024 reset(mMockContext.settings);
2025
2026 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2027 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2028 reset(mMockContext.powerManagerInternal);
2029 reset(mMockContext.settings);
2030
2031 dpm.setMaximumTimeToLock(admin2, 10);
2032 verifyScreenTimeoutCall(10, true);
2033 reset(mMockContext.powerManagerInternal);
2034 reset(mMockContext.settings);
2035
2036 // There's no restriction; shold be set to MAX.
2037 dpm.setMaximumTimeToLock(admin2, 0);
2038 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2039 }
2040
Michal Karpinski943aabd2016-10-06 11:09:25 +01002041 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2042 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2043 setupDeviceOwner();
2044 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2045
2046 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
2047 final long ONE_MINUTE = 60 * 1000;
2048
2049 // aggregation should be the default if unset by any admin
2050 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2051 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2052
2053 // admin not participating by default
2054 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2055
2056 //clamping from the top
2057 dpm.setRequiredStrongAuthTimeout(admin1,
2058 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2059 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2060 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2061 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2062 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2063
2064 // 0 means default
2065 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2066 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2067 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2068 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2069
2070 // clamping from the bottom
2071 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2072 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2073 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2074
2075 // value within range
2076 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2077 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS
2078 + ONE_MINUTE);
2079 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS
2080 + ONE_MINUTE);
2081
2082 // reset to default
2083 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2084 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2085 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2086 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2087
2088 // negative value
2089 try {
2090 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2091 fail("Didn't throw IllegalArgumentException");
2092 } catch (IllegalArgumentException iae) {
2093 }
2094 }
2095
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002096 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2097 boolean shouldStayOnWhilePluggedInBeCleared) {
2098 if (expectedTimeout == null) {
2099 verify(mMockContext.powerManagerInternal, times(0))
2100 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2101 } else {
2102 verify(mMockContext.powerManagerInternal, times(1))
2103 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2104 }
2105 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2106 // UnfinishedVerificationException.
2107 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002108
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002109 public void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002110 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2111 .thenReturn(false);
2112 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2113 .thenReturn(false);
2114 initializeDpms();
2115 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2116 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2117 .thenReturn(true);
2118 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2119
2120 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002121 }
Victor Chang3e794af2016-03-04 13:48:17 +00002122
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002123 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2124 setup_DeviceAdminFeatureOff();
Victor Chang3e794af2016-03-04 13:48:17 +00002125 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2126 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2127 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2128 false);
2129 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2130 }
2131
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002132 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2133 setup_DeviceAdminFeatureOff();
2134 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2135 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2136 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2137 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2138 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2139 assertCheckProvisioningPreCondition(
2140 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2141 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2142 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2143 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2144 }
2145
2146 public void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002147 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2148 .thenReturn(false);
2149 initializeDpms();
2150 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2151 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2152 .thenReturn(true);
2153 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2154
2155 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002156 }
Victor Chang3e794af2016-03-04 13:48:17 +00002157
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002158 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2159 setup_ManagedProfileFeatureOff();
Victor Chang3e794af2016-03-04 13:48:17 +00002160 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2161 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2162 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2163 false);
2164 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2165
2166 // Test again when split user is on
2167 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2168 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2169 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2170 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2171 true);
2172 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2173 }
2174
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002175 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2176 setup_ManagedProfileFeatureOff();
2177 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2178 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2179 DevicePolicyManager.CODE_OK);
2180 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2181 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2182 assertCheckProvisioningPreCondition(
2183 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2184 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2185 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2186 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2187
2188 // Test again when split user is on
2189 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2190 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2191 DevicePolicyManager.CODE_OK);
2192 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2193 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2194 assertCheckProvisioningPreCondition(
2195 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2196 DevicePolicyManager.CODE_OK);
2197 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2198 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2199 }
2200
2201 public void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002202 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2203 .thenReturn(true);
2204 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2205 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2206 .thenReturn(true);
2207 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2208
2209 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002210 }
Victor Chang3e794af2016-03-04 13:48:17 +00002211
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002212 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2213 setup_nonSplitUser_firstBoot_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002214 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2215 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2216 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2217 false /* because of non-split user */);
2218 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2219 false /* because of non-split user */);
2220 }
2221
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002222 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002223 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002224 setup_nonSplitUser_firstBoot_primaryUser();
2225 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2226 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2227 DevicePolicyManager.CODE_OK);
2228 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2229 DevicePolicyManager.CODE_OK);
2230 assertCheckProvisioningPreCondition(
2231 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2232 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2233 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2234 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2235 }
2236
2237 public void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002238 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2239 .thenReturn(true);
2240 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2241 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2242 .thenReturn(true);
2243 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2244
2245 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002246 }
Victor Chang3e794af2016-03-04 13:48:17 +00002247
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002248 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2249 throws Exception {
2250 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002251 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2252 false/* because of completed device setup */);
2253 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2254 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2255 false/* because of non-split user */);
2256 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2257 false/* because of non-split user */);
2258 }
2259
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002260 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2261 throws Exception {
2262 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2263 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2264 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2265 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2266 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2267 DevicePolicyManager.CODE_OK);
2268 assertCheckProvisioningPreCondition(
2269 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2270 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2271 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2272 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2273 }
2274
2275 public void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002276 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2277 .thenReturn(true);
2278 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2279 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2280 .thenReturn(false);
2281 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2282
2283 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002284 }
Victor Chang3e794af2016-03-04 13:48:17 +00002285
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002286 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2287 setup_splitUser_firstBoot_systemUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002288 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2289 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2290 false /* because canAddMoreManagedProfiles returns false */);
2291 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2292 true);
2293 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2294 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002295 }
2296
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002297 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2298 throws Exception {
2299 setup_splitUser_firstBoot_systemUser();
2300 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2301 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2302 DevicePolicyManager.CODE_OK);
2303 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002304 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002305 assertCheckProvisioningPreCondition(
2306 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2307 DevicePolicyManager.CODE_OK);
2308 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2309 DevicePolicyManager.CODE_SYSTEM_USER);
2310 }
2311
2312 public void setup_splitUser_afterDeviceSetup_systemUser() 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(true);
2316 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2317 .thenReturn(false);
2318 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2319
2320 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002321 }
Victor Chang3e794af2016-03-04 13:48:17 +00002322
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002323 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2324 setup_splitUser_afterDeviceSetup_systemUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002325 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2326 true/* it's undefined behavior. Can be changed into false in the future */);
2327 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2328 false /* because canAddMoreManagedProfiles returns false */);
2329 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2330 true/* it's undefined behavior. Can be changed into false in the future */);
2331 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2332 false/* because calling uid is system user */);
2333 }
2334
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002335 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2336 throws Exception {
2337 setup_splitUser_afterDeviceSetup_systemUser();
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,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002342 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002343 assertCheckProvisioningPreCondition(
2344 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2345 DevicePolicyManager.CODE_OK);
2346 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2347 DevicePolicyManager.CODE_SYSTEM_USER);
2348 }
2349
2350 public void setup_splitUser_firstBoot_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(true);
2354 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2355 true)).thenReturn(true);
2356 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2357
2358 mContext.binder.callingUid = DpmMockContext.CALLER_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_splitUser_firstBoot_primaryUser() throws Exception {
2362 setup_splitUser_firstBoot_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002363 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2364 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2365 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2366 true);
2367 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002368 }
2369
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002370 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002371 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002372 setup_splitUser_firstBoot_primaryUser();
2373 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2374 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2375 DevicePolicyManager.CODE_OK);
2376 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2377 DevicePolicyManager.CODE_OK);
2378 assertCheckProvisioningPreCondition(
2379 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2380 DevicePolicyManager.CODE_OK);
2381 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2382 DevicePolicyManager.CODE_OK);
2383 }
2384
2385 public void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002386 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2387 .thenReturn(true);
2388 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2389 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2390 true)).thenReturn(true);
2391 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2392
2393 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002394 }
Victor Chang3e794af2016-03-04 13:48:17 +00002395
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002396 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2397 throws Exception {
2398 setup_splitUser_afterDeviceSetup_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002399 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2400 true/* it's undefined behavior. Can be changed into false in the future */);
2401 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2402 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2403 true/* it's undefined behavior. Can be changed into false in the future */);
2404 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2405 false/* because user setup completed */);
2406 }
2407
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002408 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002409 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002410 setup_splitUser_afterDeviceSetup_primaryUser();
2411 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2412 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2413 DevicePolicyManager.CODE_OK);
2414 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2415 DevicePolicyManager.CODE_OK);
2416 assertCheckProvisioningPreCondition(
2417 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2418 DevicePolicyManager.CODE_OK);
2419 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2420 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2421 }
2422
2423 public void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002424 setDeviceOwner();
2425
2426 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2427 .thenReturn(true);
2428 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2429 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2430 .thenReturn(false);
2431 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2432
2433 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002434 }
Victor Chang3e794af2016-03-04 13:48:17 +00002435
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002436 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2437 throws Exception {
2438 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002439 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2440 false /* can't provision managed profile on system user */);
2441 }
2442
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002443 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002444 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002445 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2446 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2447 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2448 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2449 }
2450
2451 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002452 setDeviceOwner();
2453
2454 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2455 .thenReturn(true);
2456 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2457 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2458 true)).thenReturn(true);
2459 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2460
2461 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002462 }
Victor Chang3e794af2016-03-04 13:48:17 +00002463
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002464 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2465 throws Exception {
2466 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002467 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2468 }
2469
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002470 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002471 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002472 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2473 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2474 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2475 DevicePolicyManager.CODE_OK);
2476 }
2477
2478 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002479 setDeviceOwner();
2480
2481 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2482 .thenReturn(true);
2483 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002484 when(mContext.userManager.hasUserRestriction(
2485 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
2486 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002487 .thenReturn(true);
2488 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002489 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002490 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2491 true)).thenReturn(true);
2492 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2493
2494 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002495 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002496
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002497 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2498 throws Exception {
2499 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Nicolas Prevot56400a42016-11-10 12:57:54 +00002500 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2501 }
2502
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002503 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2504 throws Exception {
2505 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2506 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2507 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2508 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2509 }
2510
2511 public void testCheckProvisioningPreCondition_permission() {
2512 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2513 try {
2514 dpm.checkProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE);
2515 fail("Didn't throw SecurityException");
2516 } catch (SecurityException expected) {
2517 }
2518 }
2519
Victor Chang3577ed22016-08-25 18:49:26 +01002520 public void testForceUpdateUserSetupComplete_permission() {
2521 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2522 try {
2523 dpm.forceUpdateUserSetupComplete();
2524 fail("Didn't throw SecurityException");
2525 } catch (SecurityException expected) {
2526 }
2527 }
2528
2529 public void testForceUpdateUserSetupComplete_systemUser() {
2530 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2531 // GIVEN calling from user 20
2532 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2533 try {
2534 dpm.forceUpdateUserSetupComplete();
2535 fail("Didn't throw SecurityException");
2536 } catch (SecurityException expected) {
2537 }
2538 }
2539
2540 public void testForceUpdateUserSetupComplete_userbuild() {
2541 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2542 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2543
2544 final int userId = UserHandle.USER_SYSTEM;
2545 // GIVEN userComplete is false in SettingsProvider
2546 setUserSetupCompleteForUser(false, userId);
2547
2548 // GIVEN userComplete is true in DPM
2549 DevicePolicyManagerService.DevicePolicyData userData =
2550 new DevicePolicyManagerService.DevicePolicyData(userId);
2551 userData.mUserSetupComplete = true;
2552 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2553
2554 // GIVEN it's user build
2555 mContext.buildMock.isDebuggable = false;
2556
2557 assertTrue(dpms.hasUserSetupCompleted());
2558
2559 dpm.forceUpdateUserSetupComplete();
2560
2561 // THEN the state in dpms is not changed
2562 assertTrue(dpms.hasUserSetupCompleted());
2563 }
2564
2565 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2566 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2567 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2568
2569 final int userId = UserHandle.USER_SYSTEM;
2570 // GIVEN userComplete is false in SettingsProvider
2571 setUserSetupCompleteForUser(false, userId);
2572
2573 // GIVEN userComplete is true in DPM
2574 DevicePolicyManagerService.DevicePolicyData userData =
2575 new DevicePolicyManagerService.DevicePolicyData(userId);
2576 userData.mUserSetupComplete = true;
2577 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2578
2579 // GIVEN it's userdebug build
2580 mContext.buildMock.isDebuggable = true;
2581
2582 assertTrue(dpms.hasUserSetupCompleted());
2583
2584 dpm.forceUpdateUserSetupComplete();
2585
2586 // THEN the state in dpms is not changed
2587 assertFalse(dpms.hasUserSetupCompleted());
2588 }
2589
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002590 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002591 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002592 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2593 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2594 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2595 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002596 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002597 }
2598
2599 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2600 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2601 setupDeviceOwner();
2602 when(mContext.userManager.getUserCount()).thenReturn(1);
2603 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2604 .thenReturn(true);
2605
2606 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002607 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002608
2609 // Enabling logging should not change the timestamp.
2610 dpm.setSecurityLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002611 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002612
2613 // Retrieving the logs should update the timestamp.
2614 final long beforeRetrieval = System.currentTimeMillis();
2615 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002616 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002617 final long afterRetrieval = System.currentTimeMillis();
2618 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2619 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2620
2621 // Retrieving the pre-boot logs should update the timestamp.
2622 Thread.sleep(2);
2623 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002624 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002625 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2626
2627 // Checking the timestamp again should not change it.
2628 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002629 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002630
2631 // Retrieving the logs again should update the timestamp.
2632 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002633 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002634 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2635
2636 // Disabling logging should not change the timestamp.
2637 Thread.sleep(2);
2638 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002639 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002640
2641 // Restarting the DPMS should not lose the timestamp.
2642 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002643 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002644
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002645 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2646 mContext.binder.callingUid = 1234567;
2647 mContext.callerPermissions.add(permission.MANAGE_USERS);
2648 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2649 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2650
2651 // System can retrieve the timestamp.
2652 mContext.binder.clearCallingIdentity();
2653 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2654
2655 // Removing the device owner should clear the timestamp.
2656 clearDeviceOwner();
2657 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002658 }
2659
2660 public void testGetLastBugReportRequestTime() throws Exception {
2661 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2662 setupDeviceOwner();
2663 when(mContext.userManager.getUserCount()).thenReturn(1);
2664 mContext.packageName = admin1.getPackageName();
2665 mContext.applicationInfo = new ApplicationInfo();
2666 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2667 .thenReturn(Color.WHITE);
2668 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2669 anyObject())).thenReturn(Color.WHITE);
2670
2671 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002672 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002673
2674 // Requesting a bug report should update the timestamp.
2675 final long beforeRequest = System.currentTimeMillis();
2676 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002677 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002678 final long afterRequest = System.currentTimeMillis();
2679 assertTrue(bugReportRequestTime >= beforeRequest);
2680 assertTrue(bugReportRequestTime <= afterRequest);
2681
2682 // Checking the timestamp again should not change it.
2683 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002684 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002685
2686 // Restarting the DPMS should not lose the timestamp.
2687 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002688 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002689
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002690 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2691 mContext.binder.callingUid = 1234567;
2692 mContext.callerPermissions.add(permission.MANAGE_USERS);
2693 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2694 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2695
2696 // System can retrieve the timestamp.
2697 mContext.binder.clearCallingIdentity();
2698 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2699
2700 // Removing the device owner should clear the timestamp.
2701 clearDeviceOwner();
2702 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002703 }
2704
2705 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2706 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2707 setupDeviceOwner();
2708 when(mContext.userManager.getUserCount()).thenReturn(1);
2709 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2710 .thenReturn(true);
2711
2712 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002713 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002714
2715 // Attempting to retrieve logs without enabling logging should not change the timestamp.
2716 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002717 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002718
2719 // Enabling logging should not change the timestamp.
2720 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002721 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002722
2723 // Retrieving the logs should update the timestamp.
2724 final long beforeRetrieval = System.currentTimeMillis();
2725 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002726 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002727 final long afterRetrieval = System.currentTimeMillis();
2728 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
2729 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
2730
2731 // Checking the timestamp again should not change it.
2732 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002733 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002734
2735 // Retrieving the logs again should update the timestamp.
2736 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002737 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002738 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
2739
2740 // Disabling logging should not change the timestamp.
2741 Thread.sleep(2);
2742 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002743 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002744
2745 // Restarting the DPMS should not lose the timestamp.
2746 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002747 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2748
2749 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2750 mContext.binder.callingUid = 1234567;
2751 mContext.callerPermissions.add(permission.MANAGE_USERS);
2752 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2753 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2754
2755 // System can retrieve the timestamp.
2756 mContext.binder.clearCallingIdentity();
2757 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2758
2759 // Removing the device owner should clear the timestamp.
2760 clearDeviceOwner();
2761 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002762 }
2763
Tony Mak2f26b792016-11-28 17:54:51 +00002764 public void testGetBindDeviceAdminTargetUsers() throws Exception {
2765 // Setup device owner.
2766 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2767 setupDeviceOwner();
2768
2769 // Only device owner is setup, the result list should be empty.
2770 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2771 MoreAsserts.assertEmpty(targetUsers);
2772
2773 // Setup a managed profile managed by the same admin.
2774 final int MANAGED_PROFILE_USER_ID = 15;
2775 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2776 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2777
2778 // Add a secondary user, it should never talk with.
2779 final int ANOTHER_USER_ID = 36;
2780 mContext.addUser(ANOTHER_USER_ID, 0);
2781
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002782 // Since the managed profile is not affiliated, they should not be allowed to talk to each
2783 // other.
2784 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2785 MoreAsserts.assertEmpty(targetUsers);
2786
2787 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2788 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2789 MoreAsserts.assertEmpty(targetUsers);
2790
2791 // Setting affiliation ids
2792 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
2793 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2794 dpm.setAffiliationIds(admin1, userAffiliationIds);
2795
2796 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2797 dpm.setAffiliationIds(admin1, userAffiliationIds);
2798
Tony Mak2f26b792016-11-28 17:54:51 +00002799 // Calling from device owner admin, the result list should just contain the managed
2800 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002801 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00002802 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2803 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
2804
2805 // Calling from managed profile admin, the result list should just contain the system
2806 // user id.
2807 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2808 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2809 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002810
2811 // Changing affiliation ids in one
2812 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
2813
2814 // Since the managed profile is not affiliated any more, they should not be allowed to talk
2815 // to each other.
2816 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2817 MoreAsserts.assertEmpty(targetUsers);
2818
2819 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2820 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2821 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00002822 }
2823
2824 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
2825 // Setup a device owner.
2826 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2827 setupDeviceOwner();
2828
2829 // Set up a managed profile managed by different package.
2830 final int MANAGED_PROFILE_USER_ID = 15;
2831 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2832 final ComponentName adminDifferentPackage =
2833 new ComponentName("another.package", "whatever.class");
2834 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
2835
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002836 // Setting affiliation ids
2837 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
2838 dpm.setAffiliationIds(admin1, userAffiliationIds);
2839
2840 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2841 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
2842
Tony Mak2f26b792016-11-28 17:54:51 +00002843 // Calling from device owner admin, we should get zero bind device admin target users as
2844 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002845 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00002846 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2847 MoreAsserts.assertEmpty(targetUsers);
2848
2849 // Calling from managed profile admin, we should still get zero target users for the same
2850 // reason.
2851 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2852 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
2853 MoreAsserts.assertEmpty(targetUsers);
2854 }
2855
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01002856 public void testIsDeviceManaged() throws Exception {
2857 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2858 setupDeviceOwner();
2859
2860 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
2861 // find out that the device has a device owner.
2862 assertTrue(dpm.isDeviceManaged());
2863 mContext.binder.callingUid = 1234567;
2864 mContext.callerPermissions.add(permission.MANAGE_USERS);
2865 assertTrue(dpm.isDeviceManaged());
2866 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2867 mContext.binder.clearCallingIdentity();
2868 assertTrue(dpm.isDeviceManaged());
2869
2870 clearDeviceOwner();
2871
2872 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
2873 // not have a device owner.
2874 mContext.binder.callingUid = 1234567;
2875 mContext.callerPermissions.add(permission.MANAGE_USERS);
2876 assertFalse(dpm.isDeviceManaged());
2877 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2878 mContext.binder.clearCallingIdentity();
2879 assertFalse(dpm.isDeviceManaged());
2880 }
2881
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01002882 public void testDeviceOwnerOrganizationName() throws Exception {
2883 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2884 setupDeviceOwner();
2885
2886 dpm.setOrganizationName(admin1, "organization");
2887
2888 // Device owner can retrieve organization managing the device.
2889 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2890
2891 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
2892 mContext.binder.callingUid = 1234567;
2893 mContext.callerPermissions.add(permission.MANAGE_USERS);
2894 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2895 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2896
2897 // System can retrieve organization managing the device.
2898 mContext.binder.clearCallingIdentity();
2899 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2900
2901 // Removing the device owner clears the organization managing the device.
2902 clearDeviceOwner();
2903 assertNull(dpm.getDeviceOwnerOrganizationName());
2904 }
2905
Victor Chang3e794af2016-03-04 13:48:17 +00002906 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
2907 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
2908 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
2909 dpms.notifyChangeToContentObserver(
2910 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
2911 }
2912
2913 private void assertProvisioningAllowed(String action, boolean expected) {
2914 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
2915 dpm.isProvisioningAllowed(action));
2916 }
Tony Mak2f26b792016-11-28 17:54:51 +00002917
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002918 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
2919 assertEquals("checkProvisioningPreCondition(" + action + ") returning unexpected result",
2920 provisioningCondition, dpm.checkProvisioningPreCondition(action));
2921 }
2922
Tony Mak2f26b792016-11-28 17:54:51 +00002923 /**
2924 * Setup a managed profile with the specified admin and its uid.
2925 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
2926 * @param adminUid uid of the admin package.
2927 * @param copyFromAdmin package information for {@code admin} will be built based on this
2928 * component's information.
2929 */
2930 private void addManagedProfile(
2931 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
2932 final int userId = UserHandle.getUserId(adminUid);
2933 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
2934 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2935 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
2936 dpm.setActiveAdmin(admin, false, userId);
2937 assertTrue(dpm.setProfileOwner(admin, null, userId));
2938 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2939 }
Victor Chang3e794af2016-03-04 13:48:17 +00002940}