blob: 98516e10c6517cf98d7901abe518b141ee9dacc3 [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;
Michal Karpinskid084ca52017-01-18 15:54:18 +000064import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070065
66import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070067import static org.mockito.Matchers.anyInt;
Michal Karpinskid084ca52017-01-18 15:54:18 +000068import static org.mockito.Matchers.anyLong;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010069import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070070import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070071import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070072import static org.mockito.Matchers.isNull;
Esteban Talavera548a04b2016-12-20 15:22:30 +000073import static org.mockito.Mockito.atLeast;
Makoto Onukib643fb02015-09-22 15:03:44 -070074import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070075import static org.mockito.Mockito.doReturn;
Robin Leed2a73ed2016-12-19 09:07:16 +000076import static org.mockito.Mockito.never;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080077import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070078import static org.mockito.Mockito.times;
79import static org.mockito.Mockito.verify;
80import static org.mockito.Mockito.when;
81
82/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070083 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +000084 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070085 m FrameworksServicesTests &&
86 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000087 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070088 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080089 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070090
91 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +000092 *
93 * , or:
94 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095 */
Benjamin Franz6d009032016-01-25 18:56:38 +000096@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070097public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000098 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
99 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
100 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
101
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700102 private DpmMockContext mContext;
103 public DevicePolicyManager dpm;
104 public DevicePolicyManagerServiceTestable dpms;
105
106 @Override
107 protected void setUp() throws Exception {
108 super.setUp();
109
110 mContext = getContext();
111
112 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
113 .thenReturn(true);
114
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800115 // By default, pretend all users are running and unlocked.
116 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
117
Makoto Onukia52562c2015-10-01 16:12:31 -0700118 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700119
Makoto Onukid932f762015-09-29 16:53:38 -0700120 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
121 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
122 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800123 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700124
Makoto Onukib643fb02015-09-22 15:03:44 -0700125 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700126 }
127
Makoto Onukia52562c2015-10-01 16:12:31 -0700128 private void initializeDpms() {
129 // Need clearCallingIdentity() to pass permission checks.
130 final long ident = mContext.binder.clearCallingIdentity();
131 try {
132 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
133
134 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
135
136 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
137 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
138
139 dpm = new DevicePolicyManagerTestable(mContext, dpms);
140 } finally {
141 mContext.binder.restoreCallingIdentity(ident);
142 }
143 }
144
Makoto Onukib643fb02015-09-22 15:03:44 -0700145 private void setUpUserManager() {
146 // Emulate UserManager.set/getApplicationRestriction().
147 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
148
149 // UM.setApplicationRestrictions() will save to appRestrictions.
150 doAnswer(new Answer<Void>() {
151 @Override
152 public Void answer(InvocationOnMock invocation) throws Throwable {
153 String pkg = (String) invocation.getArguments()[0];
154 Bundle bundle = (Bundle) invocation.getArguments()[1];
155 UserHandle user = (UserHandle) invocation.getArguments()[2];
156
157 appRestrictions.put(Pair.create(pkg, user), bundle);
158
159 return null;
160 }
161 }).when(mContext.userManager).setApplicationRestrictions(
162 anyString(), any(Bundle.class), any(UserHandle.class));
163
164 // UM.getApplicationRestrictions() will read from appRestrictions.
165 doAnswer(new Answer<Bundle>() {
166 @Override
167 public Bundle answer(InvocationOnMock invocation) throws Throwable {
168 String pkg = (String) invocation.getArguments()[0];
169 UserHandle user = (UserHandle) invocation.getArguments()[1];
170
171 return appRestrictions.get(Pair.create(pkg, user));
172 }
173 }).when(mContext.userManager).getApplicationRestrictions(
174 anyString(), any(UserHandle.class));
175
Makoto Onukid932f762015-09-29 16:53:38 -0700176 // Add the first secondary user.
177 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700178 }
179
180 private void setAsProfileOwner(ComponentName admin) {
181 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
182 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
183
Makoto Onukia4f11972015-10-01 13:19:58 -0700184 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700185 dpm.setActiveAdmin(admin, /* replace =*/ false);
186
187 // Fire!
188 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
189
190 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700191 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700192 }
193
194 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700195 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
196 .thenReturn(false);
197
198 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
199 new DevicePolicyManagerServiceTestable(mContext, dataDir);
200
201 // If the device has no DPMS feature, it shouldn't register the local service.
202 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
203 }
204
205 /**
206 * Caller doesn't have proper permissions.
207 */
208 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700209 // 1. Failure cases.
210
211 // Caller doesn't have MANAGE_DEVICE_ADMINS.
212 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700213 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700214 fail("Didn't throw SecurityException");
215 } catch (SecurityException expected) {
216 }
217
218 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
219 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
220 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700221 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700222 fail("Didn't throw SecurityException");
223 } catch (SecurityException expected) {
224 }
225 }
226
Makoto Onukif76b06a2015-09-22 15:03:44 -0700227 /**
228 * Test for:
229 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800230 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700231 * {@link DevicePolicyManager#isAdminActive}
232 * {@link DevicePolicyManager#isAdminActiveAsUser}
233 * {@link DevicePolicyManager#getActiveAdmins}
234 * {@link DevicePolicyManager#getActiveAdminsAsUser}
235 */
236 public void testSetActiveAdmin() throws Exception {
237 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700238 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
239
Makoto Onukif76b06a2015-09-22 15:03:44 -0700240 // 2. Call the API.
241 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700242
243 // 3. Verify internal calls.
244
245 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700246 verify(mContext.spiedContext).sendBroadcastAsUser(
247 MockUtils.checkIntentAction(
248 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
249 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
250 verify(mContext.spiedContext).sendBroadcastAsUser(
251 MockUtils.checkIntentAction(
252 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700253 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
254
Makoto Onukif76b06a2015-09-22 15:03:44 -0700255 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
256 eq(admin1.getPackageName()),
257 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
258 eq(PackageManager.DONT_KILL_APP),
259 eq(DpmMockContext.CALLER_USER_HANDLE),
260 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700261
262 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700263
264 // Make sure it's active admin1.
265 assertTrue(dpm.isAdminActive(admin1));
266 assertFalse(dpm.isAdminActive(admin2));
267 assertFalse(dpm.isAdminActive(admin3));
268
269 // But not admin1 for a different user.
270
271 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
272 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
273 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
274
275 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
276 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
277
278 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
279
280 // Next, add one more admin.
281 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700282 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
283 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700284
285 dpm.setActiveAdmin(admin2, /* replace =*/ false);
286
287 // Now we have two admins.
288 assertTrue(dpm.isAdminActive(admin1));
289 assertTrue(dpm.isAdminActive(admin2));
290 assertFalse(dpm.isAdminActive(admin3));
291
292 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
293 // again. (times(1) because it was previously called for admin1)
294 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
295 eq(admin1.getPackageName()),
296 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
297 eq(PackageManager.DONT_KILL_APP),
298 eq(DpmMockContext.CALLER_USER_HANDLE),
299 anyString());
300
301 // 4. Add the same admin1 again without replace, which should throw.
302 try {
303 dpm.setActiveAdmin(admin1, /* replace =*/ false);
304 fail("Didn't throw");
305 } catch (IllegalArgumentException expected) {
306 }
307
308 // 5. Add the same admin1 again with replace, which should succeed.
309 dpm.setActiveAdmin(admin1, /* replace =*/ true);
310
311 // TODO make sure it's replaced.
312
313 // 6. Test getActiveAdmins()
314 List<ComponentName> admins = dpm.getActiveAdmins();
315 assertEquals(2, admins.size());
316 assertEquals(admin1, admins.get(0));
317 assertEquals(admin2, admins.get(1));
318
319 // Another user has no admins.
320 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
321
322 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
323 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
324
325 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
326 }
327
Makoto Onukid932f762015-09-29 16:53:38 -0700328 public void testSetActiveAdmin_multiUsers() throws Exception {
329
330 final int ANOTHER_USER_ID = 100;
331 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
332
333 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
334
335 // Set up pacakge manager for the other user.
336 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700337
338 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
339
340 dpm.setActiveAdmin(admin1, /* replace =*/ false);
341
342 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
343 dpm.setActiveAdmin(admin2, /* replace =*/ false);
344
345
346 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
347 assertTrue(dpm.isAdminActive(admin1));
348 assertFalse(dpm.isAdminActive(admin2));
349
350 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
351 assertFalse(dpm.isAdminActive(admin1));
352 assertTrue(dpm.isAdminActive(admin2));
353 }
354
Makoto Onukif76b06a2015-09-22 15:03:44 -0700355 /**
356 * Test for:
357 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800358 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700359 */
360 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
361 // 1. Make sure the caller has proper permissions.
362 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
363
364 dpm.setActiveAdmin(admin1, /* replace =*/ false);
365 assertTrue(dpm.isAdminActive(admin1));
366
367 // Add the same admin1 again without replace, which should throw.
368 try {
369 dpm.setActiveAdmin(admin1, /* replace =*/ false);
370 fail("Didn't throw");
371 } catch (IllegalArgumentException expected) {
372 }
373 }
374
375 /**
376 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800377 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
378 * BIND_DEVICE_ADMIN.
379 */
380 public void testSetActiveAdmin_permissionCheck() throws Exception {
381 // 1. Make sure the caller has proper permissions.
382 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
383
384 try {
385 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
386 fail();
387 } catch (IllegalArgumentException expected) {
388 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
389 }
390 assertFalse(dpm.isAdminActive(adminNoPerm));
391
392 // Change the target API level to MNC. Now it can be set as DA.
393 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
394 VERSION_CODES.M);
395 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
396 assertTrue(dpm.isAdminActive(adminNoPerm));
397
398 // TODO Test the "load from the file" case where DA will still be loaded even without
399 // BIND_DEVICE_ADMIN and target API is N.
400 }
401
402 /**
403 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700404 * {@link DevicePolicyManager#removeActiveAdmin}
405 */
406 public void testRemoveActiveAdmin_SecurityException() {
407 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
408
409 // Add admin.
410
411 dpm.setActiveAdmin(admin1, /* replace =*/ false);
412
413 assertTrue(dpm.isAdminActive(admin1));
414
415 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
416
417 // Directly call the DPMS method with a different userid, which should fail.
418 try {
419 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
420 fail("Didn't throw SecurityException");
421 } catch (SecurityException expected) {
422 }
423
424 // Try to remove active admin with a different caller userid should fail too, without
425 // having MANAGE_DEVICE_ADMINS.
426 mContext.callerPermissions.clear();
427
Makoto Onukid932f762015-09-29 16:53:38 -0700428 // Change the caller, and call into DPMS directly with a different user-id.
429
Makoto Onukif76b06a2015-09-22 15:03:44 -0700430 mContext.binder.callingUid = 1234567;
431 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700432 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700433 fail("Didn't throw SecurityException");
434 } catch (SecurityException expected) {
435 }
436 }
437
438 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800439 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
440 * (because we can't send the remove broadcast).
441 */
442 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
443 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
444
445 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
446
447 // Add admin.
448
449 dpm.setActiveAdmin(admin1, /* replace =*/ false);
450
451 assertTrue(dpm.isAdminActive(admin1));
452
453 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
454
455 // 1. User not unlocked.
456 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
457 .thenReturn(false);
458 try {
459 dpm.removeActiveAdmin(admin1);
460 fail("Didn't throw IllegalStateException");
461 } catch (IllegalStateException expected) {
462 MoreAsserts.assertContainsRegex(
463 "User must be running and unlocked", expected.getMessage());
464 }
465
466 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
467
468 // 2. User unlocked.
469 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
470 .thenReturn(true);
471
472 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700473 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800474 }
475
476 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700477 * Test for:
478 * {@link DevicePolicyManager#removeActiveAdmin}
479 */
Makoto Onukid932f762015-09-29 16:53:38 -0700480 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700481 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
482
483 // Add admin1.
484
485 dpm.setActiveAdmin(admin1, /* replace =*/ false);
486
487 assertTrue(dpm.isAdminActive(admin1));
488 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
489
490 // Different user, but should work, because caller has proper permissions.
491 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700492
493 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700494 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700495
496 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700497 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700498
499 // TODO DO Still can't be removed in this case.
500 }
501
502 /**
503 * Test for:
504 * {@link DevicePolicyManager#removeActiveAdmin}
505 */
506 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
507 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
508 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
509
510 // Add admin1.
511
512 dpm.setActiveAdmin(admin1, /* replace =*/ false);
513
514 assertTrue(dpm.isAdminActive(admin1));
515 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
516
517 // Broadcast from saveSettingsLocked().
518 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
519 MockUtils.checkIntentAction(
520 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
521 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
522
523 // Remove. No permissions, but same user, so it'll work.
524 mContext.callerPermissions.clear();
525 dpm.removeActiveAdmin(admin1);
526
Makoto Onukif76b06a2015-09-22 15:03:44 -0700527 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
528 MockUtils.checkIntentAction(
529 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
530 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
531 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700532 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700533 eq(dpms.mHandler),
534 eq(Activity.RESULT_OK),
535 isNull(String.class),
536 isNull(Bundle.class));
537
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700538 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700539
540 // Again broadcast from saveSettingsLocked().
541 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
542 MockUtils.checkIntentAction(
543 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
544 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
545
546 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700547 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700548
549 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000550 * Test for: @{link DevicePolicyManager#setActivePasswordState}
551 *
552 * Validates that when the password for a user changes, the notification broadcast intent
553 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
554 * addition to ones in the original user.
555 */
556 public void testSetActivePasswordState_sendToProfiles() throws Exception {
557 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
558
559 final int MANAGED_PROFILE_USER_ID = 78;
560 final int MANAGED_PROFILE_ADMIN_UID =
561 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
562
563 // Setup device owner.
564 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
565 mContext.packageName = admin1.getPackageName();
566 setupDeviceOwner();
567
568 // Add a managed profile belonging to the system user.
569 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
570
571 // Change the parent user's password.
572 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
573
574 // Both the device owner and the managed profile owner should receive this broadcast.
575 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
576 intent.setComponent(admin1);
577 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
578
579 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
580 MockUtils.checkIntent(intent),
581 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
582 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
583 MockUtils.checkIntent(intent),
584 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
585 }
586
587 /**
588 * Test for: @{link DevicePolicyManager#setActivePasswordState}
589 *
590 * Validates that when the password for a managed profile changes, the notification broadcast
591 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
592 * its parent.
593 */
594 public void testSetActivePasswordState_notSentToParent() throws Exception {
595 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
596
597 final int MANAGED_PROFILE_USER_ID = 78;
598 final int MANAGED_PROFILE_ADMIN_UID =
599 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
600
601 // Setup device owner.
602 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
603 mContext.packageName = admin1.getPackageName();
604 doReturn(true).when(mContext.lockPatternUtils)
605 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
606 setupDeviceOwner();
607
608 // Add a managed profile belonging to the system user.
609 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
610
611 // Change the profile's password.
612 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
613
614 // Both the device owner and the managed profile owner should receive this broadcast.
615 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
616 intent.setComponent(admin1);
617 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
618
619 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
620 MockUtils.checkIntent(intent),
621 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
622 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
623 MockUtils.checkIntent(intent),
624 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
625 }
626 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000627 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700628 */
629 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000630 setDeviceOwner();
631
632 // Try to set a profile owner on the same user, which should fail.
633 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
634 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
635 try {
636 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
637 fail("IllegalStateException not thrown");
638 } catch (IllegalStateException expected) {
639 assertTrue("Message was: " + expected.getMessage(),
640 expected.getMessage().contains("already has a device owner"));
641 }
642
643 // DO admin can't be deactivated.
644 dpm.removeActiveAdmin(admin1);
645 assertTrue(dpm.isAdminActive(admin1));
646
647 // TODO Test getDeviceOwnerName() too. To do so, we need to change
648 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
649 }
650
651 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700652 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800653 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700654 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
655 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
656
Makoto Onukid932f762015-09-29 16:53:38 -0700657 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700658 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
659
Makoto Onukid932f762015-09-29 16:53:38 -0700660 // Make sure admin1 is installed on system user.
661 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700662
Makoto Onukic8a5a552015-11-19 14:29:12 -0800663 // Check various get APIs.
664 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
665
Makoto Onukib643fb02015-09-22 15:03:44 -0700666 // DO needs to be an DA.
667 dpm.setActiveAdmin(admin1, /* replace =*/ false);
668
669 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700670 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700671
Makoto Onukic8a5a552015-11-19 14:29:12 -0800672 // getDeviceOwnerComponent should return the admin1 component.
673 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
674 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
675
676 // Check various get APIs.
677 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
678
679 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
680 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
681 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
682 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
683
684 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
685
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000686 // Verify internal calls.
687 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
688 eq(admin1.getPackageName()));
689
Makoto Onukib643fb02015-09-22 15:03:44 -0700690 // TODO We should check if the caller has called clearCallerIdentity().
691 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
692 eq(UserHandle.USER_SYSTEM), eq(false));
693
694 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
695 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
696 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
697
Makoto Onukic8a5a552015-11-19 14:29:12 -0800698 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700699 }
700
Makoto Onukic8a5a552015-11-19 14:29:12 -0800701 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
702 final int origCallingUser = mContext.binder.callingUid;
703 final List origPermissions = new ArrayList(mContext.callerPermissions);
704 mContext.callerPermissions.clear();
705
706 mContext.callerPermissions.add(permission.MANAGE_USERS);
707
708 mContext.binder.callingUid = Process.SYSTEM_UID;
709
710 // TODO Test getDeviceOwnerName() too. To do so, we need to change
711 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
712 if (hasDeviceOwner) {
713 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
714 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
715 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
716
717 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
718 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
719 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
720 } else {
721 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
722 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
723 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
724
725 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
726 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
727 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
728 }
729
730 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
731 if (hasDeviceOwner) {
732 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
733 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
734 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
735
736 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
737 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
738 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
739 } else {
740 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
741 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
742 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
743
744 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
745 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
746 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
747 }
748
749 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
750 // Still with MANAGE_USERS.
751 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
752 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
753 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
754
755 if (hasDeviceOwner) {
756 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
757 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
758 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
759 } else {
760 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
761 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
762 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
763 }
764
765 mContext.binder.callingUid = Process.SYSTEM_UID;
766 mContext.callerPermissions.remove(permission.MANAGE_USERS);
767 // System can still call "OnAnyUser" without MANAGE_USERS.
768 if (hasDeviceOwner) {
769 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
770 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
771 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
772
773 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
774 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
775 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
776 } else {
777 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
778 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
779 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
780
781 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
782 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
783 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
784 }
785
786 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
787 // Still no MANAGE_USERS.
788 if (hasDeviceOwner) {
789 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
790 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
791 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
792 } else {
793 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
794 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
795 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
796 }
797
798 try {
799 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
800 fail();
801 } catch (SecurityException expected) {
802 }
803 try {
804 dpm.getDeviceOwnerComponentOnAnyUser();
805 fail();
806 } catch (SecurityException expected) {
807 }
808 try {
809 dpm.getDeviceOwnerUserId();
810 fail();
811 } catch (SecurityException expected) {
812 }
813 try {
814 dpm.getDeviceOwnerNameOnAnyUser();
815 fail();
816 } catch (SecurityException expected) {
817 }
818
819 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
820 // Still no MANAGE_USERS.
821 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
822 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
823 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
824
825 try {
826 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
827 fail();
828 } catch (SecurityException expected) {
829 }
830 try {
831 dpm.getDeviceOwnerComponentOnAnyUser();
832 fail();
833 } catch (SecurityException expected) {
834 }
835 try {
836 dpm.getDeviceOwnerUserId();
837 fail();
838 } catch (SecurityException expected) {
839 }
840 try {
841 dpm.getDeviceOwnerNameOnAnyUser();
842 fail();
843 } catch (SecurityException expected) {
844 }
845
846 // Restore.
847 mContext.binder.callingUid = origCallingUser;
848 mContext.callerPermissions.addAll(origPermissions);
849 }
850
851
Makoto Onukib643fb02015-09-22 15:03:44 -0700852 /**
853 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
854 */
855 public void testSetDeviceOwner_noSuchPackage() {
856 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800857 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700858 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
859 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
860
861 // Call from a process on the system user.
862 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
863
Makoto Onukib643fb02015-09-22 15:03:44 -0700864 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700865 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700866 fail("Didn't throw IllegalArgumentException");
867 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700868 assertTrue("Message was: " + expected.getMessage(),
869 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700870 }
871 }
872
873 public void testSetDeviceOwner_failures() throws Exception {
874 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
875 }
876
Makoto Onukia52562c2015-10-01 16:12:31 -0700877 public void testClearDeviceOwner() throws Exception {
878 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800879 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700880 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
881 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
882
883 // Set admin1 as a DA to the secondary user.
884 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
885
886 dpm.setActiveAdmin(admin1, /* replace =*/ false);
887
888 // Set admin 1 as the DO to the system user.
889
890 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
891 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
892 dpm.setActiveAdmin(admin1, /* replace =*/ false);
893 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
894
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000895 // Verify internal calls.
896 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
897 eq(admin1.getPackageName()));
898
Makoto Onukic8a5a552015-11-19 14:29:12 -0800899 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700900
Makoto Onuki90b89652016-01-28 14:44:18 -0800901 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
902
903 assertTrue(dpm.isAdminActive(admin1));
904 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
905
Makoto Onukia52562c2015-10-01 16:12:31 -0700906 // Set up other mocks.
907 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
908
909 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700910 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700911 eq(admin1.getPackageName()),
912 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800913
914 // But first pretend the user is locked. Then it should fail.
915 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
916 try {
917 dpm.clearDeviceOwnerApp(admin1.getPackageName());
918 fail("Didn't throw IllegalStateException");
919 } catch (IllegalStateException expected) {
920 MoreAsserts.assertContainsRegex(
921 "User must be running and unlocked", expected.getMessage());
922 }
923
924 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800925 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700926 dpm.clearDeviceOwnerApp(admin1.getPackageName());
927
928 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800929 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700930
Makoto Onuki90b89652016-01-28 14:44:18 -0800931 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
932 eq(UserHandle.USER_SYSTEM),
933 MockUtils.checkUserRestrictions(),
934 MockUtils.checkUserRestrictions()
935 );
936
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700937 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100938
939 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
940 // and once for clearing it.
941 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
942 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
943 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700944 // TODO Check other calls.
945 }
946
947 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
948 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800949 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700950 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
951 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
952
953 // Set admin1 as a DA to the secondary user.
954 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
955
956 dpm.setActiveAdmin(admin1, /* replace =*/ false);
957
958 // Set admin 1 as the DO to the system user.
959
960 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
961 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
962 dpm.setActiveAdmin(admin1, /* replace =*/ false);
963 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
964
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000965 // Verify internal calls.
966 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
967 eq(admin1.getPackageName()));
968
Makoto Onukic8a5a552015-11-19 14:29:12 -0800969 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700970
971 // Now call clear from the secondary user, which should throw.
972 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
973
974 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700975 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700976 eq(admin1.getPackageName()),
977 anyInt());
978 try {
979 dpm.clearDeviceOwnerApp(admin1.getPackageName());
980 fail("Didn't throw");
981 } catch (SecurityException e) {
982 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
983 }
984
Makoto Onukic8a5a552015-11-19 14:29:12 -0800985 // DO shouldn't be removed.
986 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700987 }
988
Makoto Onukib643fb02015-09-22 15:03:44 -0700989 public void testSetProfileOwner() throws Exception {
990 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700991
Makoto Onuki90b89652016-01-28 14:44:18 -0800992 // PO admin can't be deactivated.
993 dpm.removeActiveAdmin(admin1);
994 assertTrue(dpm.isAdminActive(admin1));
995
Makoto Onuki803d6752015-10-30 12:58:39 -0700996 // Try setting DO on the same user, which should fail.
997 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
998 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
999 try {
1000 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1001 fail("IllegalStateException not thrown");
1002 } catch (IllegalStateException expected) {
1003 assertTrue("Message was: " + expected.getMessage(),
1004 expected.getMessage().contains("already has a profile owner"));
1005 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001006 }
1007
Makoto Onuki90b89652016-01-28 14:44:18 -08001008 public void testClearProfileOwner() throws Exception {
1009 setAsProfileOwner(admin1);
1010
1011 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1012
1013 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1014 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1015
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001016 // First try when the user is locked, which should fail.
1017 when(mContext.userManager.isUserUnlocked(anyInt()))
1018 .thenReturn(false);
1019 try {
1020 dpm.clearProfileOwner(admin1);
1021 fail("Didn't throw IllegalStateException");
1022 } catch (IllegalStateException expected) {
1023 MoreAsserts.assertContainsRegex(
1024 "User must be running and unlocked", expected.getMessage());
1025 }
1026 // Clear, really.
1027 when(mContext.userManager.isUserUnlocked(anyInt()))
1028 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001029 dpm.clearProfileOwner(admin1);
1030
1031 // Check
1032 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001033 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001034 }
1035
Makoto Onukib643fb02015-09-22 15:03:44 -07001036 public void testSetProfileOwner_failures() throws Exception {
1037 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1038 }
1039
Makoto Onukia52562c2015-10-01 16:12:31 -07001040 public void testGetDeviceOwnerAdminLocked() throws Exception {
1041 checkDeviceOwnerWithMultipleDeviceAdmins();
1042 }
1043
1044 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1045 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1046 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1047 // make sure it gets the right component from the right user.
1048
1049 final int ANOTHER_USER_ID = 100;
1050 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1051
1052 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1053
1054 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001055 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001056 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1057 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1058
1059 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1060
Victor Change29cd472016-03-02 20:57:42 +00001061 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1062
Makoto Onukia52562c2015-10-01 16:12:31 -07001063 // Make sure the admin packge is installed to each user.
1064 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1065 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1066
1067 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1068 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1069
1070 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1071
1072
1073 // Set active admins to the users.
1074 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1075 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1076
1077 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1078 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1079
1080 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1081
1082 // Set DO on the first non-system user.
1083 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1084 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1085
Makoto Onukic8a5a552015-11-19 14:29:12 -08001086 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001087
1088 // Then check getDeviceOwnerAdminLocked().
1089 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1090 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1091 }
1092
1093 /**
1094 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001095 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1096 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001097 *
1098 * We didn't use to persist the DO component class name, but now we do, and the above method
1099 * finds the right component from a package name upon migration.
1100 */
1101 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001102 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001103 checkDeviceOwnerWithMultipleDeviceAdmins();
1104
1105 // Overwrite the device owner setting and clears the clas name.
1106 dpms.mOwners.setDeviceOwner(
1107 new ComponentName(admin2.getPackageName(), ""),
1108 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1109 dpms.mOwners.writeDeviceOwner();
1110
1111 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001112 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001113
1114 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001115 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1116 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001117 initializeDpms();
1118
1119 // Now the DO component name is a full name.
1120 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1121 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001122 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001123 }
1124
Makoto Onukib643fb02015-09-22 15:03:44 -07001125 public void testSetGetApplicationRestriction() {
1126 setAsProfileOwner(admin1);
1127
1128 {
1129 Bundle rest = new Bundle();
1130 rest.putString("KEY_STRING", "Foo1");
1131 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1132 }
1133
1134 {
1135 Bundle rest = new Bundle();
1136 rest.putString("KEY_STRING", "Foo2");
1137 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1138 }
1139
1140 {
1141 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1142 assertNotNull(returned);
1143 assertEquals(returned.size(), 1);
1144 assertEquals(returned.get("KEY_STRING"), "Foo1");
1145 }
1146
1147 {
1148 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1149 assertNotNull(returned);
1150 assertEquals(returned.size(), 1);
1151 assertEquals(returned.get("KEY_STRING"), "Foo2");
1152 }
1153
1154 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1155 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1156 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001157
Esteban Talaverabf60f722015-12-10 16:26:44 +00001158 public void testApplicationRestrictionsManagingApp() throws Exception {
1159 setAsProfileOwner(admin1);
1160
Rubin Xued1928a2016-02-11 17:23:06 +00001161 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001162 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1163 final int appRestrictionsManagerAppId = 20987;
1164 final int appRestrictionsManagerUid = UserHandle.getUid(
1165 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001166 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001167 eq(appRestrictionsManagerPackage),
1168 eq(DpmMockContext.CALLER_USER_HANDLE));
1169 mContext.binder.callingUid = appRestrictionsManagerUid;
1170
Rubin Xued1928a2016-02-11 17:23:06 +00001171 final PackageInfo pi = new PackageInfo();
1172 pi.applicationInfo = new ApplicationInfo();
1173 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1174 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1175 eq(appRestrictionsManagerPackage),
1176 anyInt(),
1177 eq(DpmMockContext.CALLER_USER_HANDLE));
1178
Esteban Talaverabf60f722015-12-10 16:26:44 +00001179 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1180 // delegated that permission yet.
1181 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1182 Bundle rest = new Bundle();
1183 rest.putString("KEY_STRING", "Foo1");
1184 try {
1185 dpm.setApplicationRestrictions(null, "pkg1", rest);
1186 fail("Didn't throw expected SecurityException");
1187 } catch (SecurityException expected) {
1188 MoreAsserts.assertContainsRegex(
1189 "caller cannot manage application restrictions", expected.getMessage());
1190 }
1191 try {
1192 dpm.getApplicationRestrictions(null, "pkg1");
1193 fail("Didn't throw expected SecurityException");
1194 } catch (SecurityException expected) {
1195 MoreAsserts.assertContainsRegex(
1196 "caller cannot manage application restrictions", expected.getMessage());
1197 }
1198
1199 // Check via the profile owner that no restrictions were set.
1200 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1201 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1202
Rubin Xued1928a2016-02-11 17:23:06 +00001203 // Check the API does not allow setting a non-existent package
1204 try {
1205 dpm.setApplicationRestrictionsManagingPackage(admin1,
1206 nonExistAppRestrictionsManagerPackage);
1207 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001208 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001209 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001210 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001211 }
1212
Esteban Talaverabf60f722015-12-10 16:26:44 +00001213 // Let appRestrictionsManagerPackage manage app restrictions
1214 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1215 assertEquals(appRestrictionsManagerPackage,
1216 dpm.getApplicationRestrictionsManagingPackage(admin1));
1217
1218 // Now that package should be able to set and retrieve app restrictions.
1219 mContext.binder.callingUid = appRestrictionsManagerUid;
1220 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1221 dpm.setApplicationRestrictions(null, "pkg1", rest);
1222 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1223 assertEquals(1, returned.size(), 1);
1224 assertEquals("Foo1", returned.get("KEY_STRING"));
1225
1226 // The same app running on a separate user shouldn't be able to manage app restrictions.
1227 mContext.binder.callingUid = UserHandle.getUid(
1228 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1229 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1230 try {
1231 dpm.setApplicationRestrictions(null, "pkg1", rest);
1232 fail("Didn't throw expected SecurityException");
1233 } catch (SecurityException expected) {
1234 MoreAsserts.assertContainsRegex(
1235 "caller cannot manage application restrictions", expected.getMessage());
1236 }
1237
1238 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1239 // too.
1240 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1241 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1242 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1243 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1244
1245 // Removing the ability for the package to manage app restrictions.
1246 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1247 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1248 mContext.binder.callingUid = appRestrictionsManagerUid;
1249 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1250 try {
1251 dpm.setApplicationRestrictions(null, "pkg1", null);
1252 fail("Didn't throw expected SecurityException");
1253 } catch (SecurityException expected) {
1254 MoreAsserts.assertContainsRegex(
1255 "caller cannot manage application restrictions", expected.getMessage());
1256 }
1257 }
1258
Makoto Onukia4f11972015-10-01 13:19:58 -07001259 public void testSetUserRestriction_asDo() throws Exception {
1260 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001261 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001262 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1263 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1264
1265 // First, set DO.
1266
1267 // Call from a process on the system user.
1268 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1269
1270 // Make sure admin1 is installed on system user.
1271 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001272
1273 // Call.
1274 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001275 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001276 UserHandle.USER_SYSTEM));
1277
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001278 // Check that the user restrictions that are enabled by default are set. Then unset them.
1279 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001280 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001281 DpmTestUtils.assertRestrictions(
1282 DpmTestUtils.newRestrictions(defaultRestrictions),
1283 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1284 );
1285 DpmTestUtils.assertRestrictions(
1286 DpmTestUtils.newRestrictions(defaultRestrictions),
1287 dpm.getUserRestrictions(admin1)
1288 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001289 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1290 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001291 MockUtils.checkUserRestrictions(defaultRestrictions),
1292 MockUtils.checkUserRestrictions()
Esteban Talavera548a04b2016-12-20 15:22:30 +00001293 );
1294 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001295
1296 for (String restriction : defaultRestrictions) {
1297 dpm.clearUserRestriction(admin1, restriction);
1298 }
1299
Esteban Talavera548a04b2016-12-20 15:22:30 +00001300 assertNoDeviceOwnerRestrictions();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001301
1302 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1303 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1304 eq(UserHandle.USER_SYSTEM),
1305 MockUtils.checkUserRestrictions(),
1306 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001307 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001308 reset(mContext.userManagerInternal);
1309
Makoto Onukia4f11972015-10-01 13:19:58 -07001310 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001311 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1312 eq(UserHandle.USER_SYSTEM),
1313 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1314 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1315 );
1316 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001317
Makoto Onuki068c54a2015-10-13 14:34:03 -07001318 DpmTestUtils.assertRestrictions(
1319 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001320 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001321 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1322 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001323 DpmTestUtils.assertRestrictions(
1324 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001325 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001326 dpm.getUserRestrictions(admin1)
1327 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001328
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001329 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1330 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1331 eq(UserHandle.USER_SYSTEM),
1332 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1333 MockUtils.checkUserRestrictions()
1334 );
1335 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001336
Makoto Onuki068c54a2015-10-13 14:34:03 -07001337 DpmTestUtils.assertRestrictions(
1338 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1339 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1340 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001341 DpmTestUtils.assertRestrictions(
1342 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1343 dpm.getUserRestrictions(admin1)
1344 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001345
1346 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001347 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1348 eq(UserHandle.USER_SYSTEM),
1349 MockUtils.checkUserRestrictions(),
1350 MockUtils.checkUserRestrictions()
1351 );
1352 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001353
Esteban Talavera548a04b2016-12-20 15:22:30 +00001354 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001355
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001356 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1357 // DO sets them, the scope is global.
1358 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1359 reset(mContext.userManagerInternal);
1360 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1361 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1362 eq(UserHandle.USER_SYSTEM),
1363 MockUtils.checkUserRestrictions(),
1364 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1365 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1366 );
1367 reset(mContext.userManagerInternal);
1368
1369 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1370 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1371
1372
1373 // More tests.
1374 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1375 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1376 eq(UserHandle.USER_SYSTEM),
1377 MockUtils.checkUserRestrictions(),
1378 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1379 );
1380 reset(mContext.userManagerInternal);
1381
1382 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1383 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1384 eq(UserHandle.USER_SYSTEM),
1385 MockUtils.checkUserRestrictions(),
1386 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1387 UserManager.DISALLOW_ADD_USER)
1388 );
1389 reset(mContext.userManagerInternal);
1390
1391 dpm.setCameraDisabled(admin1, true);
1392 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1393 eq(UserHandle.USER_SYSTEM),
1394 // DISALLOW_CAMERA will be applied to both local and global.
1395 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1396 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1397 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1398 );
1399 reset(mContext.userManagerInternal);
1400
1401 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1402 // locally.
1403 dpm.setCameraDisabled(admin1, false);
1404 reset(mContext.userManagerInternal);
1405
1406 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1407 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1408 dpm.setCameraDisabled(admin2, true);
1409
1410 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1411 eq(UserHandle.USER_SYSTEM),
1412 // DISALLOW_CAMERA will be applied to both local and global.
1413 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1414 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1415 UserManager.DISALLOW_ADD_USER)
1416 );
1417 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001418 // TODO Make sure restrictions are written to the file.
1419 }
1420
1421 public void testSetUserRestriction_asPo() {
1422 setAsProfileOwner(admin1);
1423
Makoto Onuki068c54a2015-10-13 14:34:03 -07001424 DpmTestUtils.assertRestrictions(
1425 DpmTestUtils.newRestrictions(),
1426 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1427 .ensureUserRestrictions()
1428 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001429
1430 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001431 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1432 eq(DpmMockContext.CALLER_USER_HANDLE),
1433 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1434 isNull(Bundle.class)
1435 );
1436 reset(mContext.userManagerInternal);
1437
Makoto Onukia4f11972015-10-01 13:19:58 -07001438 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001439 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1440 eq(DpmMockContext.CALLER_USER_HANDLE),
1441 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1442 UserManager.DISALLOW_OUTGOING_CALLS),
1443 isNull(Bundle.class)
1444 );
1445 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001446
Makoto Onuki068c54a2015-10-13 14:34:03 -07001447 DpmTestUtils.assertRestrictions(
1448 DpmTestUtils.newRestrictions(
1449 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1450 UserManager.DISALLOW_OUTGOING_CALLS
1451 ),
1452 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1453 .ensureUserRestrictions()
1454 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001455 DpmTestUtils.assertRestrictions(
1456 DpmTestUtils.newRestrictions(
1457 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1458 UserManager.DISALLOW_OUTGOING_CALLS
1459 ),
1460 dpm.getUserRestrictions(admin1)
1461 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001462
1463 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001464 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1465 eq(DpmMockContext.CALLER_USER_HANDLE),
1466 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1467 isNull(Bundle.class)
1468 );
1469 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001470
1471 DpmTestUtils.assertRestrictions(
1472 DpmTestUtils.newRestrictions(
1473 UserManager.DISALLOW_OUTGOING_CALLS
1474 ),
1475 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1476 .ensureUserRestrictions()
1477 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001478 DpmTestUtils.assertRestrictions(
1479 DpmTestUtils.newRestrictions(
1480 UserManager.DISALLOW_OUTGOING_CALLS
1481 ),
1482 dpm.getUserRestrictions(admin1)
1483 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001484
1485 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001486 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1487 eq(DpmMockContext.CALLER_USER_HANDLE),
1488 MockUtils.checkUserRestrictions(),
1489 isNull(Bundle.class)
1490 );
1491 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001492
Makoto Onuki068c54a2015-10-13 14:34:03 -07001493 DpmTestUtils.assertRestrictions(
1494 DpmTestUtils.newRestrictions(),
1495 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1496 .ensureUserRestrictions()
1497 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001498 DpmTestUtils.assertRestrictions(
1499 DpmTestUtils.newRestrictions(),
1500 dpm.getUserRestrictions(admin1)
1501 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001502
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001503 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1504 // though when DO sets them they'll be applied globally.
1505 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1506 reset(mContext.userManagerInternal);
1507 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1508 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1509 eq(DpmMockContext.CALLER_USER_HANDLE),
1510 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1511 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1512 isNull(Bundle.class)
1513 );
1514 reset(mContext.userManagerInternal);
1515
1516 dpm.setCameraDisabled(admin1, true);
1517 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1518 eq(DpmMockContext.CALLER_USER_HANDLE),
1519 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1520 UserManager.DISALLOW_ADJUST_VOLUME,
1521 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1522 isNull(Bundle.class)
1523 );
1524 reset(mContext.userManagerInternal);
1525
Makoto Onukia4f11972015-10-01 13:19:58 -07001526 // TODO Make sure restrictions are written to the file.
1527 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001528
Esteban Talavera548a04b2016-12-20 15:22:30 +00001529
1530 public void testDefaultEnabledUserRestrictions() throws Exception {
1531 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1532 mContext.callerPermissions.add(permission.MANAGE_USERS);
1533 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1534 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1535
1536 // First, set DO.
1537
1538 // Call from a process on the system user.
1539 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1540
1541 // Make sure admin1 is installed on system user.
1542 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1543
1544 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1545 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1546 UserHandle.USER_SYSTEM));
1547
1548 // Check that the user restrictions that are enabled by default are set. Then unset them.
1549 String[] defaultRestrictions = UserRestrictionsUtils
1550 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1551 assertTrue(defaultRestrictions.length > 0);
1552 DpmTestUtils.assertRestrictions(
1553 DpmTestUtils.newRestrictions(defaultRestrictions),
1554 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1555 );
1556 DpmTestUtils.assertRestrictions(
1557 DpmTestUtils.newRestrictions(defaultRestrictions),
1558 dpm.getUserRestrictions(admin1)
1559 );
1560 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1561 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001562 MockUtils.checkUserRestrictions(defaultRestrictions),
1563 MockUtils.checkUserRestrictions()
Esteban Talavera548a04b2016-12-20 15:22:30 +00001564 );
1565 reset(mContext.userManagerInternal);
1566
1567 for (String restriction : defaultRestrictions) {
1568 dpm.clearUserRestriction(admin1, restriction);
1569 }
1570
1571 assertNoDeviceOwnerRestrictions();
1572
1573 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1574 reset(mContext.userManagerInternal);
1575 initializeDpms();
1576 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1577 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1578
1579 assertNoDeviceOwnerRestrictions();
1580
1581 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1582 // is set as it wasn't enabled during setDeviceOwner.
1583 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1584 assertFalse(UserRestrictionsUtils
1585 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1586 UserRestrictionsUtils
1587 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1588 try {
1589 reset(mContext.userManagerInternal);
1590 initializeDpms();
1591 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1592 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1593
1594 DpmTestUtils.assertRestrictions(
1595 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1596 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1597 );
1598 DpmTestUtils.assertRestrictions(
1599 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1600 dpm.getUserRestrictions(admin1)
1601 );
1602 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1603 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001604 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
1605 MockUtils.checkUserRestrictions()
Esteban Talavera548a04b2016-12-20 15:22:30 +00001606 );
1607 reset(mContext.userManagerInternal);
1608
1609 // Remove the restriction.
1610 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1611
1612 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1613 initializeDpms();
1614 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1615 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1616 assertNoDeviceOwnerRestrictions();
1617 } finally {
1618 UserRestrictionsUtils
1619 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1620 }
1621 }
1622
1623 private void assertNoDeviceOwnerRestrictions() {
1624 DpmTestUtils.assertRestrictions(
1625 DpmTestUtils.newRestrictions(),
1626 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1627 );
1628 DpmTestUtils.assertRestrictions(
1629 DpmTestUtils.newRestrictions(),
1630 dpm.getUserRestrictions(admin1)
1631 );
1632 }
1633
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001634 public void testGetMacAddress() throws Exception {
1635 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1636 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1637 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1638
1639 // In this test, change the caller user to "system".
1640 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1641
1642 // Make sure admin1 is installed on system user.
1643 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1644
1645 // Test 1. Caller doesn't have DO or DA.
1646 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001647 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001648 fail();
1649 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001650 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001651 }
1652
1653 // DO needs to be an DA.
1654 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1655 assertTrue(dpm.isAdminActive(admin1));
1656
1657 // Test 2. Caller has DA, but not DO.
1658 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001659 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001660 fail();
1661 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001662 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001663 }
1664
1665 // Test 3. Caller has PO, but not DO.
1666 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1667 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001668 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001669 fail();
1670 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001671 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001672 }
1673
1674 // Remove PO.
1675 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001676 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001677 // Test 4, Caller is DO now.
1678 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1679
1680 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001681 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001682
1683 // 4-2. Returns WifiInfo, but with the default MAC.
1684 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001685 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001686
1687 // 4-3. With a real MAC address.
1688 final WifiInfo wi = new WifiInfo();
1689 wi.setMacAddress("11:22:33:44:55:66");
1690 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001691 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001692 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001693
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001694 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001695 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1696 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1697
1698 // In this test, change the caller user to "system".
1699 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1700
1701 // Make sure admin1 is installed on system user.
1702 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1703
1704 // Set admin1 as DA.
1705 dpm.setActiveAdmin(admin1, false);
1706 assertTrue(dpm.isAdminActive(admin1));
1707 try {
1708 dpm.reboot(admin1);
1709 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1710 } catch (SecurityException expected) {
1711 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1712 }
1713
1714 // Set admin1 as PO.
1715 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1716 try {
1717 dpm.reboot(admin1);
1718 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1719 } catch (SecurityException expected) {
1720 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1721 }
1722
1723 // Remove PO and add DO.
1724 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001725 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001726 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1727
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001728 // admin1 is DO.
1729 // Set current call state of device to ringing.
1730 when(mContext.telephonyManager.getCallState())
1731 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1732 try {
1733 dpm.reboot(admin1);
1734 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1735 } catch (IllegalStateException expected) {
1736 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1737 }
1738
1739 // Set current call state of device to dialing/active.
1740 when(mContext.telephonyManager.getCallState())
1741 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1742 try {
1743 dpm.reboot(admin1);
1744 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1745 } catch (IllegalStateException expected) {
1746 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1747 }
1748
1749 // Set current call state of device to idle.
1750 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001751 dpm.reboot(admin1);
1752 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001753
1754 public void testSetGetSupportText() {
1755 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1756 dpm.setActiveAdmin(admin1, true);
1757 dpm.setActiveAdmin(admin2, true);
1758 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1759
1760 // Null default support messages.
1761 {
1762 assertNull(dpm.getLongSupportMessage(admin1));
1763 assertNull(dpm.getShortSupportMessage(admin1));
1764 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1765 assertNull(dpm.getShortSupportMessageForUser(admin1,
1766 DpmMockContext.CALLER_USER_HANDLE));
1767 assertNull(dpm.getLongSupportMessageForUser(admin1,
1768 DpmMockContext.CALLER_USER_HANDLE));
1769 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1770 }
1771
1772 // Only system can call the per user versions.
1773 {
1774 try {
1775 dpm.getShortSupportMessageForUser(admin1,
1776 DpmMockContext.CALLER_USER_HANDLE);
1777 fail("Only system should be able to call getXXXForUser versions");
1778 } catch (SecurityException expected) {
1779 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1780 }
1781 try {
1782 dpm.getLongSupportMessageForUser(admin1,
1783 DpmMockContext.CALLER_USER_HANDLE);
1784 fail("Only system should be able to call getXXXForUser versions");
1785 } catch (SecurityException expected) {
1786 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1787 }
1788 }
1789
1790 // Can't set message for admin in another uid.
1791 {
1792 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1793 try {
1794 dpm.setShortSupportMessage(admin1, "Some text");
1795 fail("Admins should only be able to change their own support text.");
1796 } catch (SecurityException expected) {
1797 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1798 }
1799 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1800 }
1801
1802 // Set/Get short returns what it sets and other admins text isn't changed.
1803 {
1804 final String supportText = "Some text to test with.";
1805 dpm.setShortSupportMessage(admin1, supportText);
1806 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1807 assertNull(dpm.getLongSupportMessage(admin1));
1808 assertNull(dpm.getShortSupportMessage(admin2));
1809
1810 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1811 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1812 DpmMockContext.CALLER_USER_HANDLE));
1813 assertNull(dpm.getShortSupportMessageForUser(admin2,
1814 DpmMockContext.CALLER_USER_HANDLE));
1815 assertNull(dpm.getLongSupportMessageForUser(admin1,
1816 DpmMockContext.CALLER_USER_HANDLE));
1817 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1818
1819 dpm.setShortSupportMessage(admin1, null);
1820 assertNull(dpm.getShortSupportMessage(admin1));
1821 }
1822
1823 // Set/Get long returns what it sets and other admins text isn't changed.
1824 {
1825 final String supportText = "Some text to test with.\nWith more text.";
1826 dpm.setLongSupportMessage(admin1, supportText);
1827 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1828 assertNull(dpm.getShortSupportMessage(admin1));
1829 assertNull(dpm.getLongSupportMessage(admin2));
1830
1831 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1832 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1833 DpmMockContext.CALLER_USER_HANDLE));
1834 assertNull(dpm.getLongSupportMessageForUser(admin2,
1835 DpmMockContext.CALLER_USER_HANDLE));
1836 assertNull(dpm.getShortSupportMessageForUser(admin1,
1837 DpmMockContext.CALLER_USER_HANDLE));
1838 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1839
1840 dpm.setLongSupportMessage(admin1, null);
1841 assertNull(dpm.getLongSupportMessage(admin1));
1842 }
1843 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001844
1845 /**
1846 * Test for:
1847 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001848 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001849 * {@link DevicePolicyManager#isAffiliatedUser}
1850 */
1851 public void testUserAffiliation() throws Exception {
1852 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1853 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1854 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1855
1856 // Check that the system user is unaffiliated.
1857 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1858 assertFalse(dpm.isAffiliatedUser());
1859
1860 // Set a device owner on the system user. Check that the system user becomes affiliated.
1861 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1862 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1863 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1864 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001865 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001866
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001867 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001868 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1869 setAsProfileOwner(admin2);
1870 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001871 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001872
1873 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1874 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001875 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001876 userAffiliationIds.add("red");
1877 userAffiliationIds.add("green");
1878 userAffiliationIds.add("blue");
1879 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001880 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001881 assertFalse(dpm.isAffiliatedUser());
1882
1883 // Have the device owner specify a set of affiliation ids that do not intersect with those
1884 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001885 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001886 deviceAffiliationIds.add("cyan");
1887 deviceAffiliationIds.add("yellow");
1888 deviceAffiliationIds.add("magenta");
1889 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1890 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001891 MoreAsserts.assertContentsInAnyOrder(
1892 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001893 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1894 assertFalse(dpm.isAffiliatedUser());
1895
1896 // Have the profile owner specify a set of affiliation ids that intersect with those
1897 // specified by the device owner. Check that the test user becomes affiliated.
1898 userAffiliationIds.add("yellow");
1899 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001900 MoreAsserts.assertContentsInAnyOrder(
1901 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001902 assertTrue(dpm.isAffiliatedUser());
1903
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001904 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
1905 dpm.setAffiliationIds(admin2, Collections.emptyList());
1906 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001907 assertFalse(dpm.isAffiliatedUser());
1908
1909 // Check that the system user remains affiliated.
1910 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1911 assertTrue(dpm.isAffiliatedUser());
1912 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001913
1914 public void testGetUserProvisioningState_defaultResult() {
1915 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1916 }
1917
1918 public void testSetUserProvisioningState_permission() throws Exception {
1919 setupProfileOwner();
1920 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1921
1922 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1923 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1924 }
1925
1926 public void testSetUserProvisioningState_unprivileged() throws Exception {
1927 setupProfileOwner();
1928 try {
1929 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1930 DpmMockContext.CALLER_USER_HANDLE);
1931 fail("Expected SecurityException");
1932 } catch (SecurityException expected) {
1933 }
1934 }
1935
1936 public void testSetUserProvisioningState_noManagement() {
1937 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1938 try {
1939 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1940 DpmMockContext.CALLER_USER_HANDLE);
1941 fail("IllegalStateException expected");
1942 } catch (IllegalStateException e) {
1943 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1944 e.getMessage());
1945 }
1946 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1947 }
1948
1949 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1950 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1951 setupDeviceOwner();
1952 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1953
1954 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1955 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1956 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1957 }
1958
1959 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1960 throws Exception {
1961 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1962 setupDeviceOwner();
1963 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1964
1965 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1966 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1967 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1968 }
1969
1970 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1971 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1972 setupDeviceOwner();
1973 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1974
1975 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1976 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1977 }
1978
1979 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1980 throws Exception {
1981 setupProfileOwner();
1982 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1983
1984 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1985 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1986 DevicePolicyManager.STATE_USER_UNMANAGED);
1987 }
1988
1989 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1990 throws Exception {
1991 setupProfileOwner();
1992 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1993
1994 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1995 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1996 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1997 }
1998
1999 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2000 setupProfileOwner();
2001 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2002
2003 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2004 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2005 }
2006
2007 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2008 setupProfileOwner();
2009 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2010
2011 try {
2012 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2013 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2014 DevicePolicyManager.STATE_USER_UNMANAGED);
2015 fail("Expected IllegalStateException");
2016 } catch (IllegalStateException e) {
2017 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2018 e.getMessage());
2019 }
2020 }
2021
2022 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2023 throws Exception {
2024 setupProfileOwner();
2025 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2026
2027 try {
2028 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2029 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2030 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2031 fail("Expected IllegalStateException");
2032 } catch (IllegalStateException e) {
2033 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2034 e.getMessage());
2035 }
2036 }
2037
2038 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2039 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2040 for (int state : states) {
2041 dpm.setUserProvisioningState(state, userId);
2042 assertEquals(state, dpm.getUserProvisioningState());
2043 }
2044 }
2045
2046 private void setupProfileOwner() throws Exception {
2047 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2048
2049 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2050 dpm.setActiveAdmin(admin1, false);
2051 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2052
2053 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2054 }
2055
2056 private void setupDeviceOwner() throws Exception {
2057 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2058
2059 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2060 dpm.setActiveAdmin(admin1, false);
2061 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2062
2063 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2064 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002065
2066 public void testSetMaximumTimeToLock() {
2067 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2068
2069 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2070 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2071
2072 reset(mMockContext.powerManagerInternal);
2073 reset(mMockContext.settings);
2074
2075 dpm.setMaximumTimeToLock(admin1, 0);
2076 verifyScreenTimeoutCall(null, false);
2077 reset(mMockContext.powerManagerInternal);
2078 reset(mMockContext.settings);
2079
2080 dpm.setMaximumTimeToLock(admin1, 1);
2081 verifyScreenTimeoutCall(1, true);
2082 reset(mMockContext.powerManagerInternal);
2083 reset(mMockContext.settings);
2084
2085 dpm.setMaximumTimeToLock(admin2, 10);
2086 verifyScreenTimeoutCall(null, false);
2087 reset(mMockContext.powerManagerInternal);
2088 reset(mMockContext.settings);
2089
2090 dpm.setMaximumTimeToLock(admin1, 5);
2091 verifyScreenTimeoutCall(5, true);
2092 reset(mMockContext.powerManagerInternal);
2093 reset(mMockContext.settings);
2094
2095 dpm.setMaximumTimeToLock(admin2, 4);
2096 verifyScreenTimeoutCall(4, true);
2097 reset(mMockContext.powerManagerInternal);
2098 reset(mMockContext.settings);
2099
2100 dpm.setMaximumTimeToLock(admin1, 0);
2101 reset(mMockContext.powerManagerInternal);
2102 reset(mMockContext.settings);
2103
2104 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2105 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2106 reset(mMockContext.powerManagerInternal);
2107 reset(mMockContext.settings);
2108
2109 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2110 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2111 reset(mMockContext.powerManagerInternal);
2112 reset(mMockContext.settings);
2113
2114 dpm.setMaximumTimeToLock(admin2, 10);
2115 verifyScreenTimeoutCall(10, true);
2116 reset(mMockContext.powerManagerInternal);
2117 reset(mMockContext.settings);
2118
2119 // There's no restriction; shold be set to MAX.
2120 dpm.setMaximumTimeToLock(admin2, 0);
2121 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2122 }
2123
Michal Karpinski943aabd2016-10-06 11:09:25 +01002124 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2125 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2126 setupDeviceOwner();
2127 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2128
Michal Karpinskid084ca52017-01-18 15:54:18 +00002129 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2130 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2131 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2132 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2133 - ONE_MINUTE;
2134
2135 // verify that the minimum timeout cannot be modified on user builds (system property is
2136 // not being read)
2137 mContext.buildMock.isDebuggable = false;
2138
2139 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2140 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2141 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2142
2143 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2144
2145 // restore to the debuggable build state
2146 mContext.buildMock.isDebuggable = true;
2147
2148 // Always return the default (second arg) when getting system property for long type
2149 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2150 new Answer<Long>() {
2151 @Override
2152 public Long answer(InvocationOnMock invocation) throws Throwable {
2153 return (Long) invocation.getArguments()[1];
2154 }
2155 }
2156 );
2157
2158 // reset to default (0 means the admin is not participating, so default should be returned)
2159 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002160
2161 // aggregation should be the default if unset by any admin
2162 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2163 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2164
2165 // admin not participating by default
2166 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2167
2168 //clamping from the top
2169 dpm.setRequiredStrongAuthTimeout(admin1,
2170 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2171 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2172 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2173 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2174 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2175
Michal Karpinskid084ca52017-01-18 15:54:18 +00002176 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002177 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2178 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2179 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2180 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2181
2182 // clamping from the bottom
2183 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2184 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2185 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2186
Michal Karpinskid084ca52017-01-18 15:54:18 +00002187 // values within range
2188 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2189 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2190 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2191
2192 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2193 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2194 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002195
2196 // reset to default
2197 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2198 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2199 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2200 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2201
2202 // negative value
2203 try {
2204 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2205 fail("Didn't throw IllegalArgumentException");
2206 } catch (IllegalArgumentException iae) {
2207 }
2208 }
2209
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002210 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2211 boolean shouldStayOnWhilePluggedInBeCleared) {
2212 if (expectedTimeout == null) {
2213 verify(mMockContext.powerManagerInternal, times(0))
2214 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2215 } else {
2216 verify(mMockContext.powerManagerInternal, times(1))
2217 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2218 }
2219 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2220 // UnfinishedVerificationException.
2221 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002222
Esteban Talavera01576862016-12-15 11:16:44 +00002223 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002224 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2225 .thenReturn(false);
2226 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2227 .thenReturn(false);
2228 initializeDpms();
2229 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2230 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2231 .thenReturn(true);
2232 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2233
2234 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002235 }
Victor Chang3e794af2016-03-04 13:48:17 +00002236
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002237 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2238 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002239 mContext.packageName = admin1.getPackageName();
2240 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002241 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2242 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2243 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2244 false);
2245 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2246 }
2247
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002248 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2249 setup_DeviceAdminFeatureOff();
2250 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2251 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2252 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2253 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2254 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2255 assertCheckProvisioningPreCondition(
2256 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2257 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2258 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2259 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2260 }
2261
Esteban Talavera01576862016-12-15 11:16:44 +00002262 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002263 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2264 .thenReturn(false);
2265 initializeDpms();
2266 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2267 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2268 .thenReturn(true);
2269 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2270
2271 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002272 }
Victor Chang3e794af2016-03-04 13:48:17 +00002273
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002274 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2275 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002276 mContext.packageName = admin1.getPackageName();
2277 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002278 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2279 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2280 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2281 false);
2282 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2283
2284 // Test again when split user is on
2285 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2286 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2287 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2288 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2289 true);
2290 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2291 }
2292
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002293 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2294 setup_ManagedProfileFeatureOff();
2295 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2296 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2297 DevicePolicyManager.CODE_OK);
2298 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2299 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2300 assertCheckProvisioningPreCondition(
2301 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2302 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2303 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2304 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2305
2306 // Test again when split user is on
2307 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2308 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2309 DevicePolicyManager.CODE_OK);
2310 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2311 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2312 assertCheckProvisioningPreCondition(
2313 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2314 DevicePolicyManager.CODE_OK);
2315 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2316 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2317 }
2318
Esteban Talavera01576862016-12-15 11:16:44 +00002319 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002320 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2321 .thenReturn(true);
2322 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2323 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2324 .thenReturn(true);
2325 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2326
2327 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002328 }
Victor Chang3e794af2016-03-04 13:48:17 +00002329
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002330 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2331 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002332 mContext.packageName = admin1.getPackageName();
2333 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002334 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2335 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2336 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2337 false /* because of non-split user */);
2338 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2339 false /* because of non-split user */);
2340 }
2341
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002342 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002343 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002344 setup_nonSplitUser_firstBoot_primaryUser();
2345 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2346 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2347 DevicePolicyManager.CODE_OK);
2348 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2349 DevicePolicyManager.CODE_OK);
2350 assertCheckProvisioningPreCondition(
2351 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2352 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2353 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2354 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2355 }
2356
Esteban Talavera01576862016-12-15 11:16:44 +00002357 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002358 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2359 .thenReturn(true);
2360 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2361 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2362 .thenReturn(true);
2363 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2364
2365 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002366 }
Victor Chang3e794af2016-03-04 13:48:17 +00002367
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002368 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2369 throws Exception {
2370 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002371 mContext.packageName = admin1.getPackageName();
2372 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002373 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2374 false/* because of completed device setup */);
2375 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2376 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2377 false/* because of non-split user */);
2378 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2379 false/* because of non-split user */);
2380 }
2381
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002382 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2383 throws Exception {
2384 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2385 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2386 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2387 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2388 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2389 DevicePolicyManager.CODE_OK);
2390 assertCheckProvisioningPreCondition(
2391 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2392 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2393 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2394 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2395 }
2396
Esteban Talavera01576862016-12-15 11:16:44 +00002397 public void testIsProvisioningAllowed_nonSplitUser_withDo_primaryUser() throws Exception {
2398 setDeviceOwner();
2399 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2400 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2401 mContext.packageName = admin1.getPackageName();
2402
Nicolas Prevotc3bd7b72017-01-10 11:32:43 +00002403 final ComponentName adminDifferentPackage =
2404 new ComponentName("another.package", "whatever.random.class");
2405 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 948);
2406 setUpPackageManagerForFakeAdmin(adminDifferentPackage, ANOTHER_UID, admin2);
2407
Esteban Talavera01576862016-12-15 11:16:44 +00002408 // COMP mode is allowed.
2409 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2410
2411 when(mContext.userManager.hasUserRestriction(
2412 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2413 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2414 .thenReturn(true);
2415
2416 // The DO should be allowed to initiate provisioning if it set the restriction itself.
2417 when(mContext.userManager.getUserRestrictionSource(
2418 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2419 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2420 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2421 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2422
Nicolas Prevotc3bd7b72017-01-10 11:32:43 +00002423 // But another app should not
2424 mContext.binder.callingUid = ANOTHER_UID;
2425 mContext.packageName = adminDifferentPackage.getPackageName();
2426 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2427
Esteban Talavera01576862016-12-15 11:16:44 +00002428 // The DO should not be allowed to initiate provisioning if the restriction is set by
2429 // another entity.
2430 when(mContext.userManager.getUserRestrictionSource(
2431 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2432 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2433 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
Nicolas Prevotc3bd7b72017-01-10 11:32:43 +00002434 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2435 mContext.packageName = admin1.getPackageName();
2436 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2437
2438 mContext.binder.callingUid = ANOTHER_UID;
2439 mContext.packageName = adminDifferentPackage.getPackageName();
2440 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2441 }
2442
2443 public void testIsProvisioningAllowed_nonSplitUser_comp() throws Exception {
2444 setDeviceOwner();
2445 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2446 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2447
2448 final ComponentName adminDifferentPackage =
2449 new ComponentName("another.package", "whatever.class");
2450 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 948);
2451 setUpPackageManagerForFakeAdmin(adminDifferentPackage, ANOTHER_UID, admin2);
2452
2453 final int MANAGED_PROFILE_USER_ID = 18;
2454 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2455 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2456
2457 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2458 false /* we can't remove a managed profile */)).thenReturn(false);
2459 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2460 true)).thenReturn(true);
2461
2462 // We can delete the managed profile to create a new one, so provisioning is allowed.
2463 mContext.packageName = admin1.getPackageName();
2464 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2465 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2466
2467 mContext.packageName = adminDifferentPackage.getPackageName();
2468 mContext.binder.callingUid = ANOTHER_UID;
2469 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2470
2471 when(mContext.userManager.hasUserRestriction(
2472 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2473 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
2474 .thenReturn(true);
2475
2476 // Now, we can't remove the profile any more to create a new one.
2477 mContext.packageName = admin1.getPackageName();
2478 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2479 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2480
2481 mContext.packageName = adminDifferentPackage.getPackageName();
2482 mContext.binder.callingUid = ANOTHER_UID;
Esteban Talavera01576862016-12-15 11:16:44 +00002483 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2484 }
2485
2486 public void
2487 testCheckProvisioningPreCondition_nonSplitUser_withDo_primaryUser() throws Exception {
2488 setDeviceOwner();
2489 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2490 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2491
2492 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2493 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
2494
2495 // COMP mode is allowed.
2496 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2497 DevicePolicyManager.CODE_OK);
2498
2499 // And other DPCs can also provisioning a managed profile (DO + BYOD case).
2500 assertCheckProvisioningPreCondition(
2501 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2502 "some.other.dpc.package.name",
2503 DevicePolicyManager.CODE_OK);
2504
2505 when(mContext.userManager.hasUserRestriction(
2506 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2507 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2508 .thenReturn(true);
2509
2510 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2511 // other packages should be forbidden.
2512 when(mContext.userManager.getUserRestrictionSource(
2513 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2514 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2515 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2516 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2517 DevicePolicyManager.CODE_OK);
2518 assertCheckProvisioningPreCondition(
2519 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2520 "some.other.dpc.package.name",
2521 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2522
2523 // The DO should not be allowed to initiate provisioning if the restriction is set by
2524 // another entity.
2525 when(mContext.userManager.getUserRestrictionSource(
2526 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2527 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2528 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2529 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2530 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2531 assertCheckProvisioningPreCondition(
2532 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2533 "some.other.dpc.package.name",
2534 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2535 }
2536
2537 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002538 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2539 .thenReturn(true);
2540 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2541 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2542 .thenReturn(false);
2543 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2544
2545 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002546 }
Victor Chang3e794af2016-03-04 13:48:17 +00002547
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002548 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2549 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002550 mContext.packageName = admin1.getPackageName();
2551 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002552 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2553 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2554 false /* because canAddMoreManagedProfiles returns false */);
2555 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2556 true);
2557 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2558 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002559 }
2560
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002561 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2562 throws Exception {
2563 setup_splitUser_firstBoot_systemUser();
2564 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2565 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2566 DevicePolicyManager.CODE_OK);
2567 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002568 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002569 assertCheckProvisioningPreCondition(
2570 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2571 DevicePolicyManager.CODE_OK);
2572 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2573 DevicePolicyManager.CODE_SYSTEM_USER);
2574 }
2575
Esteban Talavera01576862016-12-15 11:16:44 +00002576 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002577 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2578 .thenReturn(true);
2579 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2580 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2581 .thenReturn(false);
2582 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2583
2584 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002585 }
Victor Chang3e794af2016-03-04 13:48:17 +00002586
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002587 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2588 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002589 mContext.packageName = admin1.getPackageName();
2590 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002591 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2592 true/* it's undefined behavior. Can be changed into false in the future */);
2593 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2594 false /* because canAddMoreManagedProfiles returns false */);
2595 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2596 true/* it's undefined behavior. Can be changed into false in the future */);
2597 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2598 false/* because calling uid is system user */);
2599 }
2600
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002601 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2602 throws Exception {
2603 setup_splitUser_afterDeviceSetup_systemUser();
2604 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2605 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2606 DevicePolicyManager.CODE_OK);
2607 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002608 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002609 assertCheckProvisioningPreCondition(
2610 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2611 DevicePolicyManager.CODE_OK);
2612 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2613 DevicePolicyManager.CODE_SYSTEM_USER);
2614 }
2615
Esteban Talavera01576862016-12-15 11:16:44 +00002616 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002617 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2618 .thenReturn(true);
2619 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2620 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2621 true)).thenReturn(true);
2622 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2623
2624 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002625 }
Victor Chang3e794af2016-03-04 13:48:17 +00002626
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002627 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2628 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002629 mContext.packageName = admin1.getPackageName();
2630 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002631 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2632 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2633 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2634 true);
2635 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002636 }
2637
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002638 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002639 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002640 setup_splitUser_firstBoot_primaryUser();
2641 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2642 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2643 DevicePolicyManager.CODE_OK);
2644 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2645 DevicePolicyManager.CODE_OK);
2646 assertCheckProvisioningPreCondition(
2647 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2648 DevicePolicyManager.CODE_OK);
2649 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2650 DevicePolicyManager.CODE_OK);
2651 }
2652
Esteban Talavera01576862016-12-15 11:16:44 +00002653 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002654 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2655 .thenReturn(true);
2656 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2657 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2658 true)).thenReturn(true);
2659 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2660
2661 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002662 }
Victor Chang3e794af2016-03-04 13:48:17 +00002663
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002664 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2665 throws Exception {
2666 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002667 mContext.packageName = admin1.getPackageName();
2668 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002669 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2670 true/* it's undefined behavior. Can be changed into false in the future */);
2671 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2672 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2673 true/* it's undefined behavior. Can be changed into false in the future */);
2674 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2675 false/* because user setup completed */);
2676 }
2677
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002678 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002679 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002680 setup_splitUser_afterDeviceSetup_primaryUser();
2681 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2682 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2683 DevicePolicyManager.CODE_OK);
2684 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2685 DevicePolicyManager.CODE_OK);
2686 assertCheckProvisioningPreCondition(
2687 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2688 DevicePolicyManager.CODE_OK);
2689 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2690 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2691 }
2692
Esteban Talavera01576862016-12-15 11:16:44 +00002693 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002694 setDeviceOwner();
2695
2696 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2697 .thenReturn(true);
2698 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2699 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2700 .thenReturn(false);
2701 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2702
2703 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002704 }
Victor Chang3e794af2016-03-04 13:48:17 +00002705
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002706 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2707 throws Exception {
2708 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002709 mContext.packageName = admin1.getPackageName();
2710 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002711 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2712 false /* can't provision managed profile on system user */);
2713 }
2714
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002715 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002716 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002717 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2718 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2719 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2720 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2721 }
2722
2723 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002724 setDeviceOwner();
2725
2726 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2727 .thenReturn(true);
2728 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2729 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2730 true)).thenReturn(true);
2731 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2732
2733 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002734 }
Victor Chang3e794af2016-03-04 13:48:17 +00002735
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002736 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2737 throws Exception {
2738 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002739 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2740 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002741 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2742 }
2743
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002744 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002745 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002746 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2747 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002748
2749 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002750 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2751 DevicePolicyManager.CODE_OK);
2752 }
2753
2754 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002755 setDeviceOwner();
2756
2757 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2758 .thenReturn(true);
2759 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002760 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002761 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2762 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002763 .thenReturn(true);
2764 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002765 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002766 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2767 true)).thenReturn(true);
2768 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2769
2770 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002771 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002772
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002773 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2774 throws Exception {
2775 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002776 mContext.packageName = admin1.getPackageName();
2777 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002778 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2779 }
2780
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002781 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2782 throws Exception {
2783 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2784 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2785 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2786 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2787 }
2788
2789 public void testCheckProvisioningPreCondition_permission() {
2790 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2791 try {
Esteban Talavera01576862016-12-15 11:16:44 +00002792 dpm.checkProvisioningPreCondition(
2793 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002794 fail("Didn't throw SecurityException");
2795 } catch (SecurityException expected) {
2796 }
2797 }
2798
Victor Chang3577ed22016-08-25 18:49:26 +01002799 public void testForceUpdateUserSetupComplete_permission() {
2800 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2801 try {
2802 dpm.forceUpdateUserSetupComplete();
2803 fail("Didn't throw SecurityException");
2804 } catch (SecurityException expected) {
2805 }
2806 }
2807
2808 public void testForceUpdateUserSetupComplete_systemUser() {
2809 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2810 // GIVEN calling from user 20
2811 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2812 try {
2813 dpm.forceUpdateUserSetupComplete();
2814 fail("Didn't throw SecurityException");
2815 } catch (SecurityException expected) {
2816 }
2817 }
2818
2819 public void testForceUpdateUserSetupComplete_userbuild() {
2820 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2821 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2822
2823 final int userId = UserHandle.USER_SYSTEM;
2824 // GIVEN userComplete is false in SettingsProvider
2825 setUserSetupCompleteForUser(false, userId);
2826
2827 // GIVEN userComplete is true in DPM
2828 DevicePolicyManagerService.DevicePolicyData userData =
2829 new DevicePolicyManagerService.DevicePolicyData(userId);
2830 userData.mUserSetupComplete = true;
2831 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2832
2833 // GIVEN it's user build
2834 mContext.buildMock.isDebuggable = false;
2835
2836 assertTrue(dpms.hasUserSetupCompleted());
2837
2838 dpm.forceUpdateUserSetupComplete();
2839
2840 // THEN the state in dpms is not changed
2841 assertTrue(dpms.hasUserSetupCompleted());
2842 }
2843
2844 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2845 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2846 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2847
2848 final int userId = UserHandle.USER_SYSTEM;
2849 // GIVEN userComplete is false in SettingsProvider
2850 setUserSetupCompleteForUser(false, userId);
2851
2852 // GIVEN userComplete is true in DPM
2853 DevicePolicyManagerService.DevicePolicyData userData =
2854 new DevicePolicyManagerService.DevicePolicyData(userId);
2855 userData.mUserSetupComplete = true;
2856 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2857
2858 // GIVEN it's userdebug build
2859 mContext.buildMock.isDebuggable = true;
2860
2861 assertTrue(dpms.hasUserSetupCompleted());
2862
2863 dpm.forceUpdateUserSetupComplete();
2864
2865 // THEN the state in dpms is not changed
2866 assertFalse(dpms.hasUserSetupCompleted());
2867 }
2868
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002869 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002870 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002871 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2872 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2873 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2874 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002875 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002876 }
2877
2878 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2879 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2880 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002881
2882 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2883 // feature is disabled because there are non-affiliated secondary users.
2884 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002885 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2886 .thenReturn(true);
2887
2888 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002889 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002890
2891 // Enabling logging should not change the timestamp.
2892 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00002893 verify(mContext.settings)
2894 .securityLogSetLoggingEnabledProperty(true);
2895 when(mContext.settings.securityLogGetLoggingEnabledProperty())
2896 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002897 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002898
2899 // Retrieving the logs should update the timestamp.
2900 final long beforeRetrieval = System.currentTimeMillis();
2901 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002902 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002903 final long afterRetrieval = System.currentTimeMillis();
2904 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2905 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2906
2907 // Retrieving the pre-boot logs should update the timestamp.
2908 Thread.sleep(2);
2909 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002910 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002911 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2912
2913 // Checking the timestamp again should not change it.
2914 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002915 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002916
2917 // Retrieving the logs again should update the timestamp.
2918 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002919 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002920 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2921
2922 // Disabling logging should not change the timestamp.
2923 Thread.sleep(2);
2924 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002925 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002926
2927 // Restarting the DPMS should not lose the timestamp.
2928 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002929 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002930
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002931 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2932 mContext.binder.callingUid = 1234567;
2933 mContext.callerPermissions.add(permission.MANAGE_USERS);
2934 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2935 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2936
2937 // System can retrieve the timestamp.
2938 mContext.binder.clearCallingIdentity();
2939 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2940
2941 // Removing the device owner should clear the timestamp.
2942 clearDeviceOwner();
2943 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002944 }
2945
2946 public void testGetLastBugReportRequestTime() throws Exception {
2947 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2948 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002949
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002950 mContext.packageName = admin1.getPackageName();
2951 mContext.applicationInfo = new ApplicationInfo();
2952 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2953 .thenReturn(Color.WHITE);
2954 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2955 anyObject())).thenReturn(Color.WHITE);
2956
Esteban Talaverad36dd152016-12-15 08:51:45 +00002957 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2958 // feature is disabled because there are non-affiliated secondary users.
2959 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
2960
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002961 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002962 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002963
2964 // Requesting a bug report should update the timestamp.
2965 final long beforeRequest = System.currentTimeMillis();
2966 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002967 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002968 final long afterRequest = System.currentTimeMillis();
2969 assertTrue(bugReportRequestTime >= beforeRequest);
2970 assertTrue(bugReportRequestTime <= afterRequest);
2971
2972 // Checking the timestamp again should not change it.
2973 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002974 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002975
2976 // Restarting the DPMS should not lose the timestamp.
2977 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002978 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002979
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002980 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2981 mContext.binder.callingUid = 1234567;
2982 mContext.callerPermissions.add(permission.MANAGE_USERS);
2983 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2984 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2985
2986 // System can retrieve the timestamp.
2987 mContext.binder.clearCallingIdentity();
2988 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2989
2990 // Removing the device owner should clear the timestamp.
2991 clearDeviceOwner();
2992 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002993 }
2994
2995 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2996 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2997 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002998 mContext.packageName = admin1.getPackageName();
2999 mContext.applicationInfo = new ApplicationInfo();
3000 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3001 .thenReturn(Color.WHITE);
3002 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3003 anyObject())).thenReturn(Color.WHITE);
3004
3005 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3006 // feature is disabled because there are non-affiliated secondary users.
3007 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003008 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3009 .thenReturn(true);
3010
3011 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003012 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003013
3014 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3015 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003016 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003017
3018 // Enabling logging should not change the timestamp.
3019 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003020 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003021
3022 // Retrieving the logs should update the timestamp.
3023 final long beforeRetrieval = System.currentTimeMillis();
3024 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003025 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003026 final long afterRetrieval = System.currentTimeMillis();
3027 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3028 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3029
3030 // Checking the timestamp again should not change it.
3031 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003032 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003033
3034 // Retrieving the logs again should update the timestamp.
3035 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003036 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003037 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3038
3039 // Disabling logging should not change the timestamp.
3040 Thread.sleep(2);
3041 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003042 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003043
3044 // Restarting the DPMS should not lose the timestamp.
3045 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003046 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3047
3048 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3049 mContext.binder.callingUid = 1234567;
3050 mContext.callerPermissions.add(permission.MANAGE_USERS);
3051 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3052 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3053
3054 // System can retrieve the timestamp.
3055 mContext.binder.clearCallingIdentity();
3056 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3057
3058 // Removing the device owner should clear the timestamp.
3059 clearDeviceOwner();
3060 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003061 }
3062
Tony Mak2f26b792016-11-28 17:54:51 +00003063 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3064 // Setup device owner.
3065 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3066 setupDeviceOwner();
3067
3068 // Only device owner is setup, the result list should be empty.
3069 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3070 MoreAsserts.assertEmpty(targetUsers);
3071
3072 // Setup a managed profile managed by the same admin.
3073 final int MANAGED_PROFILE_USER_ID = 15;
3074 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3075 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3076
3077 // Add a secondary user, it should never talk with.
3078 final int ANOTHER_USER_ID = 36;
3079 mContext.addUser(ANOTHER_USER_ID, 0);
3080
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003081 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3082 // other.
3083 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3084 MoreAsserts.assertEmpty(targetUsers);
3085
3086 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3087 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3088 MoreAsserts.assertEmpty(targetUsers);
3089
3090 // Setting affiliation ids
3091 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3092 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3093 dpm.setAffiliationIds(admin1, userAffiliationIds);
3094
3095 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3096 dpm.setAffiliationIds(admin1, userAffiliationIds);
3097
Tony Mak2f26b792016-11-28 17:54:51 +00003098 // Calling from device owner admin, the result list should just contain the managed
3099 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003100 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003101 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3102 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3103
3104 // Calling from managed profile admin, the result list should just contain the system
3105 // user id.
3106 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3107 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3108 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003109
3110 // Changing affiliation ids in one
3111 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3112
3113 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3114 // to each other.
3115 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3116 MoreAsserts.assertEmpty(targetUsers);
3117
3118 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3119 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3120 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003121 }
3122
3123 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3124 // Setup a device owner.
3125 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3126 setupDeviceOwner();
3127
3128 // Set up a managed profile managed by different package.
3129 final int MANAGED_PROFILE_USER_ID = 15;
3130 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3131 final ComponentName adminDifferentPackage =
3132 new ComponentName("another.package", "whatever.class");
3133 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3134
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003135 // Setting affiliation ids
3136 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3137 dpm.setAffiliationIds(admin1, userAffiliationIds);
3138
3139 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3140 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3141
Tony Mak2f26b792016-11-28 17:54:51 +00003142 // Calling from device owner admin, we should get zero bind device admin target users as
3143 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003144 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003145 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3146 MoreAsserts.assertEmpty(targetUsers);
3147
3148 // Calling from managed profile admin, we should still get zero target users for the same
3149 // reason.
3150 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3151 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3152 MoreAsserts.assertEmpty(targetUsers);
3153 }
3154
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003155 public void testIsDeviceManaged() throws Exception {
3156 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3157 setupDeviceOwner();
3158
3159 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3160 // find out that the device has a device owner.
3161 assertTrue(dpm.isDeviceManaged());
3162 mContext.binder.callingUid = 1234567;
3163 mContext.callerPermissions.add(permission.MANAGE_USERS);
3164 assertTrue(dpm.isDeviceManaged());
3165 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3166 mContext.binder.clearCallingIdentity();
3167 assertTrue(dpm.isDeviceManaged());
3168
3169 clearDeviceOwner();
3170
3171 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3172 // not have a device owner.
3173 mContext.binder.callingUid = 1234567;
3174 mContext.callerPermissions.add(permission.MANAGE_USERS);
3175 assertFalse(dpm.isDeviceManaged());
3176 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3177 mContext.binder.clearCallingIdentity();
3178 assertFalse(dpm.isDeviceManaged());
3179 }
3180
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003181 public void testDeviceOwnerOrganizationName() throws Exception {
3182 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3183 setupDeviceOwner();
3184
3185 dpm.setOrganizationName(admin1, "organization");
3186
3187 // Device owner can retrieve organization managing the device.
3188 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3189
3190 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3191 mContext.binder.callingUid = 1234567;
3192 mContext.callerPermissions.add(permission.MANAGE_USERS);
3193 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3194 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3195
3196 // System can retrieve organization managing the device.
3197 mContext.binder.clearCallingIdentity();
3198 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3199
3200 // Removing the device owner clears the organization managing the device.
3201 clearDeviceOwner();
3202 assertNull(dpm.getDeviceOwnerOrganizationName());
3203 }
3204
Victor Chang3e794af2016-03-04 13:48:17 +00003205 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
3206 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
3207 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
3208 dpms.notifyChangeToContentObserver(
3209 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
3210 }
3211
3212 private void assertProvisioningAllowed(String action, boolean expected) {
3213 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
3214 dpm.isProvisioningAllowed(action));
3215 }
Tony Mak2f26b792016-11-28 17:54:51 +00003216
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003217 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00003218 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
3219 }
3220
3221 private void assertCheckProvisioningPreCondition(
3222 String action, String packageName, int provisioningCondition) {
3223 assertEquals("checkProvisioningPreCondition("
3224 + action + ", " + packageName + ") returning unexpected result",
3225 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003226 }
3227
Tony Mak2f26b792016-11-28 17:54:51 +00003228 /**
3229 * Setup a managed profile with the specified admin and its uid.
3230 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
3231 * @param adminUid uid of the admin package.
3232 * @param copyFromAdmin package information for {@code admin} will be built based on this
3233 * component's information.
3234 */
3235 private void addManagedProfile(
3236 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
3237 final int userId = UserHandle.getUserId(adminUid);
3238 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
3239 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3240 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
3241 dpm.setActiveAdmin(admin, false, userId);
3242 assertTrue(dpm.setProfileOwner(admin, null, userId));
3243 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3244 }
Victor Chang3e794af2016-03-04 13:48:17 +00003245}