blob: 5b6d31b464e2dcc420f07c833d22bf39d4e4d635 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Makoto Onukif76b06a2015-09-22 15:03:44 -070018import android.Manifest.permission;
19import android.app.Activity;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070020import android.app.admin.DeviceAdminReceiver;
21import android.app.admin.DevicePolicyManager;
22import android.app.admin.DevicePolicyManagerInternal;
Makoto Onukif76b06a2015-09-22 15:03:44 -070023import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070024import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000025import android.content.Context;
26import android.content.Intent;
27import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000028import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070030import android.content.pm.PackageManager;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010031import android.content.res.Resources;
32import android.graphics.Color;
33import android.net.IIpConnectivityMetrics;
Tony Mak2f26b792016-11-28 17:54:51 +000034import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080035import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080036import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070037import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000038import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080039import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070040import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070041import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080042import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000043import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080044import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000045import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010046import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070047import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070048
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010049import com.android.internal.R;
Alan Treadwayafad8782016-01-19 15:15:08 +000050import com.android.server.LocalServices;
51import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000052import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000053
Makoto Onukib643fb02015-09-22 15:03:44 -070054import org.mockito.invocation.InvocationOnMock;
55import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070056
Makoto Onukic8a5a552015-11-19 14:29:12 -080057import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000058import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000059import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070060import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070062import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010063import java.util.Set;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070064
65import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070066import static org.mockito.Matchers.anyInt;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010067import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070068import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070069import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070070import static org.mockito.Matchers.isNull;
Makoto Onukib643fb02015-09-22 15:03:44 -070071import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070072import static org.mockito.Mockito.doReturn;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080073import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070074import static org.mockito.Mockito.times;
75import static org.mockito.Mockito.verify;
76import static org.mockito.Mockito.when;
77
78/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070079 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070080 *
81 m FrameworksServicesTests &&
82 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000083 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070084 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080085 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070086
87 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
88 */
Benjamin Franz6d009032016-01-25 18:56:38 +000089@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070090public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000091 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
92 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
93 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
94
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095 private DpmMockContext mContext;
96 public DevicePolicyManager dpm;
97 public DevicePolicyManagerServiceTestable dpms;
98
99 @Override
100 protected void setUp() throws Exception {
101 super.setUp();
102
103 mContext = getContext();
104
105 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
106 .thenReturn(true);
107
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800108 // By default, pretend all users are running and unlocked.
109 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
110
Makoto Onukia52562c2015-10-01 16:12:31 -0700111 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700112
Makoto Onukid932f762015-09-29 16:53:38 -0700113 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
114 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
115 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800116 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700117
Makoto Onukib643fb02015-09-22 15:03:44 -0700118 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700119 }
120
Makoto Onukia52562c2015-10-01 16:12:31 -0700121 private void initializeDpms() {
122 // Need clearCallingIdentity() to pass permission checks.
123 final long ident = mContext.binder.clearCallingIdentity();
124 try {
125 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
126
127 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
128
129 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
130 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
131
132 dpm = new DevicePolicyManagerTestable(mContext, dpms);
133 } finally {
134 mContext.binder.restoreCallingIdentity(ident);
135 }
136 }
137
Makoto Onukib643fb02015-09-22 15:03:44 -0700138 private void setUpUserManager() {
139 // Emulate UserManager.set/getApplicationRestriction().
140 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
141
142 // UM.setApplicationRestrictions() will save to appRestrictions.
143 doAnswer(new Answer<Void>() {
144 @Override
145 public Void answer(InvocationOnMock invocation) throws Throwable {
146 String pkg = (String) invocation.getArguments()[0];
147 Bundle bundle = (Bundle) invocation.getArguments()[1];
148 UserHandle user = (UserHandle) invocation.getArguments()[2];
149
150 appRestrictions.put(Pair.create(pkg, user), bundle);
151
152 return null;
153 }
154 }).when(mContext.userManager).setApplicationRestrictions(
155 anyString(), any(Bundle.class), any(UserHandle.class));
156
157 // UM.getApplicationRestrictions() will read from appRestrictions.
158 doAnswer(new Answer<Bundle>() {
159 @Override
160 public Bundle answer(InvocationOnMock invocation) throws Throwable {
161 String pkg = (String) invocation.getArguments()[0];
162 UserHandle user = (UserHandle) invocation.getArguments()[1];
163
164 return appRestrictions.get(Pair.create(pkg, user));
165 }
166 }).when(mContext.userManager).getApplicationRestrictions(
167 anyString(), any(UserHandle.class));
168
Makoto Onukid932f762015-09-29 16:53:38 -0700169 // Add the first secondary user.
170 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700171 }
172
173 private void setAsProfileOwner(ComponentName admin) {
174 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
175 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
176
Makoto Onukia4f11972015-10-01 13:19:58 -0700177 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700178 dpm.setActiveAdmin(admin, /* replace =*/ false);
179
180 // Fire!
181 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
182
183 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700184 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700185 }
186
187 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700188 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
189 .thenReturn(false);
190
191 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
192 new DevicePolicyManagerServiceTestable(mContext, dataDir);
193
194 // If the device has no DPMS feature, it shouldn't register the local service.
195 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
196 }
197
198 /**
199 * Caller doesn't have proper permissions.
200 */
201 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700202 // 1. Failure cases.
203
204 // Caller doesn't have MANAGE_DEVICE_ADMINS.
205 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700206 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700207 fail("Didn't throw SecurityException");
208 } catch (SecurityException expected) {
209 }
210
211 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
212 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
213 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700214 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700215 fail("Didn't throw SecurityException");
216 } catch (SecurityException expected) {
217 }
218 }
219
Makoto Onukif76b06a2015-09-22 15:03:44 -0700220 /**
221 * Test for:
222 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800223 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700224 * {@link DevicePolicyManager#isAdminActive}
225 * {@link DevicePolicyManager#isAdminActiveAsUser}
226 * {@link DevicePolicyManager#getActiveAdmins}
227 * {@link DevicePolicyManager#getActiveAdminsAsUser}
228 */
229 public void testSetActiveAdmin() throws Exception {
230 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700231 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
232
Makoto Onukif76b06a2015-09-22 15:03:44 -0700233 // 2. Call the API.
234 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700235
236 // 3. Verify internal calls.
237
238 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700239 verify(mContext.spiedContext).sendBroadcastAsUser(
240 MockUtils.checkIntentAction(
241 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
242 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
243 verify(mContext.spiedContext).sendBroadcastAsUser(
244 MockUtils.checkIntentAction(
245 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700246 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
247
Makoto Onukif76b06a2015-09-22 15:03:44 -0700248 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
249 eq(admin1.getPackageName()),
250 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
251 eq(PackageManager.DONT_KILL_APP),
252 eq(DpmMockContext.CALLER_USER_HANDLE),
253 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700254
255 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700256
257 // Make sure it's active admin1.
258 assertTrue(dpm.isAdminActive(admin1));
259 assertFalse(dpm.isAdminActive(admin2));
260 assertFalse(dpm.isAdminActive(admin3));
261
262 // But not admin1 for a different user.
263
264 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
265 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
266 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
267
268 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
269 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
270
271 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
272
273 // Next, add one more admin.
274 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700275 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
276 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700277
278 dpm.setActiveAdmin(admin2, /* replace =*/ false);
279
280 // Now we have two admins.
281 assertTrue(dpm.isAdminActive(admin1));
282 assertTrue(dpm.isAdminActive(admin2));
283 assertFalse(dpm.isAdminActive(admin3));
284
285 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
286 // again. (times(1) because it was previously called for admin1)
287 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
288 eq(admin1.getPackageName()),
289 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
290 eq(PackageManager.DONT_KILL_APP),
291 eq(DpmMockContext.CALLER_USER_HANDLE),
292 anyString());
293
294 // 4. Add the same admin1 again without replace, which should throw.
295 try {
296 dpm.setActiveAdmin(admin1, /* replace =*/ false);
297 fail("Didn't throw");
298 } catch (IllegalArgumentException expected) {
299 }
300
301 // 5. Add the same admin1 again with replace, which should succeed.
302 dpm.setActiveAdmin(admin1, /* replace =*/ true);
303
304 // TODO make sure it's replaced.
305
306 // 6. Test getActiveAdmins()
307 List<ComponentName> admins = dpm.getActiveAdmins();
308 assertEquals(2, admins.size());
309 assertEquals(admin1, admins.get(0));
310 assertEquals(admin2, admins.get(1));
311
312 // Another user has no admins.
313 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
314
315 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
316 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
317
318 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
319 }
320
Makoto Onukid932f762015-09-29 16:53:38 -0700321 public void testSetActiveAdmin_multiUsers() throws Exception {
322
323 final int ANOTHER_USER_ID = 100;
324 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
325
326 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
327
328 // Set up pacakge manager for the other user.
329 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700330
331 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
332
333 dpm.setActiveAdmin(admin1, /* replace =*/ false);
334
335 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
336 dpm.setActiveAdmin(admin2, /* replace =*/ false);
337
338
339 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
340 assertTrue(dpm.isAdminActive(admin1));
341 assertFalse(dpm.isAdminActive(admin2));
342
343 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
344 assertFalse(dpm.isAdminActive(admin1));
345 assertTrue(dpm.isAdminActive(admin2));
346 }
347
Makoto Onukif76b06a2015-09-22 15:03:44 -0700348 /**
349 * Test for:
350 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800351 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700352 */
353 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
354 // 1. Make sure the caller has proper permissions.
355 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
356
357 dpm.setActiveAdmin(admin1, /* replace =*/ false);
358 assertTrue(dpm.isAdminActive(admin1));
359
360 // Add the same admin1 again without replace, which should throw.
361 try {
362 dpm.setActiveAdmin(admin1, /* replace =*/ false);
363 fail("Didn't throw");
364 } catch (IllegalArgumentException expected) {
365 }
366 }
367
368 /**
369 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800370 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
371 * BIND_DEVICE_ADMIN.
372 */
373 public void testSetActiveAdmin_permissionCheck() throws Exception {
374 // 1. Make sure the caller has proper permissions.
375 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
376
377 try {
378 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
379 fail();
380 } catch (IllegalArgumentException expected) {
381 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
382 }
383 assertFalse(dpm.isAdminActive(adminNoPerm));
384
385 // Change the target API level to MNC. Now it can be set as DA.
386 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
387 VERSION_CODES.M);
388 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
389 assertTrue(dpm.isAdminActive(adminNoPerm));
390
391 // TODO Test the "load from the file" case where DA will still be loaded even without
392 // BIND_DEVICE_ADMIN and target API is N.
393 }
394
395 /**
396 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700397 * {@link DevicePolicyManager#removeActiveAdmin}
398 */
399 public void testRemoveActiveAdmin_SecurityException() {
400 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
401
402 // Add admin.
403
404 dpm.setActiveAdmin(admin1, /* replace =*/ false);
405
406 assertTrue(dpm.isAdminActive(admin1));
407
408 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
409
410 // Directly call the DPMS method with a different userid, which should fail.
411 try {
412 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
413 fail("Didn't throw SecurityException");
414 } catch (SecurityException expected) {
415 }
416
417 // Try to remove active admin with a different caller userid should fail too, without
418 // having MANAGE_DEVICE_ADMINS.
419 mContext.callerPermissions.clear();
420
Makoto Onukid932f762015-09-29 16:53:38 -0700421 // Change the caller, and call into DPMS directly with a different user-id.
422
Makoto Onukif76b06a2015-09-22 15:03:44 -0700423 mContext.binder.callingUid = 1234567;
424 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700425 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700426 fail("Didn't throw SecurityException");
427 } catch (SecurityException expected) {
428 }
429 }
430
431 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800432 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
433 * (because we can't send the remove broadcast).
434 */
435 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
436 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
437
438 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
439
440 // Add admin.
441
442 dpm.setActiveAdmin(admin1, /* replace =*/ false);
443
444 assertTrue(dpm.isAdminActive(admin1));
445
446 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
447
448 // 1. User not unlocked.
449 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
450 .thenReturn(false);
451 try {
452 dpm.removeActiveAdmin(admin1);
453 fail("Didn't throw IllegalStateException");
454 } catch (IllegalStateException expected) {
455 MoreAsserts.assertContainsRegex(
456 "User must be running and unlocked", expected.getMessage());
457 }
458
459 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
460
461 // 2. User unlocked.
462 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
463 .thenReturn(true);
464
465 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700466 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800467 }
468
469 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700470 * Test for:
471 * {@link DevicePolicyManager#removeActiveAdmin}
472 */
Makoto Onukid932f762015-09-29 16:53:38 -0700473 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700474 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
475
476 // Add admin1.
477
478 dpm.setActiveAdmin(admin1, /* replace =*/ false);
479
480 assertTrue(dpm.isAdminActive(admin1));
481 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
482
483 // Different user, but should work, because caller has proper permissions.
484 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700485
486 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700487 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700488
489 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700490 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700491
492 // TODO DO Still can't be removed in this case.
493 }
494
495 /**
496 * Test for:
497 * {@link DevicePolicyManager#removeActiveAdmin}
498 */
499 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
500 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
501 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
502
503 // Add admin1.
504
505 dpm.setActiveAdmin(admin1, /* replace =*/ false);
506
507 assertTrue(dpm.isAdminActive(admin1));
508 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
509
510 // Broadcast from saveSettingsLocked().
511 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
512 MockUtils.checkIntentAction(
513 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
514 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
515
516 // Remove. No permissions, but same user, so it'll work.
517 mContext.callerPermissions.clear();
518 dpm.removeActiveAdmin(admin1);
519
Makoto Onukif76b06a2015-09-22 15:03:44 -0700520 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
521 MockUtils.checkIntentAction(
522 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
523 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
524 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700525 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700526 eq(dpms.mHandler),
527 eq(Activity.RESULT_OK),
528 isNull(String.class),
529 isNull(Bundle.class));
530
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700531 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700532
533 // Again broadcast from saveSettingsLocked().
534 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
535 MockUtils.checkIntentAction(
536 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
537 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
538
539 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700540 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700541
542 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000543 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700544 */
545 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000546 setDeviceOwner();
547
548 // Try to set a profile owner on the same user, which should fail.
549 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
550 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
551 try {
552 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
553 fail("IllegalStateException not thrown");
554 } catch (IllegalStateException expected) {
555 assertTrue("Message was: " + expected.getMessage(),
556 expected.getMessage().contains("already has a device owner"));
557 }
558
559 // DO admin can't be deactivated.
560 dpm.removeActiveAdmin(admin1);
561 assertTrue(dpm.isAdminActive(admin1));
562
563 // TODO Test getDeviceOwnerName() too. To do so, we need to change
564 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
565 }
566
567 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700568 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800569 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700570 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
571 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
572
Makoto Onukid932f762015-09-29 16:53:38 -0700573 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700574 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
575
Makoto Onukid932f762015-09-29 16:53:38 -0700576 // Make sure admin1 is installed on system user.
577 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700578
Makoto Onukic8a5a552015-11-19 14:29:12 -0800579 // Check various get APIs.
580 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
581
Makoto Onukib643fb02015-09-22 15:03:44 -0700582 // DO needs to be an DA.
583 dpm.setActiveAdmin(admin1, /* replace =*/ false);
584
585 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700586 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700587
Makoto Onukic8a5a552015-11-19 14:29:12 -0800588 // getDeviceOwnerComponent should return the admin1 component.
589 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
590 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
591
592 // Check various get APIs.
593 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
594
595 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
596 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
597 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
598 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
599
600 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
601
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000602 // Verify internal calls.
603 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
604 eq(admin1.getPackageName()));
605
Makoto Onukib643fb02015-09-22 15:03:44 -0700606 // TODO We should check if the caller has called clearCallerIdentity().
607 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
608 eq(UserHandle.USER_SYSTEM), eq(false));
609
610 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
611 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
612 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
613
Makoto Onukic8a5a552015-11-19 14:29:12 -0800614 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700615 }
616
Makoto Onukic8a5a552015-11-19 14:29:12 -0800617 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
618 final int origCallingUser = mContext.binder.callingUid;
619 final List origPermissions = new ArrayList(mContext.callerPermissions);
620 mContext.callerPermissions.clear();
621
622 mContext.callerPermissions.add(permission.MANAGE_USERS);
623
624 mContext.binder.callingUid = Process.SYSTEM_UID;
625
626 // TODO Test getDeviceOwnerName() too. To do so, we need to change
627 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
628 if (hasDeviceOwner) {
629 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
630 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
631 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
632
633 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
634 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
635 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
636 } else {
637 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
638 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
639 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
640
641 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
642 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
643 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
644 }
645
646 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
647 if (hasDeviceOwner) {
648 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
649 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
650 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
651
652 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
653 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
654 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
655 } else {
656 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
657 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
658 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
659
660 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
661 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
662 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
663 }
664
665 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
666 // Still with MANAGE_USERS.
667 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
668 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
669 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
670
671 if (hasDeviceOwner) {
672 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
673 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
674 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
675 } else {
676 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
677 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
678 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
679 }
680
681 mContext.binder.callingUid = Process.SYSTEM_UID;
682 mContext.callerPermissions.remove(permission.MANAGE_USERS);
683 // System can still call "OnAnyUser" without MANAGE_USERS.
684 if (hasDeviceOwner) {
685 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
686 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
687 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
688
689 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
690 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
691 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
692 } else {
693 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
694 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
695 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
696
697 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
698 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
699 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
700 }
701
702 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
703 // Still no MANAGE_USERS.
704 if (hasDeviceOwner) {
705 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
706 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
707 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
708 } else {
709 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
710 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
711 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
712 }
713
714 try {
715 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
716 fail();
717 } catch (SecurityException expected) {
718 }
719 try {
720 dpm.getDeviceOwnerComponentOnAnyUser();
721 fail();
722 } catch (SecurityException expected) {
723 }
724 try {
725 dpm.getDeviceOwnerUserId();
726 fail();
727 } catch (SecurityException expected) {
728 }
729 try {
730 dpm.getDeviceOwnerNameOnAnyUser();
731 fail();
732 } catch (SecurityException expected) {
733 }
734
735 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
736 // Still no MANAGE_USERS.
737 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
738 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
739 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
740
741 try {
742 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
743 fail();
744 } catch (SecurityException expected) {
745 }
746 try {
747 dpm.getDeviceOwnerComponentOnAnyUser();
748 fail();
749 } catch (SecurityException expected) {
750 }
751 try {
752 dpm.getDeviceOwnerUserId();
753 fail();
754 } catch (SecurityException expected) {
755 }
756 try {
757 dpm.getDeviceOwnerNameOnAnyUser();
758 fail();
759 } catch (SecurityException expected) {
760 }
761
762 // Restore.
763 mContext.binder.callingUid = origCallingUser;
764 mContext.callerPermissions.addAll(origPermissions);
765 }
766
767
Makoto Onukib643fb02015-09-22 15:03:44 -0700768 /**
769 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
770 */
771 public void testSetDeviceOwner_noSuchPackage() {
772 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800773 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700774 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
775 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
776
777 // Call from a process on the system user.
778 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
779
Makoto Onukib643fb02015-09-22 15:03:44 -0700780 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700781 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700782 fail("Didn't throw IllegalArgumentException");
783 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700784 assertTrue("Message was: " + expected.getMessage(),
785 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700786 }
787 }
788
789 public void testSetDeviceOwner_failures() throws Exception {
790 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
791 }
792
Makoto Onukia52562c2015-10-01 16:12:31 -0700793 public void testClearDeviceOwner() throws Exception {
794 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800795 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700796 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
797 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
798
799 // Set admin1 as a DA to the secondary user.
800 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
801
802 dpm.setActiveAdmin(admin1, /* replace =*/ false);
803
804 // Set admin 1 as the DO to the system user.
805
806 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
807 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
808 dpm.setActiveAdmin(admin1, /* replace =*/ false);
809 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
810
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000811 // Verify internal calls.
812 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
813 eq(admin1.getPackageName()));
814
Makoto Onukic8a5a552015-11-19 14:29:12 -0800815 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700816
Makoto Onuki90b89652016-01-28 14:44:18 -0800817 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
818
819 assertTrue(dpm.isAdminActive(admin1));
820 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
821
Makoto Onukia52562c2015-10-01 16:12:31 -0700822 // Set up other mocks.
823 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
824
825 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700826 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700827 eq(admin1.getPackageName()),
828 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800829
830 // But first pretend the user is locked. Then it should fail.
831 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
832 try {
833 dpm.clearDeviceOwnerApp(admin1.getPackageName());
834 fail("Didn't throw IllegalStateException");
835 } catch (IllegalStateException expected) {
836 MoreAsserts.assertContainsRegex(
837 "User must be running and unlocked", expected.getMessage());
838 }
839
840 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800841 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700842 dpm.clearDeviceOwnerApp(admin1.getPackageName());
843
844 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800845 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700846
Makoto Onuki90b89652016-01-28 14:44:18 -0800847 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
848 eq(UserHandle.USER_SYSTEM),
849 MockUtils.checkUserRestrictions(),
850 MockUtils.checkUserRestrictions()
851 );
852
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700853 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100854
855 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
856 // and once for clearing it.
857 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
858 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
859 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700860 // TODO Check other calls.
861 }
862
863 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
864 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800865 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700866 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
867 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
868
869 // Set admin1 as a DA to the secondary user.
870 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
871
872 dpm.setActiveAdmin(admin1, /* replace =*/ false);
873
874 // Set admin 1 as the DO to the system user.
875
876 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
877 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
878 dpm.setActiveAdmin(admin1, /* replace =*/ false);
879 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
880
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000881 // Verify internal calls.
882 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
883 eq(admin1.getPackageName()));
884
Makoto Onukic8a5a552015-11-19 14:29:12 -0800885 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700886
887 // Now call clear from the secondary user, which should throw.
888 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
889
890 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700891 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700892 eq(admin1.getPackageName()),
893 anyInt());
894 try {
895 dpm.clearDeviceOwnerApp(admin1.getPackageName());
896 fail("Didn't throw");
897 } catch (SecurityException e) {
898 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
899 }
900
Makoto Onukic8a5a552015-11-19 14:29:12 -0800901 // DO shouldn't be removed.
902 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700903 }
904
Makoto Onukib643fb02015-09-22 15:03:44 -0700905 public void testSetProfileOwner() throws Exception {
906 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700907
Makoto Onuki90b89652016-01-28 14:44:18 -0800908 // PO admin can't be deactivated.
909 dpm.removeActiveAdmin(admin1);
910 assertTrue(dpm.isAdminActive(admin1));
911
Makoto Onuki803d6752015-10-30 12:58:39 -0700912 // Try setting DO on the same user, which should fail.
913 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
914 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
915 try {
916 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
917 fail("IllegalStateException not thrown");
918 } catch (IllegalStateException expected) {
919 assertTrue("Message was: " + expected.getMessage(),
920 expected.getMessage().contains("already has a profile owner"));
921 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700922 }
923
Makoto Onuki90b89652016-01-28 14:44:18 -0800924 public void testClearProfileOwner() throws Exception {
925 setAsProfileOwner(admin1);
926
927 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
928
929 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
930 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
931
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800932 // First try when the user is locked, which should fail.
933 when(mContext.userManager.isUserUnlocked(anyInt()))
934 .thenReturn(false);
935 try {
936 dpm.clearProfileOwner(admin1);
937 fail("Didn't throw IllegalStateException");
938 } catch (IllegalStateException expected) {
939 MoreAsserts.assertContainsRegex(
940 "User must be running and unlocked", expected.getMessage());
941 }
942 // Clear, really.
943 when(mContext.userManager.isUserUnlocked(anyInt()))
944 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800945 dpm.clearProfileOwner(admin1);
946
947 // Check
948 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700949 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -0800950 }
951
Makoto Onukib643fb02015-09-22 15:03:44 -0700952 public void testSetProfileOwner_failures() throws Exception {
953 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
954 }
955
Makoto Onukia52562c2015-10-01 16:12:31 -0700956 public void testGetDeviceOwnerAdminLocked() throws Exception {
957 checkDeviceOwnerWithMultipleDeviceAdmins();
958 }
959
960 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
961 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
962 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
963 // make sure it gets the right component from the right user.
964
965 final int ANOTHER_USER_ID = 100;
966 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
967
968 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
969
970 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800971 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700972 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
973 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
974
975 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
976
Victor Change29cd472016-03-02 20:57:42 +0000977 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
978
Makoto Onukia52562c2015-10-01 16:12:31 -0700979 // Make sure the admin packge is installed to each user.
980 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
981 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
982
983 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
984 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
985
986 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
987
988
989 // Set active admins to the users.
990 dpm.setActiveAdmin(admin1, /* replace =*/ false);
991 dpm.setActiveAdmin(admin3, /* replace =*/ false);
992
993 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
994 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
995
996 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
997
998 // Set DO on the first non-system user.
999 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1000 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1001
Makoto Onukic8a5a552015-11-19 14:29:12 -08001002 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001003
1004 // Then check getDeviceOwnerAdminLocked().
1005 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1006 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1007 }
1008
1009 /**
1010 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001011 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1012 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001013 *
1014 * We didn't use to persist the DO component class name, but now we do, and the above method
1015 * finds the right component from a package name upon migration.
1016 */
1017 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001018 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001019 checkDeviceOwnerWithMultipleDeviceAdmins();
1020
1021 // Overwrite the device owner setting and clears the clas name.
1022 dpms.mOwners.setDeviceOwner(
1023 new ComponentName(admin2.getPackageName(), ""),
1024 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1025 dpms.mOwners.writeDeviceOwner();
1026
1027 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001028 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001029
1030 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001031 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1032 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001033 initializeDpms();
1034
1035 // Now the DO component name is a full name.
1036 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1037 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001038 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001039 }
1040
Makoto Onukib643fb02015-09-22 15:03:44 -07001041 public void testSetGetApplicationRestriction() {
1042 setAsProfileOwner(admin1);
1043
1044 {
1045 Bundle rest = new Bundle();
1046 rest.putString("KEY_STRING", "Foo1");
1047 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1048 }
1049
1050 {
1051 Bundle rest = new Bundle();
1052 rest.putString("KEY_STRING", "Foo2");
1053 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1054 }
1055
1056 {
1057 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1058 assertNotNull(returned);
1059 assertEquals(returned.size(), 1);
1060 assertEquals(returned.get("KEY_STRING"), "Foo1");
1061 }
1062
1063 {
1064 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1065 assertNotNull(returned);
1066 assertEquals(returned.size(), 1);
1067 assertEquals(returned.get("KEY_STRING"), "Foo2");
1068 }
1069
1070 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1071 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1072 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001073
Esteban Talaverabf60f722015-12-10 16:26:44 +00001074 public void testApplicationRestrictionsManagingApp() throws Exception {
1075 setAsProfileOwner(admin1);
1076
Rubin Xued1928a2016-02-11 17:23:06 +00001077 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001078 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1079 final int appRestrictionsManagerAppId = 20987;
1080 final int appRestrictionsManagerUid = UserHandle.getUid(
1081 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001082 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001083 eq(appRestrictionsManagerPackage),
1084 eq(DpmMockContext.CALLER_USER_HANDLE));
1085 mContext.binder.callingUid = appRestrictionsManagerUid;
1086
Rubin Xued1928a2016-02-11 17:23:06 +00001087 final PackageInfo pi = new PackageInfo();
1088 pi.applicationInfo = new ApplicationInfo();
1089 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1090 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1091 eq(appRestrictionsManagerPackage),
1092 anyInt(),
1093 eq(DpmMockContext.CALLER_USER_HANDLE));
1094
Esteban Talaverabf60f722015-12-10 16:26:44 +00001095 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1096 // delegated that permission yet.
1097 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1098 Bundle rest = new Bundle();
1099 rest.putString("KEY_STRING", "Foo1");
1100 try {
1101 dpm.setApplicationRestrictions(null, "pkg1", rest);
1102 fail("Didn't throw expected SecurityException");
1103 } catch (SecurityException expected) {
1104 MoreAsserts.assertContainsRegex(
1105 "caller cannot manage application restrictions", expected.getMessage());
1106 }
1107 try {
1108 dpm.getApplicationRestrictions(null, "pkg1");
1109 fail("Didn't throw expected SecurityException");
1110 } catch (SecurityException expected) {
1111 MoreAsserts.assertContainsRegex(
1112 "caller cannot manage application restrictions", expected.getMessage());
1113 }
1114
1115 // Check via the profile owner that no restrictions were set.
1116 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1117 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1118
Rubin Xued1928a2016-02-11 17:23:06 +00001119 // Check the API does not allow setting a non-existent package
1120 try {
1121 dpm.setApplicationRestrictionsManagingPackage(admin1,
1122 nonExistAppRestrictionsManagerPackage);
1123 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001124 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001125 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001126 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001127 }
1128
Esteban Talaverabf60f722015-12-10 16:26:44 +00001129 // Let appRestrictionsManagerPackage manage app restrictions
1130 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1131 assertEquals(appRestrictionsManagerPackage,
1132 dpm.getApplicationRestrictionsManagingPackage(admin1));
1133
1134 // Now that package should be able to set and retrieve app restrictions.
1135 mContext.binder.callingUid = appRestrictionsManagerUid;
1136 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1137 dpm.setApplicationRestrictions(null, "pkg1", rest);
1138 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1139 assertEquals(1, returned.size(), 1);
1140 assertEquals("Foo1", returned.get("KEY_STRING"));
1141
1142 // The same app running on a separate user shouldn't be able to manage app restrictions.
1143 mContext.binder.callingUid = UserHandle.getUid(
1144 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1145 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1146 try {
1147 dpm.setApplicationRestrictions(null, "pkg1", rest);
1148 fail("Didn't throw expected SecurityException");
1149 } catch (SecurityException expected) {
1150 MoreAsserts.assertContainsRegex(
1151 "caller cannot manage application restrictions", expected.getMessage());
1152 }
1153
1154 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1155 // too.
1156 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1157 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1158 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1159 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1160
1161 // Removing the ability for the package to manage app restrictions.
1162 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1163 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1164 mContext.binder.callingUid = appRestrictionsManagerUid;
1165 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1166 try {
1167 dpm.setApplicationRestrictions(null, "pkg1", null);
1168 fail("Didn't throw expected SecurityException");
1169 } catch (SecurityException expected) {
1170 MoreAsserts.assertContainsRegex(
1171 "caller cannot manage application restrictions", expected.getMessage());
1172 }
1173 }
1174
Makoto Onukia4f11972015-10-01 13:19:58 -07001175 public void testSetUserRestriction_asDo() throws Exception {
1176 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001177 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001178 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1179 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1180
1181 // First, set DO.
1182
1183 // Call from a process on the system user.
1184 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1185
1186 // Make sure admin1 is installed on system user.
1187 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001188
1189 // Call.
1190 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001191 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001192 UserHandle.USER_SYSTEM));
1193
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001194 // Check that the user restrictions that are enabled by default are set. Then unset them.
1195 String[] defaultRestrictions = UserRestrictionsUtils
1196 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1197 DpmTestUtils.assertRestrictions(
1198 DpmTestUtils.newRestrictions(defaultRestrictions),
1199 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1200 );
1201 DpmTestUtils.assertRestrictions(
1202 DpmTestUtils.newRestrictions(defaultRestrictions),
1203 dpm.getUserRestrictions(admin1)
1204 );
1205
1206 for (String restriction : defaultRestrictions) {
1207 dpm.clearUserRestriction(admin1, restriction);
1208 }
1209
Makoto Onuki068c54a2015-10-13 14:34:03 -07001210 DpmTestUtils.assertRestrictions(
1211 DpmTestUtils.newRestrictions(),
1212 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1213 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001214 DpmTestUtils.assertRestrictions(
1215 DpmTestUtils.newRestrictions(),
1216 dpm.getUserRestrictions(admin1)
1217 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001218
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001219 reset(mContext.userManagerInternal);
1220
1221 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1222 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1223 eq(UserHandle.USER_SYSTEM),
1224 MockUtils.checkUserRestrictions(),
1225 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001226 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001227 reset(mContext.userManagerInternal);
1228
Makoto Onukia4f11972015-10-01 13:19:58 -07001229 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001230 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1231 eq(UserHandle.USER_SYSTEM),
1232 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1233 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1234 );
1235 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001236
Makoto Onuki068c54a2015-10-13 14:34:03 -07001237 DpmTestUtils.assertRestrictions(
1238 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001239 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001240 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1241 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001242 DpmTestUtils.assertRestrictions(
1243 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001244 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001245 dpm.getUserRestrictions(admin1)
1246 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001247
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001248 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1249 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1250 eq(UserHandle.USER_SYSTEM),
1251 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1252 MockUtils.checkUserRestrictions()
1253 );
1254 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001255
Makoto Onuki068c54a2015-10-13 14:34:03 -07001256 DpmTestUtils.assertRestrictions(
1257 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1258 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1259 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001260 DpmTestUtils.assertRestrictions(
1261 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1262 dpm.getUserRestrictions(admin1)
1263 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001264
1265 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001266 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1267 eq(UserHandle.USER_SYSTEM),
1268 MockUtils.checkUserRestrictions(),
1269 MockUtils.checkUserRestrictions()
1270 );
1271 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001272
Makoto Onuki068c54a2015-10-13 14:34:03 -07001273 DpmTestUtils.assertRestrictions(
1274 DpmTestUtils.newRestrictions(),
1275 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1276 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001277 DpmTestUtils.assertRestrictions(
1278 DpmTestUtils.newRestrictions(),
1279 dpm.getUserRestrictions(admin1)
1280 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001281
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001282 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1283 // DO sets them, the scope is global.
1284 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1285 reset(mContext.userManagerInternal);
1286 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1287 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1288 eq(UserHandle.USER_SYSTEM),
1289 MockUtils.checkUserRestrictions(),
1290 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1291 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1292 );
1293 reset(mContext.userManagerInternal);
1294
1295 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1296 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1297
1298
1299 // More tests.
1300 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1301 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1302 eq(UserHandle.USER_SYSTEM),
1303 MockUtils.checkUserRestrictions(),
1304 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1305 );
1306 reset(mContext.userManagerInternal);
1307
1308 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1309 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1310 eq(UserHandle.USER_SYSTEM),
1311 MockUtils.checkUserRestrictions(),
1312 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1313 UserManager.DISALLOW_ADD_USER)
1314 );
1315 reset(mContext.userManagerInternal);
1316
1317 dpm.setCameraDisabled(admin1, true);
1318 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1319 eq(UserHandle.USER_SYSTEM),
1320 // DISALLOW_CAMERA will be applied to both local and global.
1321 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1322 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1323 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1324 );
1325 reset(mContext.userManagerInternal);
1326
1327 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1328 // locally.
1329 dpm.setCameraDisabled(admin1, false);
1330 reset(mContext.userManagerInternal);
1331
1332 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1333 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1334 dpm.setCameraDisabled(admin2, true);
1335
1336 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1337 eq(UserHandle.USER_SYSTEM),
1338 // DISALLOW_CAMERA will be applied to both local and global.
1339 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1340 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1341 UserManager.DISALLOW_ADD_USER)
1342 );
1343 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001344 // TODO Make sure restrictions are written to the file.
1345 }
1346
1347 public void testSetUserRestriction_asPo() {
1348 setAsProfileOwner(admin1);
1349
Makoto Onuki068c54a2015-10-13 14:34:03 -07001350 DpmTestUtils.assertRestrictions(
1351 DpmTestUtils.newRestrictions(),
1352 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1353 .ensureUserRestrictions()
1354 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001355
1356 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001357 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1358 eq(DpmMockContext.CALLER_USER_HANDLE),
1359 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1360 isNull(Bundle.class)
1361 );
1362 reset(mContext.userManagerInternal);
1363
Makoto Onukia4f11972015-10-01 13:19:58 -07001364 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001365 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1366 eq(DpmMockContext.CALLER_USER_HANDLE),
1367 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1368 UserManager.DISALLOW_OUTGOING_CALLS),
1369 isNull(Bundle.class)
1370 );
1371 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001372
Makoto Onuki068c54a2015-10-13 14:34:03 -07001373 DpmTestUtils.assertRestrictions(
1374 DpmTestUtils.newRestrictions(
1375 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1376 UserManager.DISALLOW_OUTGOING_CALLS
1377 ),
1378 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1379 .ensureUserRestrictions()
1380 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001381 DpmTestUtils.assertRestrictions(
1382 DpmTestUtils.newRestrictions(
1383 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1384 UserManager.DISALLOW_OUTGOING_CALLS
1385 ),
1386 dpm.getUserRestrictions(admin1)
1387 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001388
1389 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001390 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1391 eq(DpmMockContext.CALLER_USER_HANDLE),
1392 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1393 isNull(Bundle.class)
1394 );
1395 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001396
1397 DpmTestUtils.assertRestrictions(
1398 DpmTestUtils.newRestrictions(
1399 UserManager.DISALLOW_OUTGOING_CALLS
1400 ),
1401 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1402 .ensureUserRestrictions()
1403 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001404 DpmTestUtils.assertRestrictions(
1405 DpmTestUtils.newRestrictions(
1406 UserManager.DISALLOW_OUTGOING_CALLS
1407 ),
1408 dpm.getUserRestrictions(admin1)
1409 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001410
1411 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001412 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1413 eq(DpmMockContext.CALLER_USER_HANDLE),
1414 MockUtils.checkUserRestrictions(),
1415 isNull(Bundle.class)
1416 );
1417 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001418
Makoto Onuki068c54a2015-10-13 14:34:03 -07001419 DpmTestUtils.assertRestrictions(
1420 DpmTestUtils.newRestrictions(),
1421 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1422 .ensureUserRestrictions()
1423 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001424 DpmTestUtils.assertRestrictions(
1425 DpmTestUtils.newRestrictions(),
1426 dpm.getUserRestrictions(admin1)
1427 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001428
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001429 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1430 // though when DO sets them they'll be applied globally.
1431 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1432 reset(mContext.userManagerInternal);
1433 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1434 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1435 eq(DpmMockContext.CALLER_USER_HANDLE),
1436 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1437 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1438 isNull(Bundle.class)
1439 );
1440 reset(mContext.userManagerInternal);
1441
1442 dpm.setCameraDisabled(admin1, true);
1443 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1444 eq(DpmMockContext.CALLER_USER_HANDLE),
1445 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1446 UserManager.DISALLOW_ADJUST_VOLUME,
1447 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1448 isNull(Bundle.class)
1449 );
1450 reset(mContext.userManagerInternal);
1451
Makoto Onukia4f11972015-10-01 13:19:58 -07001452 // TODO Make sure restrictions are written to the file.
1453 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001454
1455 public void testGetMacAddress() throws Exception {
1456 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1457 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1458 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1459
1460 // In this test, change the caller user to "system".
1461 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1462
1463 // Make sure admin1 is installed on system user.
1464 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1465
1466 // Test 1. Caller doesn't have DO or DA.
1467 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001468 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001469 fail();
1470 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001471 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001472 }
1473
1474 // DO needs to be an DA.
1475 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1476 assertTrue(dpm.isAdminActive(admin1));
1477
1478 // Test 2. Caller has DA, but not DO.
1479 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001480 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001481 fail();
1482 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001483 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001484 }
1485
1486 // Test 3. Caller has PO, but not DO.
1487 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1488 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001489 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001490 fail();
1491 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001492 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001493 }
1494
1495 // Remove PO.
1496 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001497 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001498 // Test 4, Caller is DO now.
1499 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1500
1501 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001502 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001503
1504 // 4-2. Returns WifiInfo, but with the default MAC.
1505 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001506 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001507
1508 // 4-3. With a real MAC address.
1509 final WifiInfo wi = new WifiInfo();
1510 wi.setMacAddress("11:22:33:44:55:66");
1511 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001512 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001513 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001514
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001515 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001516 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1517 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1518
1519 // In this test, change the caller user to "system".
1520 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1521
1522 // Make sure admin1 is installed on system user.
1523 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1524
1525 // Set admin1 as DA.
1526 dpm.setActiveAdmin(admin1, false);
1527 assertTrue(dpm.isAdminActive(admin1));
1528 try {
1529 dpm.reboot(admin1);
1530 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1531 } catch (SecurityException expected) {
1532 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1533 }
1534
1535 // Set admin1 as PO.
1536 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1537 try {
1538 dpm.reboot(admin1);
1539 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1540 } catch (SecurityException expected) {
1541 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1542 }
1543
1544 // Remove PO and add DO.
1545 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001546 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001547 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1548
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001549 // admin1 is DO.
1550 // Set current call state of device to ringing.
1551 when(mContext.telephonyManager.getCallState())
1552 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1553 try {
1554 dpm.reboot(admin1);
1555 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1556 } catch (IllegalStateException expected) {
1557 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1558 }
1559
1560 // Set current call state of device to dialing/active.
1561 when(mContext.telephonyManager.getCallState())
1562 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1563 try {
1564 dpm.reboot(admin1);
1565 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1566 } catch (IllegalStateException expected) {
1567 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1568 }
1569
1570 // Set current call state of device to idle.
1571 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001572 dpm.reboot(admin1);
1573 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001574
1575 public void testSetGetSupportText() {
1576 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1577 dpm.setActiveAdmin(admin1, true);
1578 dpm.setActiveAdmin(admin2, true);
1579 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1580
1581 // Null default support messages.
1582 {
1583 assertNull(dpm.getLongSupportMessage(admin1));
1584 assertNull(dpm.getShortSupportMessage(admin1));
1585 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1586 assertNull(dpm.getShortSupportMessageForUser(admin1,
1587 DpmMockContext.CALLER_USER_HANDLE));
1588 assertNull(dpm.getLongSupportMessageForUser(admin1,
1589 DpmMockContext.CALLER_USER_HANDLE));
1590 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1591 }
1592
1593 // Only system can call the per user versions.
1594 {
1595 try {
1596 dpm.getShortSupportMessageForUser(admin1,
1597 DpmMockContext.CALLER_USER_HANDLE);
1598 fail("Only system should be able to call getXXXForUser versions");
1599 } catch (SecurityException expected) {
1600 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1601 }
1602 try {
1603 dpm.getLongSupportMessageForUser(admin1,
1604 DpmMockContext.CALLER_USER_HANDLE);
1605 fail("Only system should be able to call getXXXForUser versions");
1606 } catch (SecurityException expected) {
1607 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1608 }
1609 }
1610
1611 // Can't set message for admin in another uid.
1612 {
1613 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1614 try {
1615 dpm.setShortSupportMessage(admin1, "Some text");
1616 fail("Admins should only be able to change their own support text.");
1617 } catch (SecurityException expected) {
1618 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1619 }
1620 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1621 }
1622
1623 // Set/Get short returns what it sets and other admins text isn't changed.
1624 {
1625 final String supportText = "Some text to test with.";
1626 dpm.setShortSupportMessage(admin1, supportText);
1627 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1628 assertNull(dpm.getLongSupportMessage(admin1));
1629 assertNull(dpm.getShortSupportMessage(admin2));
1630
1631 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1632 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1633 DpmMockContext.CALLER_USER_HANDLE));
1634 assertNull(dpm.getShortSupportMessageForUser(admin2,
1635 DpmMockContext.CALLER_USER_HANDLE));
1636 assertNull(dpm.getLongSupportMessageForUser(admin1,
1637 DpmMockContext.CALLER_USER_HANDLE));
1638 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1639
1640 dpm.setShortSupportMessage(admin1, null);
1641 assertNull(dpm.getShortSupportMessage(admin1));
1642 }
1643
1644 // Set/Get long returns what it sets and other admins text isn't changed.
1645 {
1646 final String supportText = "Some text to test with.\nWith more text.";
1647 dpm.setLongSupportMessage(admin1, supportText);
1648 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1649 assertNull(dpm.getShortSupportMessage(admin1));
1650 assertNull(dpm.getLongSupportMessage(admin2));
1651
1652 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1653 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1654 DpmMockContext.CALLER_USER_HANDLE));
1655 assertNull(dpm.getLongSupportMessageForUser(admin2,
1656 DpmMockContext.CALLER_USER_HANDLE));
1657 assertNull(dpm.getShortSupportMessageForUser(admin1,
1658 DpmMockContext.CALLER_USER_HANDLE));
1659 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1660
1661 dpm.setLongSupportMessage(admin1, null);
1662 assertNull(dpm.getLongSupportMessage(admin1));
1663 }
1664 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001665
1666 /**
1667 * Test for:
1668 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001669 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001670 * {@link DevicePolicyManager#isAffiliatedUser}
1671 */
1672 public void testUserAffiliation() throws Exception {
1673 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1674 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1675 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1676
1677 // Check that the system user is unaffiliated.
1678 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1679 assertFalse(dpm.isAffiliatedUser());
1680
1681 // Set a device owner on the system user. Check that the system user becomes affiliated.
1682 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1683 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1684 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1685 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001686 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001687
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001688 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001689 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1690 setAsProfileOwner(admin2);
1691 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001692 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001693
1694 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1695 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001696 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001697 userAffiliationIds.add("red");
1698 userAffiliationIds.add("green");
1699 userAffiliationIds.add("blue");
1700 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001701 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001702 assertFalse(dpm.isAffiliatedUser());
1703
1704 // Have the device owner specify a set of affiliation ids that do not intersect with those
1705 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001706 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001707 deviceAffiliationIds.add("cyan");
1708 deviceAffiliationIds.add("yellow");
1709 deviceAffiliationIds.add("magenta");
1710 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1711 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001712 MoreAsserts.assertContentsInAnyOrder(
1713 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001714 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1715 assertFalse(dpm.isAffiliatedUser());
1716
1717 // Have the profile owner specify a set of affiliation ids that intersect with those
1718 // specified by the device owner. Check that the test user becomes affiliated.
1719 userAffiliationIds.add("yellow");
1720 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001721 MoreAsserts.assertContentsInAnyOrder(
1722 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001723 assertTrue(dpm.isAffiliatedUser());
1724
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001725 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
1726 dpm.setAffiliationIds(admin2, Collections.emptyList());
1727 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001728 assertFalse(dpm.isAffiliatedUser());
1729
1730 // Check that the system user remains affiliated.
1731 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1732 assertTrue(dpm.isAffiliatedUser());
1733 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001734
1735 public void testGetUserProvisioningState_defaultResult() {
1736 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1737 }
1738
1739 public void testSetUserProvisioningState_permission() throws Exception {
1740 setupProfileOwner();
1741 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1742
1743 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1744 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1745 }
1746
1747 public void testSetUserProvisioningState_unprivileged() throws Exception {
1748 setupProfileOwner();
1749 try {
1750 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1751 DpmMockContext.CALLER_USER_HANDLE);
1752 fail("Expected SecurityException");
1753 } catch (SecurityException expected) {
1754 }
1755 }
1756
1757 public void testSetUserProvisioningState_noManagement() {
1758 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1759 try {
1760 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1761 DpmMockContext.CALLER_USER_HANDLE);
1762 fail("IllegalStateException expected");
1763 } catch (IllegalStateException e) {
1764 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1765 e.getMessage());
1766 }
1767 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1768 }
1769
1770 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1771 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1772 setupDeviceOwner();
1773 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1774
1775 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1776 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1777 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1778 }
1779
1780 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1781 throws Exception {
1782 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1783 setupDeviceOwner();
1784 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1785
1786 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1787 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1788 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1789 }
1790
1791 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1792 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1793 setupDeviceOwner();
1794 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1795
1796 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1797 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1798 }
1799
1800 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1801 throws Exception {
1802 setupProfileOwner();
1803 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1804
1805 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1806 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1807 DevicePolicyManager.STATE_USER_UNMANAGED);
1808 }
1809
1810 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1811 throws Exception {
1812 setupProfileOwner();
1813 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1814
1815 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1816 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1817 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1818 }
1819
1820 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1821 setupProfileOwner();
1822 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1823
1824 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1825 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1826 }
1827
1828 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
1829 setupProfileOwner();
1830 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1831
1832 try {
1833 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1834 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1835 DevicePolicyManager.STATE_USER_UNMANAGED);
1836 fail("Expected IllegalStateException");
1837 } catch (IllegalStateException e) {
1838 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1839 e.getMessage());
1840 }
1841 }
1842
1843 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
1844 throws Exception {
1845 setupProfileOwner();
1846 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1847
1848 try {
1849 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1850 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1851 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
1852 fail("Expected IllegalStateException");
1853 } catch (IllegalStateException e) {
1854 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1855 e.getMessage());
1856 }
1857 }
1858
1859 private void exerciseUserProvisioningTransitions(int userId, int... states) {
1860 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1861 for (int state : states) {
1862 dpm.setUserProvisioningState(state, userId);
1863 assertEquals(state, dpm.getUserProvisioningState());
1864 }
1865 }
1866
1867 private void setupProfileOwner() throws Exception {
1868 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1869
1870 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1871 dpm.setActiveAdmin(admin1, false);
1872 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
1873
1874 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1875 }
1876
1877 private void setupDeviceOwner() throws Exception {
1878 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1879
1880 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1881 dpm.setActiveAdmin(admin1, false);
1882 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1883
1884 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1885 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001886
1887 public void testSetMaximumTimeToLock() {
1888 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1889
1890 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1891 dpm.setActiveAdmin(admin2, /* replace =*/ false);
1892
1893 reset(mMockContext.powerManagerInternal);
1894 reset(mMockContext.settings);
1895
1896 dpm.setMaximumTimeToLock(admin1, 0);
1897 verifyScreenTimeoutCall(null, false);
1898 reset(mMockContext.powerManagerInternal);
1899 reset(mMockContext.settings);
1900
1901 dpm.setMaximumTimeToLock(admin1, 1);
1902 verifyScreenTimeoutCall(1, true);
1903 reset(mMockContext.powerManagerInternal);
1904 reset(mMockContext.settings);
1905
1906 dpm.setMaximumTimeToLock(admin2, 10);
1907 verifyScreenTimeoutCall(null, false);
1908 reset(mMockContext.powerManagerInternal);
1909 reset(mMockContext.settings);
1910
1911 dpm.setMaximumTimeToLock(admin1, 5);
1912 verifyScreenTimeoutCall(5, true);
1913 reset(mMockContext.powerManagerInternal);
1914 reset(mMockContext.settings);
1915
1916 dpm.setMaximumTimeToLock(admin2, 4);
1917 verifyScreenTimeoutCall(4, true);
1918 reset(mMockContext.powerManagerInternal);
1919 reset(mMockContext.settings);
1920
1921 dpm.setMaximumTimeToLock(admin1, 0);
1922 reset(mMockContext.powerManagerInternal);
1923 reset(mMockContext.settings);
1924
1925 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
1926 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1927 reset(mMockContext.powerManagerInternal);
1928 reset(mMockContext.settings);
1929
1930 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
1931 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1932 reset(mMockContext.powerManagerInternal);
1933 reset(mMockContext.settings);
1934
1935 dpm.setMaximumTimeToLock(admin2, 10);
1936 verifyScreenTimeoutCall(10, true);
1937 reset(mMockContext.powerManagerInternal);
1938 reset(mMockContext.settings);
1939
1940 // There's no restriction; shold be set to MAX.
1941 dpm.setMaximumTimeToLock(admin2, 0);
1942 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
1943 }
1944
Michal Karpinski943aabd2016-10-06 11:09:25 +01001945 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
1946 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1947 setupDeviceOwner();
1948 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1949
1950 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
1951 final long ONE_MINUTE = 60 * 1000;
1952
1953 // aggregation should be the default if unset by any admin
1954 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1955 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1956
1957 // admin not participating by default
1958 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1959
1960 //clamping from the top
1961 dpm.setRequiredStrongAuthTimeout(admin1,
1962 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1963 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
1964 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1965 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1966 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1967
1968 // 0 means default
1969 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1970 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1971 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1972 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1973
1974 // clamping from the bottom
1975 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
1976 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1977 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1978
1979 // value within range
1980 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1981 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1982 + ONE_MINUTE);
1983 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1984 + ONE_MINUTE);
1985
1986 // reset to default
1987 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1988 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1989 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1990 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1991
1992 // negative value
1993 try {
1994 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
1995 fail("Didn't throw IllegalArgumentException");
1996 } catch (IllegalArgumentException iae) {
1997 }
1998 }
1999
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002000 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2001 boolean shouldStayOnWhilePluggedInBeCleared) {
2002 if (expectedTimeout == null) {
2003 verify(mMockContext.powerManagerInternal, times(0))
2004 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2005 } else {
2006 verify(mMockContext.powerManagerInternal, times(1))
2007 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2008 }
2009 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2010 // UnfinishedVerificationException.
2011 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002012
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002013 public void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002014 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2015 .thenReturn(false);
2016 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2017 .thenReturn(false);
2018 initializeDpms();
2019 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2020 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2021 .thenReturn(true);
2022 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2023
2024 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002025 }
Victor Chang3e794af2016-03-04 13:48:17 +00002026
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002027 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2028 setup_DeviceAdminFeatureOff();
Victor Chang3e794af2016-03-04 13:48:17 +00002029 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2030 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2031 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2032 false);
2033 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2034 }
2035
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002036 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2037 setup_DeviceAdminFeatureOff();
2038 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2039 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2040 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2041 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2042 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2043 assertCheckProvisioningPreCondition(
2044 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2045 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2046 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2047 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2048 }
2049
2050 public void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002051 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2052 .thenReturn(false);
2053 initializeDpms();
2054 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2055 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2056 .thenReturn(true);
2057 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2058
2059 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002060 }
Victor Chang3e794af2016-03-04 13:48:17 +00002061
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002062 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2063 setup_ManagedProfileFeatureOff();
Victor Chang3e794af2016-03-04 13:48:17 +00002064 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2065 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2066 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2067 false);
2068 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2069
2070 // Test again when split user is on
2071 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2072 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2073 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2074 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2075 true);
2076 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2077 }
2078
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002079 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2080 setup_ManagedProfileFeatureOff();
2081 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2082 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2083 DevicePolicyManager.CODE_OK);
2084 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2085 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2086 assertCheckProvisioningPreCondition(
2087 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2088 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2089 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2090 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2091
2092 // Test again when split user is on
2093 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2094 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2095 DevicePolicyManager.CODE_OK);
2096 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2097 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2098 assertCheckProvisioningPreCondition(
2099 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2100 DevicePolicyManager.CODE_OK);
2101 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2102 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2103 }
2104
2105 public void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002106 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2107 .thenReturn(true);
2108 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2109 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2110 .thenReturn(true);
2111 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2112
2113 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002114 }
Victor Chang3e794af2016-03-04 13:48:17 +00002115
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002116 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2117 setup_nonSplitUser_firstBoot_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002118 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2119 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2120 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2121 false /* because of non-split user */);
2122 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2123 false /* because of non-split user */);
2124 }
2125
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002126 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002127 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002128 setup_nonSplitUser_firstBoot_primaryUser();
2129 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2130 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2131 DevicePolicyManager.CODE_OK);
2132 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2133 DevicePolicyManager.CODE_OK);
2134 assertCheckProvisioningPreCondition(
2135 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2136 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2137 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2138 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2139 }
2140
2141 public void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002142 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2143 .thenReturn(true);
2144 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2145 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2146 .thenReturn(true);
2147 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2148
2149 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002150 }
Victor Chang3e794af2016-03-04 13:48:17 +00002151
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002152 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2153 throws Exception {
2154 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002155 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2156 false/* because of completed device setup */);
2157 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2158 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2159 false/* because of non-split user */);
2160 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2161 false/* because of non-split user */);
2162 }
2163
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002164 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2165 throws Exception {
2166 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2167 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2168 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2169 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2170 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2171 DevicePolicyManager.CODE_OK);
2172 assertCheckProvisioningPreCondition(
2173 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2174 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2175 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2176 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2177 }
2178
2179 public void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002180 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2181 .thenReturn(true);
2182 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2183 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2184 .thenReturn(false);
2185 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2186
2187 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002188 }
Victor Chang3e794af2016-03-04 13:48:17 +00002189
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002190 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2191 setup_splitUser_firstBoot_systemUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002192 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2193 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2194 false /* because canAddMoreManagedProfiles returns false */);
2195 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2196 true);
2197 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2198 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002199 }
2200
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002201 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2202 throws Exception {
2203 setup_splitUser_firstBoot_systemUser();
2204 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2205 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2206 DevicePolicyManager.CODE_OK);
2207 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002208 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002209 assertCheckProvisioningPreCondition(
2210 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2211 DevicePolicyManager.CODE_OK);
2212 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2213 DevicePolicyManager.CODE_SYSTEM_USER);
2214 }
2215
2216 public void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002217 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2218 .thenReturn(true);
2219 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2220 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2221 .thenReturn(false);
2222 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2223
2224 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002225 }
Victor Chang3e794af2016-03-04 13:48:17 +00002226
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002227 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2228 setup_splitUser_afterDeviceSetup_systemUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002229 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2230 true/* it's undefined behavior. Can be changed into false in the future */);
2231 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2232 false /* because canAddMoreManagedProfiles returns false */);
2233 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2234 true/* it's undefined behavior. Can be changed into false in the future */);
2235 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2236 false/* because calling uid is system user */);
2237 }
2238
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002239 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2240 throws Exception {
2241 setup_splitUser_afterDeviceSetup_systemUser();
2242 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2243 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2244 DevicePolicyManager.CODE_OK);
2245 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002246 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002247 assertCheckProvisioningPreCondition(
2248 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2249 DevicePolicyManager.CODE_OK);
2250 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2251 DevicePolicyManager.CODE_SYSTEM_USER);
2252 }
2253
2254 public void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002255 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2256 .thenReturn(true);
2257 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2258 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2259 true)).thenReturn(true);
2260 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2261
2262 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002263 }
Victor Chang3e794af2016-03-04 13:48:17 +00002264
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002265 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2266 setup_splitUser_firstBoot_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002267 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2268 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2269 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2270 true);
2271 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002272 }
2273
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002274 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002275 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002276 setup_splitUser_firstBoot_primaryUser();
2277 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2278 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2279 DevicePolicyManager.CODE_OK);
2280 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2281 DevicePolicyManager.CODE_OK);
2282 assertCheckProvisioningPreCondition(
2283 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2284 DevicePolicyManager.CODE_OK);
2285 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2286 DevicePolicyManager.CODE_OK);
2287 }
2288
2289 public void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002290 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2291 .thenReturn(true);
2292 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2293 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2294 true)).thenReturn(true);
2295 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2296
2297 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002298 }
Victor Chang3e794af2016-03-04 13:48:17 +00002299
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002300 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2301 throws Exception {
2302 setup_splitUser_afterDeviceSetup_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002303 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2304 true/* it's undefined behavior. Can be changed into false in the future */);
2305 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2306 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2307 true/* it's undefined behavior. Can be changed into false in the future */);
2308 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2309 false/* because user setup completed */);
2310 }
2311
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002312 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002313 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002314 setup_splitUser_afterDeviceSetup_primaryUser();
2315 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2316 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2317 DevicePolicyManager.CODE_OK);
2318 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2319 DevicePolicyManager.CODE_OK);
2320 assertCheckProvisioningPreCondition(
2321 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2322 DevicePolicyManager.CODE_OK);
2323 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2324 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2325 }
2326
2327 public void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002328 setDeviceOwner();
2329
2330 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2331 .thenReturn(true);
2332 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2333 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2334 .thenReturn(false);
2335 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2336
2337 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002338 }
Victor Chang3e794af2016-03-04 13:48:17 +00002339
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002340 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2341 throws Exception {
2342 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002343 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2344 false /* can't provision managed profile on system user */);
2345 }
2346
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002347 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002348 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002349 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2350 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2351 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2352 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2353 }
2354
2355 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002356 setDeviceOwner();
2357
2358 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2359 .thenReturn(true);
2360 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2361 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2362 true)).thenReturn(true);
2363 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2364
2365 mContext.binder.callingUid = DpmMockContext.CALLER_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_provisionManagedProfileWithDeviceOwner_primaryUser()
2369 throws Exception {
2370 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Victor Chang3e794af2016-03-04 13:48:17 +00002371 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2372 }
2373
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002374 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002375 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002376 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2377 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2378 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2379 DevicePolicyManager.CODE_OK);
2380 }
2381
2382 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002383 setDeviceOwner();
2384
2385 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2386 .thenReturn(true);
2387 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002388 when(mContext.userManager.hasUserRestriction(
2389 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
2390 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002391 .thenReturn(true);
2392 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002393 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002394 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2395 true)).thenReturn(true);
2396 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2397
2398 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002399 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002400
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002401 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2402 throws Exception {
2403 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Nicolas Prevot56400a42016-11-10 12:57:54 +00002404 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2405 }
2406
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002407 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2408 throws Exception {
2409 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2410 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2411 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2412 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2413 }
2414
2415 public void testCheckProvisioningPreCondition_permission() {
2416 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2417 try {
2418 dpm.checkProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE);
2419 fail("Didn't throw SecurityException");
2420 } catch (SecurityException expected) {
2421 }
2422 }
2423
Victor Chang3577ed22016-08-25 18:49:26 +01002424 public void testForceUpdateUserSetupComplete_permission() {
2425 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2426 try {
2427 dpm.forceUpdateUserSetupComplete();
2428 fail("Didn't throw SecurityException");
2429 } catch (SecurityException expected) {
2430 }
2431 }
2432
2433 public void testForceUpdateUserSetupComplete_systemUser() {
2434 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2435 // GIVEN calling from user 20
2436 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2437 try {
2438 dpm.forceUpdateUserSetupComplete();
2439 fail("Didn't throw SecurityException");
2440 } catch (SecurityException expected) {
2441 }
2442 }
2443
2444 public void testForceUpdateUserSetupComplete_userbuild() {
2445 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2446 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2447
2448 final int userId = UserHandle.USER_SYSTEM;
2449 // GIVEN userComplete is false in SettingsProvider
2450 setUserSetupCompleteForUser(false, userId);
2451
2452 // GIVEN userComplete is true in DPM
2453 DevicePolicyManagerService.DevicePolicyData userData =
2454 new DevicePolicyManagerService.DevicePolicyData(userId);
2455 userData.mUserSetupComplete = true;
2456 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2457
2458 // GIVEN it's user build
2459 mContext.buildMock.isDebuggable = false;
2460
2461 assertTrue(dpms.hasUserSetupCompleted());
2462
2463 dpm.forceUpdateUserSetupComplete();
2464
2465 // THEN the state in dpms is not changed
2466 assertTrue(dpms.hasUserSetupCompleted());
2467 }
2468
2469 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2470 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2471 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2472
2473 final int userId = UserHandle.USER_SYSTEM;
2474 // GIVEN userComplete is false in SettingsProvider
2475 setUserSetupCompleteForUser(false, userId);
2476
2477 // GIVEN userComplete is true in DPM
2478 DevicePolicyManagerService.DevicePolicyData userData =
2479 new DevicePolicyManagerService.DevicePolicyData(userId);
2480 userData.mUserSetupComplete = true;
2481 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2482
2483 // GIVEN it's userdebug build
2484 mContext.buildMock.isDebuggable = true;
2485
2486 assertTrue(dpms.hasUserSetupCompleted());
2487
2488 dpm.forceUpdateUserSetupComplete();
2489
2490 // THEN the state in dpms is not changed
2491 assertFalse(dpms.hasUserSetupCompleted());
2492 }
2493
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002494 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002495 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002496 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2497 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2498 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2499 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002500 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002501 }
2502
2503 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2504 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2505 setupDeviceOwner();
2506 when(mContext.userManager.getUserCount()).thenReturn(1);
2507 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2508 .thenReturn(true);
2509
2510 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002511 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002512
2513 // Enabling logging should not change the timestamp.
2514 dpm.setSecurityLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002515 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002516
2517 // Retrieving the logs should update the timestamp.
2518 final long beforeRetrieval = System.currentTimeMillis();
2519 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002520 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002521 final long afterRetrieval = System.currentTimeMillis();
2522 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2523 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2524
2525 // Retrieving the pre-boot logs should update the timestamp.
2526 Thread.sleep(2);
2527 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002528 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002529 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2530
2531 // Checking the timestamp again should not change it.
2532 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002533 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002534
2535 // Retrieving the logs again should update the timestamp.
2536 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002537 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002538 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2539
2540 // Disabling logging should not change the timestamp.
2541 Thread.sleep(2);
2542 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002543 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002544
2545 // Restarting the DPMS should not lose the timestamp.
2546 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002547 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002548
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002549 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2550 mContext.binder.callingUid = 1234567;
2551 mContext.callerPermissions.add(permission.MANAGE_USERS);
2552 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2553 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2554
2555 // System can retrieve the timestamp.
2556 mContext.binder.clearCallingIdentity();
2557 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2558
2559 // Removing the device owner should clear the timestamp.
2560 clearDeviceOwner();
2561 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002562 }
2563
2564 public void testGetLastBugReportRequestTime() throws Exception {
2565 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2566 setupDeviceOwner();
2567 when(mContext.userManager.getUserCount()).thenReturn(1);
2568 mContext.packageName = admin1.getPackageName();
2569 mContext.applicationInfo = new ApplicationInfo();
2570 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2571 .thenReturn(Color.WHITE);
2572 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2573 anyObject())).thenReturn(Color.WHITE);
2574
2575 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002576 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002577
2578 // Requesting a bug report should update the timestamp.
2579 final long beforeRequest = System.currentTimeMillis();
2580 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002581 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002582 final long afterRequest = System.currentTimeMillis();
2583 assertTrue(bugReportRequestTime >= beforeRequest);
2584 assertTrue(bugReportRequestTime <= afterRequest);
2585
2586 // Checking the timestamp again should not change it.
2587 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002588 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002589
2590 // Restarting the DPMS should not lose the timestamp.
2591 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002592 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002593
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002594 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2595 mContext.binder.callingUid = 1234567;
2596 mContext.callerPermissions.add(permission.MANAGE_USERS);
2597 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2598 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2599
2600 // System can retrieve the timestamp.
2601 mContext.binder.clearCallingIdentity();
2602 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2603
2604 // Removing the device owner should clear the timestamp.
2605 clearDeviceOwner();
2606 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002607 }
2608
2609 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2610 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2611 setupDeviceOwner();
2612 when(mContext.userManager.getUserCount()).thenReturn(1);
2613 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2614 .thenReturn(true);
2615
2616 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002617 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002618
2619 // Attempting to retrieve logs without enabling logging should not change the timestamp.
2620 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002621 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002622
2623 // Enabling logging should not change the timestamp.
2624 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002625 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002626
2627 // Retrieving the logs should update the timestamp.
2628 final long beforeRetrieval = System.currentTimeMillis();
2629 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002630 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002631 final long afterRetrieval = System.currentTimeMillis();
2632 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
2633 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
2634
2635 // Checking the timestamp again should not change it.
2636 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002637 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002638
2639 // Retrieving the logs again should update the timestamp.
2640 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002641 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002642 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
2643
2644 // Disabling logging should not change the timestamp.
2645 Thread.sleep(2);
2646 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002647 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002648
2649 // Restarting the DPMS should not lose the timestamp.
2650 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002651 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2652
2653 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2654 mContext.binder.callingUid = 1234567;
2655 mContext.callerPermissions.add(permission.MANAGE_USERS);
2656 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2657 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2658
2659 // System can retrieve the timestamp.
2660 mContext.binder.clearCallingIdentity();
2661 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2662
2663 // Removing the device owner should clear the timestamp.
2664 clearDeviceOwner();
2665 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002666 }
2667
Tony Mak2f26b792016-11-28 17:54:51 +00002668 public void testGetBindDeviceAdminTargetUsers() throws Exception {
2669 // Setup device owner.
2670 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2671 setupDeviceOwner();
2672
2673 // Only device owner is setup, the result list should be empty.
2674 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2675 MoreAsserts.assertEmpty(targetUsers);
2676
2677 // Setup a managed profile managed by the same admin.
2678 final int MANAGED_PROFILE_USER_ID = 15;
2679 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2680 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2681
2682 // Add a secondary user, it should never talk with.
2683 final int ANOTHER_USER_ID = 36;
2684 mContext.addUser(ANOTHER_USER_ID, 0);
2685
2686 // Calling from device owner admin, the result list should just contain the managed
2687 // profile user id.
2688 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2689 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
2690
2691 // Calling from managed profile admin, the result list should just contain the system
2692 // user id.
2693 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2694 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2695 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
2696 }
2697
2698 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
2699 // Setup a device owner.
2700 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2701 setupDeviceOwner();
2702
2703 // Set up a managed profile managed by different package.
2704 final int MANAGED_PROFILE_USER_ID = 15;
2705 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2706 final ComponentName adminDifferentPackage =
2707 new ComponentName("another.package", "whatever.class");
2708 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
2709
2710 // Calling from device owner admin, we should get zero bind device admin target users as
2711 // their packages are different.
2712 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2713 MoreAsserts.assertEmpty(targetUsers);
2714
2715 // Calling from managed profile admin, we should still get zero target users for the same
2716 // reason.
2717 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2718 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
2719 MoreAsserts.assertEmpty(targetUsers);
2720 }
2721
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01002722 public void testIsDeviceManaged() throws Exception {
2723 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2724 setupDeviceOwner();
2725
2726 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
2727 // find out that the device has a device owner.
2728 assertTrue(dpm.isDeviceManaged());
2729 mContext.binder.callingUid = 1234567;
2730 mContext.callerPermissions.add(permission.MANAGE_USERS);
2731 assertTrue(dpm.isDeviceManaged());
2732 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2733 mContext.binder.clearCallingIdentity();
2734 assertTrue(dpm.isDeviceManaged());
2735
2736 clearDeviceOwner();
2737
2738 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
2739 // not have a device owner.
2740 mContext.binder.callingUid = 1234567;
2741 mContext.callerPermissions.add(permission.MANAGE_USERS);
2742 assertFalse(dpm.isDeviceManaged());
2743 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2744 mContext.binder.clearCallingIdentity();
2745 assertFalse(dpm.isDeviceManaged());
2746 }
2747
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01002748 public void testDeviceOwnerOrganizationName() throws Exception {
2749 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2750 setupDeviceOwner();
2751
2752 dpm.setOrganizationName(admin1, "organization");
2753
2754 // Device owner can retrieve organization managing the device.
2755 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2756
2757 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
2758 mContext.binder.callingUid = 1234567;
2759 mContext.callerPermissions.add(permission.MANAGE_USERS);
2760 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2761 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2762
2763 // System can retrieve organization managing the device.
2764 mContext.binder.clearCallingIdentity();
2765 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2766
2767 // Removing the device owner clears the organization managing the device.
2768 clearDeviceOwner();
2769 assertNull(dpm.getDeviceOwnerOrganizationName());
2770 }
2771
Victor Chang3e794af2016-03-04 13:48:17 +00002772 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
2773 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
2774 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
2775 dpms.notifyChangeToContentObserver(
2776 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
2777 }
2778
2779 private void assertProvisioningAllowed(String action, boolean expected) {
2780 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
2781 dpm.isProvisioningAllowed(action));
2782 }
Tony Mak2f26b792016-11-28 17:54:51 +00002783
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002784 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
2785 assertEquals("checkProvisioningPreCondition(" + action + ") returning unexpected result",
2786 provisioningCondition, dpm.checkProvisioningPreCondition(action));
2787 }
2788
Tony Mak2f26b792016-11-28 17:54:51 +00002789 /**
2790 * Setup a managed profile with the specified admin and its uid.
2791 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
2792 * @param adminUid uid of the admin package.
2793 * @param copyFromAdmin package information for {@code admin} will be built based on this
2794 * component's information.
2795 */
2796 private void addManagedProfile(
2797 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
2798 final int userId = UserHandle.getUserId(adminUid);
2799 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
2800 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2801 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
2802 dpm.setActiveAdmin(admin, false, userId);
2803 assertTrue(dpm.setProfileOwner(admin, null, userId));
2804 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2805 }
Victor Chang3e794af2016-03-04 13:48:17 +00002806}