blob: 23a1bb4462f408f6d13c039470dd206f34322ac2 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov6a40f092016-10-25 15:46:51 +010018import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
19import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
20import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
21
Makoto Onukif76b06a2015-09-22 15:03:44 -070022import android.Manifest.permission;
23import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000024import android.app.Notification;
25import android.app.NotificationManager;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070026import android.app.admin.DeviceAdminReceiver;
27import android.app.admin.DevicePolicyManager;
28import android.app.admin.DevicePolicyManagerInternal;
Makoto Onukif76b06a2015-09-22 15:03:44 -070029import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070030import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000031import android.content.Context;
32import android.content.Intent;
33import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000034import android.content.pm.ApplicationInfo;
35import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070036import android.content.pm.PackageManager;
Robin Lee7f5c91c2017-02-08 21:27:02 +000037import android.content.pm.ParceledListSlice;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010038import android.content.res.Resources;
39import android.graphics.Color;
40import android.net.IIpConnectivityMetrics;
Tony Mak2f26b792016-11-28 17:54:51 +000041import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080042import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080043import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070044import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000045import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080046import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070047import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070048import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010049import android.os.UserManagerInternal;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080050import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000051import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080052import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000053import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010054import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070055import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070056
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010057import com.android.internal.R;
Robin Lee7f5c91c2017-02-08 21:27:02 +000058import com.android.internal.util.ParcelableString;
Rubin Xuaab7a412016-12-30 21:13:29 +000059import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000060import com.android.server.LocalServices;
61import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000062import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000063
Robin Lee7f5c91c2017-02-08 21:27:02 +000064import org.hamcrest.BaseMatcher;
65import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070066import org.mockito.invocation.InvocationOnMock;
67import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070068
Makoto Onukic8a5a552015-11-19 14:29:12 -080069import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000070import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000071import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070072import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070073import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070074import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010075import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000076import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070077
Edman Anjosf9946772016-11-28 16:35:15 +010078import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
79import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
80
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070081import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070082import static org.mockito.Matchers.anyInt;
Michal Karpinskid084ca52017-01-18 15:54:18 +000083import static org.mockito.Matchers.anyLong;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010084import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070085import static org.mockito.Matchers.anyString;
Robin Lee7f5c91c2017-02-08 21:27:02 +000086import static org.mockito.Matchers.argThat;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070087import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070088import static org.mockito.Matchers.isNull;
Esteban Talavera548a04b2016-12-20 15:22:30 +000089import static org.mockito.Mockito.atLeast;
Makoto Onukib643fb02015-09-22 15:03:44 -070090import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070091import static org.mockito.Mockito.doReturn;
Robin Lee7f5c91c2017-02-08 21:27:02 +000092import static org.mockito.Mockito.mock;
Robin Leed2a73ed2016-12-19 09:07:16 +000093import static org.mockito.Mockito.never;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080094import static org.mockito.Mockito.reset;
Robin Lee7f5c91c2017-02-08 21:27:02 +000095import static org.mockito.Mockito.timeout;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070096import static org.mockito.Mockito.times;
97import static org.mockito.Mockito.verify;
Esteban Talaverab88f42b2017-01-24 16:47:16 +000098import static org.mockito.Mockito.verifyZeroInteractions;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070099import static org.mockito.Mockito.when;
100
101/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700102 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000103 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700104 m FrameworksServicesTests &&
105 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000106 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800108 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700109
110 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000111 *
112 * , or:
113 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700114 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000115@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000117 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
118 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
119 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
120
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 private DpmMockContext mContext;
122 public DevicePolicyManager dpm;
123 public DevicePolicyManagerServiceTestable dpms;
124
125 @Override
126 protected void setUp() throws Exception {
127 super.setUp();
128
129 mContext = getContext();
130
131 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
132 .thenReturn(true);
133
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800134 // By default, pretend all users are running and unlocked.
135 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
136
Makoto Onukia52562c2015-10-01 16:12:31 -0700137 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700138
Makoto Onukid932f762015-09-29 16:53:38 -0700139 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
140 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
141 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800142 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700143
Makoto Onukib643fb02015-09-22 15:03:44 -0700144 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700145 }
146
Makoto Onukia52562c2015-10-01 16:12:31 -0700147 private void initializeDpms() {
148 // Need clearCallingIdentity() to pass permission checks.
149 final long ident = mContext.binder.clearCallingIdentity();
150 try {
151 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
152
153 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
154
155 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
156 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
157
158 dpm = new DevicePolicyManagerTestable(mContext, dpms);
159 } finally {
160 mContext.binder.restoreCallingIdentity(ident);
161 }
162 }
163
Makoto Onukib643fb02015-09-22 15:03:44 -0700164 private void setUpUserManager() {
165 // Emulate UserManager.set/getApplicationRestriction().
166 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
167
168 // UM.setApplicationRestrictions() will save to appRestrictions.
169 doAnswer(new Answer<Void>() {
170 @Override
171 public Void answer(InvocationOnMock invocation) throws Throwable {
172 String pkg = (String) invocation.getArguments()[0];
173 Bundle bundle = (Bundle) invocation.getArguments()[1];
174 UserHandle user = (UserHandle) invocation.getArguments()[2];
175
176 appRestrictions.put(Pair.create(pkg, user), bundle);
177
178 return null;
179 }
180 }).when(mContext.userManager).setApplicationRestrictions(
181 anyString(), any(Bundle.class), any(UserHandle.class));
182
183 // UM.getApplicationRestrictions() will read from appRestrictions.
184 doAnswer(new Answer<Bundle>() {
185 @Override
186 public Bundle answer(InvocationOnMock invocation) throws Throwable {
187 String pkg = (String) invocation.getArguments()[0];
188 UserHandle user = (UserHandle) invocation.getArguments()[1];
189
190 return appRestrictions.get(Pair.create(pkg, user));
191 }
192 }).when(mContext.userManager).getApplicationRestrictions(
193 anyString(), any(UserHandle.class));
194
Makoto Onukid932f762015-09-29 16:53:38 -0700195 // Add the first secondary user.
196 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700197 }
198
199 private void setAsProfileOwner(ComponentName admin) {
200 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
201 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
202
Makoto Onukia4f11972015-10-01 13:19:58 -0700203 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700204 dpm.setActiveAdmin(admin, /* replace =*/ false);
205
206 // Fire!
207 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
208
209 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700210 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700211 }
212
213 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700214 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
215 .thenReturn(false);
216
217 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
218 new DevicePolicyManagerServiceTestable(mContext, dataDir);
219
220 // If the device has no DPMS feature, it shouldn't register the local service.
221 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
222 }
223
224 /**
225 * Caller doesn't have proper permissions.
226 */
227 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700228 // 1. Failure cases.
229
230 // Caller doesn't have MANAGE_DEVICE_ADMINS.
231 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700232 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700233 fail("Didn't throw SecurityException");
234 } catch (SecurityException expected) {
235 }
236
237 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
238 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
239 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700240 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700241 fail("Didn't throw SecurityException");
242 } catch (SecurityException expected) {
243 }
244 }
245
Makoto Onukif76b06a2015-09-22 15:03:44 -0700246 /**
247 * Test for:
248 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800249 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700250 * {@link DevicePolicyManager#isAdminActive}
251 * {@link DevicePolicyManager#isAdminActiveAsUser}
252 * {@link DevicePolicyManager#getActiveAdmins}
253 * {@link DevicePolicyManager#getActiveAdminsAsUser}
254 */
255 public void testSetActiveAdmin() throws Exception {
256 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700257 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
258
Makoto Onukif76b06a2015-09-22 15:03:44 -0700259 // 2. Call the API.
260 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700261
262 // 3. Verify internal calls.
263
264 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700265 verify(mContext.spiedContext).sendBroadcastAsUser(
266 MockUtils.checkIntentAction(
267 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
268 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
269 verify(mContext.spiedContext).sendBroadcastAsUser(
270 MockUtils.checkIntentAction(
271 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700272 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
273
Makoto Onukif76b06a2015-09-22 15:03:44 -0700274 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
275 eq(admin1.getPackageName()),
276 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
277 eq(PackageManager.DONT_KILL_APP),
278 eq(DpmMockContext.CALLER_USER_HANDLE),
279 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700280
281 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700282
283 // Make sure it's active admin1.
284 assertTrue(dpm.isAdminActive(admin1));
285 assertFalse(dpm.isAdminActive(admin2));
286 assertFalse(dpm.isAdminActive(admin3));
287
288 // But not admin1 for a different user.
289
290 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
291 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
292 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
293
294 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
295 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
296
297 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
298
299 // Next, add one more admin.
300 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700301 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
302 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700303
304 dpm.setActiveAdmin(admin2, /* replace =*/ false);
305
306 // Now we have two admins.
307 assertTrue(dpm.isAdminActive(admin1));
308 assertTrue(dpm.isAdminActive(admin2));
309 assertFalse(dpm.isAdminActive(admin3));
310
311 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
312 // again. (times(1) because it was previously called for admin1)
313 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
314 eq(admin1.getPackageName()),
315 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
316 eq(PackageManager.DONT_KILL_APP),
317 eq(DpmMockContext.CALLER_USER_HANDLE),
318 anyString());
319
320 // 4. Add the same admin1 again without replace, which should throw.
321 try {
322 dpm.setActiveAdmin(admin1, /* replace =*/ false);
323 fail("Didn't throw");
324 } catch (IllegalArgumentException expected) {
325 }
326
327 // 5. Add the same admin1 again with replace, which should succeed.
328 dpm.setActiveAdmin(admin1, /* replace =*/ true);
329
330 // TODO make sure it's replaced.
331
332 // 6. Test getActiveAdmins()
333 List<ComponentName> admins = dpm.getActiveAdmins();
334 assertEquals(2, admins.size());
335 assertEquals(admin1, admins.get(0));
336 assertEquals(admin2, admins.get(1));
337
338 // Another user has no admins.
339 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
340
341 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
342 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
343
344 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
345 }
346
Makoto Onukid932f762015-09-29 16:53:38 -0700347 public void testSetActiveAdmin_multiUsers() throws Exception {
348
349 final int ANOTHER_USER_ID = 100;
350 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
351
352 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
353
354 // Set up pacakge manager for the other user.
355 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700356
357 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
358
359 dpm.setActiveAdmin(admin1, /* replace =*/ false);
360
361 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
362 dpm.setActiveAdmin(admin2, /* replace =*/ false);
363
364
365 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
366 assertTrue(dpm.isAdminActive(admin1));
367 assertFalse(dpm.isAdminActive(admin2));
368
369 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
370 assertFalse(dpm.isAdminActive(admin1));
371 assertTrue(dpm.isAdminActive(admin2));
372 }
373
Makoto Onukif76b06a2015-09-22 15:03:44 -0700374 /**
375 * Test for:
376 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800377 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700378 */
379 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
380 // 1. Make sure the caller has proper permissions.
381 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
382
383 dpm.setActiveAdmin(admin1, /* replace =*/ false);
384 assertTrue(dpm.isAdminActive(admin1));
385
386 // Add the same admin1 again without replace, which should throw.
387 try {
388 dpm.setActiveAdmin(admin1, /* replace =*/ false);
389 fail("Didn't throw");
390 } catch (IllegalArgumentException expected) {
391 }
392 }
393
394 /**
395 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800396 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
397 * BIND_DEVICE_ADMIN.
398 */
399 public void testSetActiveAdmin_permissionCheck() throws Exception {
400 // 1. Make sure the caller has proper permissions.
401 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
402
403 try {
404 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
405 fail();
406 } catch (IllegalArgumentException expected) {
407 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
408 }
409 assertFalse(dpm.isAdminActive(adminNoPerm));
410
411 // Change the target API level to MNC. Now it can be set as DA.
412 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
413 VERSION_CODES.M);
414 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
415 assertTrue(dpm.isAdminActive(adminNoPerm));
416
417 // TODO Test the "load from the file" case where DA will still be loaded even without
418 // BIND_DEVICE_ADMIN and target API is N.
419 }
420
421 /**
422 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700423 * {@link DevicePolicyManager#removeActiveAdmin}
424 */
425 public void testRemoveActiveAdmin_SecurityException() {
426 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
427
428 // Add admin.
429
430 dpm.setActiveAdmin(admin1, /* replace =*/ false);
431
432 assertTrue(dpm.isAdminActive(admin1));
433
434 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
435
436 // Directly call the DPMS method with a different userid, which should fail.
437 try {
438 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
439 fail("Didn't throw SecurityException");
440 } catch (SecurityException expected) {
441 }
442
443 // Try to remove active admin with a different caller userid should fail too, without
444 // having MANAGE_DEVICE_ADMINS.
445 mContext.callerPermissions.clear();
446
Makoto Onukid932f762015-09-29 16:53:38 -0700447 // Change the caller, and call into DPMS directly with a different user-id.
448
Makoto Onukif76b06a2015-09-22 15:03:44 -0700449 mContext.binder.callingUid = 1234567;
450 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700451 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700452 fail("Didn't throw SecurityException");
453 } catch (SecurityException expected) {
454 }
455 }
456
457 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800458 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
459 * (because we can't send the remove broadcast).
460 */
461 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
462 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
463
464 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
465
466 // Add admin.
467
468 dpm.setActiveAdmin(admin1, /* replace =*/ false);
469
470 assertTrue(dpm.isAdminActive(admin1));
471
472 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
473
474 // 1. User not unlocked.
475 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
476 .thenReturn(false);
477 try {
478 dpm.removeActiveAdmin(admin1);
479 fail("Didn't throw IllegalStateException");
480 } catch (IllegalStateException expected) {
481 MoreAsserts.assertContainsRegex(
482 "User must be running and unlocked", expected.getMessage());
483 }
484
485 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
486
487 // 2. User unlocked.
488 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
489 .thenReturn(true);
490
491 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700492 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800493 }
494
495 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700496 * Test for:
497 * {@link DevicePolicyManager#removeActiveAdmin}
498 */
Makoto Onukid932f762015-09-29 16:53:38 -0700499 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700500 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
501
502 // Add admin1.
503
504 dpm.setActiveAdmin(admin1, /* replace =*/ false);
505
506 assertTrue(dpm.isAdminActive(admin1));
507 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
508
509 // Different user, but should work, because caller has proper permissions.
510 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700511
512 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700513 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700514
515 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700516 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700517
518 // TODO DO Still can't be removed in this case.
519 }
520
521 /**
522 * Test for:
523 * {@link DevicePolicyManager#removeActiveAdmin}
524 */
525 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
526 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
527 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
528
529 // Add admin1.
530
531 dpm.setActiveAdmin(admin1, /* replace =*/ false);
532
533 assertTrue(dpm.isAdminActive(admin1));
534 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
535
536 // Broadcast from saveSettingsLocked().
537 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
538 MockUtils.checkIntentAction(
539 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
540 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
541
542 // Remove. No permissions, but same user, so it'll work.
543 mContext.callerPermissions.clear();
544 dpm.removeActiveAdmin(admin1);
545
Makoto Onukif76b06a2015-09-22 15:03:44 -0700546 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
547 MockUtils.checkIntentAction(
548 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
549 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
550 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700551 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700552 eq(dpms.mHandler),
553 eq(Activity.RESULT_OK),
554 isNull(String.class),
555 isNull(Bundle.class));
556
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700557 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700558
559 // Again broadcast from saveSettingsLocked().
560 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
561 MockUtils.checkIntentAction(
562 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
563 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
564
565 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700566 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700567
568 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000569 * Test for: @{link DevicePolicyManager#setActivePasswordState}
570 *
571 * Validates that when the password for a user changes, the notification broadcast intent
572 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
573 * addition to ones in the original user.
574 */
575 public void testSetActivePasswordState_sendToProfiles() throws Exception {
576 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
577
578 final int MANAGED_PROFILE_USER_ID = 78;
579 final int MANAGED_PROFILE_ADMIN_UID =
580 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
581
582 // Setup device owner.
583 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
584 mContext.packageName = admin1.getPackageName();
585 setupDeviceOwner();
586
587 // Add a managed profile belonging to the system user.
588 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
589
590 // Change the parent user's password.
591 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
592
593 // Both the device owner and the managed profile owner should receive this broadcast.
594 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
595 intent.setComponent(admin1);
596 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
597
598 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
599 MockUtils.checkIntent(intent),
600 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
601 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
602 MockUtils.checkIntent(intent),
603 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
604 }
605
606 /**
607 * Test for: @{link DevicePolicyManager#setActivePasswordState}
608 *
609 * Validates that when the password for a managed profile changes, the notification broadcast
610 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
611 * its parent.
612 */
613 public void testSetActivePasswordState_notSentToParent() throws Exception {
614 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
615
616 final int MANAGED_PROFILE_USER_ID = 78;
617 final int MANAGED_PROFILE_ADMIN_UID =
618 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
619
620 // Setup device owner.
621 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
622 mContext.packageName = admin1.getPackageName();
623 doReturn(true).when(mContext.lockPatternUtils)
624 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
625 setupDeviceOwner();
626
627 // Add a managed profile belonging to the system user.
628 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
629
630 // Change the profile's password.
631 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
632
633 // Both the device owner and the managed profile owner should receive this broadcast.
634 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
635 intent.setComponent(admin1);
636 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
637
638 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
639 MockUtils.checkIntent(intent),
640 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
641 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
642 MockUtils.checkIntent(intent),
643 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
644 }
645 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000646 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700647 */
648 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000649 setDeviceOwner();
650
651 // Try to set a profile owner on the same user, which should fail.
652 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
653 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
654 try {
655 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
656 fail("IllegalStateException not thrown");
657 } catch (IllegalStateException expected) {
658 assertTrue("Message was: " + expected.getMessage(),
659 expected.getMessage().contains("already has a device owner"));
660 }
661
662 // DO admin can't be deactivated.
663 dpm.removeActiveAdmin(admin1);
664 assertTrue(dpm.isAdminActive(admin1));
665
666 // TODO Test getDeviceOwnerName() too. To do so, we need to change
667 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
668 }
669
670 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700671 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800672 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700673 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
674 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
675
Makoto Onukid932f762015-09-29 16:53:38 -0700676 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700677 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
678
Makoto Onukid932f762015-09-29 16:53:38 -0700679 // Make sure admin1 is installed on system user.
680 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700681
Makoto Onukic8a5a552015-11-19 14:29:12 -0800682 // Check various get APIs.
683 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
684
Makoto Onukib643fb02015-09-22 15:03:44 -0700685 // DO needs to be an DA.
686 dpm.setActiveAdmin(admin1, /* replace =*/ false);
687
688 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700689 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700690
Makoto Onukic8a5a552015-11-19 14:29:12 -0800691 // getDeviceOwnerComponent should return the admin1 component.
692 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
693 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
694
695 // Check various get APIs.
696 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
697
698 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
699 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
700 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
701 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
702
703 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
704
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000705 // Verify internal calls.
706 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
707 eq(admin1.getPackageName()));
708
Makoto Onukib643fb02015-09-22 15:03:44 -0700709 // TODO We should check if the caller has called clearCallerIdentity().
710 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
711 eq(UserHandle.USER_SYSTEM), eq(false));
712
713 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
714 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
715 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
716
Makoto Onukic8a5a552015-11-19 14:29:12 -0800717 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700718 }
719
Makoto Onukic8a5a552015-11-19 14:29:12 -0800720 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
721 final int origCallingUser = mContext.binder.callingUid;
722 final List origPermissions = new ArrayList(mContext.callerPermissions);
723 mContext.callerPermissions.clear();
724
725 mContext.callerPermissions.add(permission.MANAGE_USERS);
726
727 mContext.binder.callingUid = Process.SYSTEM_UID;
728
729 // TODO Test getDeviceOwnerName() too. To do so, we need to change
730 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
731 if (hasDeviceOwner) {
732 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
733 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
734 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
735
736 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
737 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
738 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
739 } else {
740 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
741 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
742 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
743
744 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
745 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
746 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
747 }
748
749 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
750 if (hasDeviceOwner) {
751 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
752 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
753 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
754
755 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
756 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
757 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
758 } else {
759 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
760 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
761 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
762
763 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
764 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
765 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
766 }
767
768 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
769 // Still with MANAGE_USERS.
770 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
771 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
772 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
773
774 if (hasDeviceOwner) {
775 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
776 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
777 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
778 } else {
779 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
780 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
781 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
782 }
783
784 mContext.binder.callingUid = Process.SYSTEM_UID;
785 mContext.callerPermissions.remove(permission.MANAGE_USERS);
786 // System can still call "OnAnyUser" without MANAGE_USERS.
787 if (hasDeviceOwner) {
788 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
789 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
790 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
791
792 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
793 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
794 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
795 } else {
796 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
797 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
798 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
799
800 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
801 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
802 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
803 }
804
805 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
806 // Still no MANAGE_USERS.
807 if (hasDeviceOwner) {
808 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
809 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
810 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
811 } else {
812 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
813 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
814 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
815 }
816
817 try {
818 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
819 fail();
820 } catch (SecurityException expected) {
821 }
822 try {
823 dpm.getDeviceOwnerComponentOnAnyUser();
824 fail();
825 } catch (SecurityException expected) {
826 }
827 try {
828 dpm.getDeviceOwnerUserId();
829 fail();
830 } catch (SecurityException expected) {
831 }
832 try {
833 dpm.getDeviceOwnerNameOnAnyUser();
834 fail();
835 } catch (SecurityException expected) {
836 }
837
838 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
839 // Still no MANAGE_USERS.
840 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
841 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
842 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
843
844 try {
845 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
846 fail();
847 } catch (SecurityException expected) {
848 }
849 try {
850 dpm.getDeviceOwnerComponentOnAnyUser();
851 fail();
852 } catch (SecurityException expected) {
853 }
854 try {
855 dpm.getDeviceOwnerUserId();
856 fail();
857 } catch (SecurityException expected) {
858 }
859 try {
860 dpm.getDeviceOwnerNameOnAnyUser();
861 fail();
862 } catch (SecurityException expected) {
863 }
864
865 // Restore.
866 mContext.binder.callingUid = origCallingUser;
867 mContext.callerPermissions.addAll(origPermissions);
868 }
869
870
Makoto Onukib643fb02015-09-22 15:03:44 -0700871 /**
872 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
873 */
874 public void testSetDeviceOwner_noSuchPackage() {
875 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800876 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700877 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
878 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
879
880 // Call from a process on the system user.
881 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
882
Makoto Onukib643fb02015-09-22 15:03:44 -0700883 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700884 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700885 fail("Didn't throw IllegalArgumentException");
886 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700887 assertTrue("Message was: " + expected.getMessage(),
888 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700889 }
890 }
891
892 public void testSetDeviceOwner_failures() throws Exception {
893 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
894 }
895
Makoto Onukia52562c2015-10-01 16:12:31 -0700896 public void testClearDeviceOwner() throws Exception {
897 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800898 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700899 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
900 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
901
902 // Set admin1 as a DA to the secondary user.
903 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
904
905 dpm.setActiveAdmin(admin1, /* replace =*/ false);
906
907 // Set admin 1 as the DO to the system user.
908
909 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
910 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
911 dpm.setActiveAdmin(admin1, /* replace =*/ false);
912 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
913
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000914 // Verify internal calls.
915 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
916 eq(admin1.getPackageName()));
917
Makoto Onukic8a5a552015-11-19 14:29:12 -0800918 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700919
Makoto Onuki90b89652016-01-28 14:44:18 -0800920 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
921
922 assertTrue(dpm.isAdminActive(admin1));
923 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
924
Makoto Onukia52562c2015-10-01 16:12:31 -0700925 // Set up other mocks.
926 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
927
928 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700929 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700930 eq(admin1.getPackageName()),
931 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800932
933 // But first pretend the user is locked. Then it should fail.
934 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
935 try {
936 dpm.clearDeviceOwnerApp(admin1.getPackageName());
937 fail("Didn't throw IllegalStateException");
938 } catch (IllegalStateException expected) {
939 MoreAsserts.assertContainsRegex(
940 "User must be running and unlocked", expected.getMessage());
941 }
942
943 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800944 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700945 dpm.clearDeviceOwnerApp(admin1.getPackageName());
946
947 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800948 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700949
Makoto Onuki90b89652016-01-28 14:44:18 -0800950 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
951 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100952 eq(null),
953 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800954
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700955 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100956
957 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
958 // and once for clearing it.
959 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
960 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
961 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700962 // TODO Check other calls.
963 }
964
965 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
966 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800967 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700968 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
969 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
970
971 // Set admin1 as a DA to the secondary user.
972 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
973
974 dpm.setActiveAdmin(admin1, /* replace =*/ false);
975
976 // Set admin 1 as the DO to the system user.
977
978 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
979 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
980 dpm.setActiveAdmin(admin1, /* replace =*/ false);
981 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
982
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000983 // Verify internal calls.
984 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
985 eq(admin1.getPackageName()));
986
Makoto Onukic8a5a552015-11-19 14:29:12 -0800987 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700988
989 // Now call clear from the secondary user, which should throw.
990 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
991
992 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700993 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700994 eq(admin1.getPackageName()),
995 anyInt());
996 try {
997 dpm.clearDeviceOwnerApp(admin1.getPackageName());
998 fail("Didn't throw");
999 } catch (SecurityException e) {
1000 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
1001 }
1002
Makoto Onukic8a5a552015-11-19 14:29:12 -08001003 // DO shouldn't be removed.
1004 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001005 }
1006
Makoto Onukib643fb02015-09-22 15:03:44 -07001007 public void testSetProfileOwner() throws Exception {
1008 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001009
Makoto Onuki90b89652016-01-28 14:44:18 -08001010 // PO admin can't be deactivated.
1011 dpm.removeActiveAdmin(admin1);
1012 assertTrue(dpm.isAdminActive(admin1));
1013
Makoto Onuki803d6752015-10-30 12:58:39 -07001014 // Try setting DO on the same user, which should fail.
1015 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1016 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1017 try {
1018 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1019 fail("IllegalStateException not thrown");
1020 } catch (IllegalStateException expected) {
1021 assertTrue("Message was: " + expected.getMessage(),
1022 expected.getMessage().contains("already has a profile owner"));
1023 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001024 }
1025
Makoto Onuki90b89652016-01-28 14:44:18 -08001026 public void testClearProfileOwner() throws Exception {
1027 setAsProfileOwner(admin1);
1028
1029 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1030
1031 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1032 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1033
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001034 // First try when the user is locked, which should fail.
1035 when(mContext.userManager.isUserUnlocked(anyInt()))
1036 .thenReturn(false);
1037 try {
1038 dpm.clearProfileOwner(admin1);
1039 fail("Didn't throw IllegalStateException");
1040 } catch (IllegalStateException expected) {
1041 MoreAsserts.assertContainsRegex(
1042 "User must be running and unlocked", expected.getMessage());
1043 }
1044 // Clear, really.
1045 when(mContext.userManager.isUserUnlocked(anyInt()))
1046 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001047 dpm.clearProfileOwner(admin1);
1048
1049 // Check
1050 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001051 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001052 }
1053
Makoto Onukib643fb02015-09-22 15:03:44 -07001054 public void testSetProfileOwner_failures() throws Exception {
1055 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1056 }
1057
Makoto Onukia52562c2015-10-01 16:12:31 -07001058 public void testGetDeviceOwnerAdminLocked() throws Exception {
1059 checkDeviceOwnerWithMultipleDeviceAdmins();
1060 }
1061
1062 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1063 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1064 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1065 // make sure it gets the right component from the right user.
1066
1067 final int ANOTHER_USER_ID = 100;
1068 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1069
1070 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1071
1072 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001073 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001074 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1075 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1076
1077 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1078
Victor Change29cd472016-03-02 20:57:42 +00001079 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1080
Makoto Onukia52562c2015-10-01 16:12:31 -07001081 // Make sure the admin packge is installed to each user.
1082 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1083 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1084
1085 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1086 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1087
1088 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1089
1090
1091 // Set active admins to the users.
1092 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1093 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1094
1095 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1096 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1097
1098 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1099
1100 // Set DO on the first non-system user.
1101 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1102 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1103
Makoto Onukic8a5a552015-11-19 14:29:12 -08001104 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001105
1106 // Then check getDeviceOwnerAdminLocked().
1107 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1108 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1109 }
1110
1111 /**
1112 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001113 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1114 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001115 *
1116 * We didn't use to persist the DO component class name, but now we do, and the above method
1117 * finds the right component from a package name upon migration.
1118 */
1119 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001120 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001121 checkDeviceOwnerWithMultipleDeviceAdmins();
1122
1123 // Overwrite the device owner setting and clears the clas name.
1124 dpms.mOwners.setDeviceOwner(
1125 new ComponentName(admin2.getPackageName(), ""),
1126 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1127 dpms.mOwners.writeDeviceOwner();
1128
1129 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001130 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001131
1132 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001133 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1134 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001135 initializeDpms();
1136
1137 // Now the DO component name is a full name.
1138 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1139 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001140 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001141 }
1142
Makoto Onukib643fb02015-09-22 15:03:44 -07001143 public void testSetGetApplicationRestriction() {
1144 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001145 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001146
1147 {
1148 Bundle rest = new Bundle();
1149 rest.putString("KEY_STRING", "Foo1");
1150 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1151 }
1152
1153 {
1154 Bundle rest = new Bundle();
1155 rest.putString("KEY_STRING", "Foo2");
1156 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1157 }
1158
1159 {
1160 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1161 assertNotNull(returned);
1162 assertEquals(returned.size(), 1);
1163 assertEquals(returned.get("KEY_STRING"), "Foo1");
1164 }
1165
1166 {
1167 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1168 assertNotNull(returned);
1169 assertEquals(returned.size(), 1);
1170 assertEquals(returned.get("KEY_STRING"), "Foo2");
1171 }
1172
1173 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1174 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1175 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001176
Edman Anjosf9946772016-11-28 16:35:15 +01001177 /**
1178 * Setup a package in the package manager mock. Useful for faking installed applications.
1179 *
1180 * @param packageName the name of the package to be setup
1181 * @param appId the application ID to be given to the package
1182 * @return the UID of the package as known by the mock package manager
1183 */
1184 private int setupPackageInPackageManager(final String packageName, final int appId)
1185 throws Exception {
1186 // Make the PackageManager return the package instead of throwing a NameNotFoundException
1187 final PackageInfo pi = new PackageInfo();
1188 pi.applicationInfo = new ApplicationInfo();
1189 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1190 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1191 eq(packageName),
1192 anyInt(),
1193 eq(DpmMockContext.CALLER_USER_HANDLE));
1194 // Setup application UID with the PackageManager
1195 final int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, appId);
1196 doReturn(uid).when(mContext.packageManager).getPackageUidAsUser(
1197 eq(packageName),
1198 eq(DpmMockContext.CALLER_USER_HANDLE));
1199 // Associate packageName to uid
1200 doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid));
1201 doReturn(new String[]{packageName})
1202 .when(mContext.ipackageManager).getPackagesForUid(eq(uid));
1203 return uid;
1204 }
1205
Robin Lee7f5c91c2017-02-08 21:27:02 +00001206 public void testCertificateDisclosure() throws Exception {
1207 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1208 final UserHandle user = UserHandle.of(userId);
1209
1210 mContext.applicationInfo = new ApplicationInfo();
1211 mContext.callerPermissions.add(permission.MANAGE_USERS);
1212 mContext.packageName = "com.android.frameworks.servicestests";
1213 mContext.userContexts.put(user, mContext);
1214 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1215
1216 ParceledListSlice<ParcelableString> oneCert = asSlice(new String[] {"1"});
1217 ParceledListSlice<ParcelableString> fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
1218
1219 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1220 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1221
1222 // Given that we have exactly one certificate installed,
1223 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
1224 // when that certificate is approved,
1225 dpms.approveCaCert(oneCert.getList().get(0).string, userId, true);
1226 // a notification should not be shown.
1227 verify(mContext.notificationManager, timeout(1000))
1228 .cancelAsUser(anyString(), anyInt(), eq(user));
1229
1230 // Given that we have four certificates installed,
1231 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
1232 // when two of them are approved (one of them approved twice hence no action),
1233 dpms.approveCaCert(fourCerts.getList().get(0).string, userId, true);
1234 dpms.approveCaCert(fourCerts.getList().get(1).string, userId, true);
1235 // a notification should be shown saying that there are two certificates left to approve.
1236 verify(mContext.notificationManager, timeout(1000))
1237 .notifyAsUser(anyString(), anyInt(), argThat(
1238 new BaseMatcher<Notification>() {
1239 @Override
1240 public boolean matches(Object item) {
1241 final Notification noti = (Notification) item;
1242 return TEST_STRING.equals(
1243 noti.extras.getString(Notification.EXTRA_TITLE));
1244 }
1245 @Override
1246 public void describeTo(Description description) {
1247 description.appendText(
1248 "Notification{title=\"" + TEST_STRING + "\"}");
1249 }
1250 }), eq(user));
1251 }
1252
Edman Anjosf9946772016-11-28 16:35:15 +01001253 /**
1254 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1255 * privileges can acually be exercised by a delegate are not covered here.
1256 */
1257 public void testDelegation() throws Exception {
1258 setAsProfileOwner(admin1);
1259
1260 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1261
1262 // Given two packages
1263 final String CERT_DELEGATE = "com.delegate.certs";
1264 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1265 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1266 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1267 20989);
1268
1269 // On delegation
1270 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1271 mContext.packageName = admin1.getPackageName();
1272 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1273 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1274
1275 // DPMS correctly stores and retrieves the delegates
1276 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1277 assertEquals(2, policy.mDelegationMap.size());
1278 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1279 DELEGATION_CERT_INSTALL);
1280 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1281 DELEGATION_CERT_INSTALL);
1282 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1283 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1284 DELEGATION_APP_RESTRICTIONS);
1285 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1286 DELEGATION_APP_RESTRICTIONS);
1287 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1288
1289 // On calling install certificate APIs from an unauthorized process
1290 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1291 mContext.packageName = RESTRICTIONS_DELEGATE;
1292
1293 // DPMS throws a SecurityException
1294 try {
1295 dpm.installCaCert(null, null);
1296 fail("Didn't throw SecurityException on unauthorized access");
1297 } catch (SecurityException expected) {
1298 }
1299
1300 // On calling install certificate APIs from an authorized process
1301 mContext.binder.callingUid = CERT_DELEGATE_UID;
1302 mContext.packageName = CERT_DELEGATE;
1303
1304 // DPMS executes without a SecurityException
1305 try {
1306 dpm.installCaCert(null, null);
1307 } catch (SecurityException unexpected) {
1308 fail("Threw SecurityException on authorized access");
1309 } catch (NullPointerException expected) {
1310 }
1311
1312 // On removing a delegate
1313 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1314 mContext.packageName = admin1.getPackageName();
1315 dpm.setCertInstallerPackage(admin1, null);
1316
1317 // DPMS does not allow access to ex-delegate
1318 mContext.binder.callingUid = CERT_DELEGATE_UID;
1319 mContext.packageName = CERT_DELEGATE;
1320 try {
1321 dpm.installCaCert(null, null);
1322 fail("Didn't throw SecurityException on unauthorized access");
1323 } catch (SecurityException expected) {
1324 }
1325
1326 // But still allows access to other existing delegates
1327 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1328 mContext.packageName = RESTRICTIONS_DELEGATE;
1329 try {
1330 dpm.getApplicationRestrictions(null, "pkg");
1331 } catch (SecurityException expected) {
1332 fail("Threw SecurityException on authorized access");
1333 }
1334 }
1335
Esteban Talaverabf60f722015-12-10 16:26:44 +00001336 public void testApplicationRestrictionsManagingApp() throws Exception {
1337 setAsProfileOwner(admin1);
1338
Rubin Xued1928a2016-02-11 17:23:06 +00001339 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001340 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1341 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001342 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1343 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001344
Esteban Talaverabf60f722015-12-10 16:26:44 +00001345 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1346 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001347 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1348 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001349 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1350 Bundle rest = new Bundle();
1351 rest.putString("KEY_STRING", "Foo1");
1352 try {
1353 dpm.setApplicationRestrictions(null, "pkg1", rest);
1354 fail("Didn't throw expected SecurityException");
1355 } catch (SecurityException expected) {
1356 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001357 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1358 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001359 }
1360 try {
1361 dpm.getApplicationRestrictions(null, "pkg1");
1362 fail("Didn't throw expected SecurityException");
1363 } catch (SecurityException expected) {
1364 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001365 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1366 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001367 }
1368
1369 // Check via the profile owner that no restrictions were set.
1370 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001371 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001372 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1373
Rubin Xued1928a2016-02-11 17:23:06 +00001374 // Check the API does not allow setting a non-existent package
1375 try {
1376 dpm.setApplicationRestrictionsManagingPackage(admin1,
1377 nonExistAppRestrictionsManagerPackage);
1378 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001379 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001380 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001381 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001382 }
1383
Esteban Talaverabf60f722015-12-10 16:26:44 +00001384 // Let appRestrictionsManagerPackage manage app restrictions
1385 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1386 assertEquals(appRestrictionsManagerPackage,
1387 dpm.getApplicationRestrictionsManagingPackage(admin1));
1388
1389 // Now that package should be able to set and retrieve app restrictions.
1390 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001391 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001392 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1393 dpm.setApplicationRestrictions(null, "pkg1", rest);
1394 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1395 assertEquals(1, returned.size(), 1);
1396 assertEquals("Foo1", returned.get("KEY_STRING"));
1397
1398 // The same app running on a separate user shouldn't be able to manage app restrictions.
1399 mContext.binder.callingUid = UserHandle.getUid(
1400 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1401 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1402 try {
1403 dpm.setApplicationRestrictions(null, "pkg1", rest);
1404 fail("Didn't throw expected SecurityException");
1405 } catch (SecurityException expected) {
1406 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001407 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1408 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001409 }
1410
1411 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1412 // too.
1413 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001414 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001415 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1416 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1417 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1418
1419 // Removing the ability for the package to manage app restrictions.
1420 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1421 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1422 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001423 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001424 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1425 try {
1426 dpm.setApplicationRestrictions(null, "pkg1", null);
1427 fail("Didn't throw expected SecurityException");
1428 } catch (SecurityException expected) {
1429 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001430 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1431 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001432 }
1433 }
1434
Makoto Onukia4f11972015-10-01 13:19:58 -07001435 public void testSetUserRestriction_asDo() throws Exception {
1436 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001437 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001438 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1439 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1440
1441 // First, set DO.
1442
1443 // Call from a process on the system user.
1444 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1445
1446 // Make sure admin1 is installed on system user.
1447 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001448
1449 // Call.
1450 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001451 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001452 UserHandle.USER_SYSTEM));
1453
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001454 // Check that the user restrictions that are enabled by default are set. Then unset them.
1455 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001456 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001457 DpmTestUtils.assertRestrictions(
1458 DpmTestUtils.newRestrictions(defaultRestrictions),
1459 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1460 );
1461 DpmTestUtils.assertRestrictions(
1462 DpmTestUtils.newRestrictions(defaultRestrictions),
1463 dpm.getUserRestrictions(admin1)
1464 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001465 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1466 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001467 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001468 eq(true) /* isDeviceOwner */,
1469 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001470 );
1471 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001472
1473 for (String restriction : defaultRestrictions) {
1474 dpm.clearUserRestriction(admin1, restriction);
1475 }
1476
Esteban Talavera548a04b2016-12-20 15:22:30 +00001477 assertNoDeviceOwnerRestrictions();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001478 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001479
1480 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1481 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1482 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001483 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1484 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001485 reset(mContext.userManagerInternal);
1486
Makoto Onukia4f11972015-10-01 13:19:58 -07001487 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001488 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1489 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001490 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1491 UserManager.DISALLOW_ADD_USER),
1492 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001493 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001494
Makoto Onuki068c54a2015-10-13 14:34:03 -07001495 DpmTestUtils.assertRestrictions(
1496 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001497 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001498 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1499 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001500 DpmTestUtils.assertRestrictions(
1501 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001502 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001503 dpm.getUserRestrictions(admin1)
1504 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001505
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001506 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1507 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1508 eq(UserHandle.USER_SYSTEM),
1509 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001510 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001511 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001512
Makoto Onuki068c54a2015-10-13 14:34:03 -07001513 DpmTestUtils.assertRestrictions(
1514 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1515 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1516 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001517 DpmTestUtils.assertRestrictions(
1518 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1519 dpm.getUserRestrictions(admin1)
1520 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001521
1522 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001523 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1524 eq(UserHandle.USER_SYSTEM),
1525 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001526 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001527 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001528
Esteban Talavera548a04b2016-12-20 15:22:30 +00001529 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001530
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001531 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1532 // DO sets them, the scope is global.
1533 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1534 reset(mContext.userManagerInternal);
1535 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1536 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1537 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001538 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001539 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1540 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001541 reset(mContext.userManagerInternal);
1542
1543 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1544 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov6a40f092016-10-25 15:46:51 +01001545 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001546
1547 // More tests.
1548 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1549 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1550 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001551 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1552 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001553 reset(mContext.userManagerInternal);
1554
1555 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1556 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1557 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001558 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001559 UserManager.DISALLOW_ADD_USER),
1560 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001561 reset(mContext.userManagerInternal);
1562
1563 dpm.setCameraDisabled(admin1, true);
1564 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1565 eq(UserHandle.USER_SYSTEM),
1566 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001567 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001568 UserManager.DISALLOW_ADD_USER),
1569 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001570 reset(mContext.userManagerInternal);
1571
1572 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1573 // locally.
1574 dpm.setCameraDisabled(admin1, false);
1575 reset(mContext.userManagerInternal);
1576
1577 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1578 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1579 dpm.setCameraDisabled(admin2, true);
1580
1581 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1582 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001583 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001584 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001585 UserManager.DISALLOW_ADD_USER),
1586 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001587 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001588 // TODO Make sure restrictions are written to the file.
1589 }
1590
1591 public void testSetUserRestriction_asPo() {
1592 setAsProfileOwner(admin1);
1593
Makoto Onuki068c54a2015-10-13 14:34:03 -07001594 DpmTestUtils.assertRestrictions(
1595 DpmTestUtils.newRestrictions(),
1596 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1597 .ensureUserRestrictions()
1598 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001599
1600 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001601 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1602 eq(DpmMockContext.CALLER_USER_HANDLE),
1603 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001604 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001605 reset(mContext.userManagerInternal);
1606
Makoto Onukia4f11972015-10-01 13:19:58 -07001607 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001608 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1609 eq(DpmMockContext.CALLER_USER_HANDLE),
1610 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1611 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001612 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001613 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001614
Makoto Onuki068c54a2015-10-13 14:34:03 -07001615 DpmTestUtils.assertRestrictions(
1616 DpmTestUtils.newRestrictions(
1617 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1618 UserManager.DISALLOW_OUTGOING_CALLS
1619 ),
1620 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1621 .ensureUserRestrictions()
1622 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001623 DpmTestUtils.assertRestrictions(
1624 DpmTestUtils.newRestrictions(
1625 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1626 UserManager.DISALLOW_OUTGOING_CALLS
1627 ),
1628 dpm.getUserRestrictions(admin1)
1629 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001630
1631 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001632 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1633 eq(DpmMockContext.CALLER_USER_HANDLE),
1634 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001635 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001636 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001637
1638 DpmTestUtils.assertRestrictions(
1639 DpmTestUtils.newRestrictions(
1640 UserManager.DISALLOW_OUTGOING_CALLS
1641 ),
1642 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1643 .ensureUserRestrictions()
1644 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001645 DpmTestUtils.assertRestrictions(
1646 DpmTestUtils.newRestrictions(
1647 UserManager.DISALLOW_OUTGOING_CALLS
1648 ),
1649 dpm.getUserRestrictions(admin1)
1650 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001651
1652 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1654 eq(DpmMockContext.CALLER_USER_HANDLE),
1655 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001656 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001657 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001658
Makoto Onuki068c54a2015-10-13 14:34:03 -07001659 DpmTestUtils.assertRestrictions(
1660 DpmTestUtils.newRestrictions(),
1661 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1662 .ensureUserRestrictions()
1663 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001664 DpmTestUtils.assertRestrictions(
1665 DpmTestUtils.newRestrictions(),
1666 dpm.getUserRestrictions(admin1)
1667 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001668
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001669 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1670 // though when DO sets them they'll be applied globally.
1671 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1672 reset(mContext.userManagerInternal);
1673 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1674 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1675 eq(DpmMockContext.CALLER_USER_HANDLE),
1676 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1677 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001678 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001679 reset(mContext.userManagerInternal);
1680
1681 dpm.setCameraDisabled(admin1, true);
1682 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1683 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001684 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001685 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001686 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687 reset(mContext.userManagerInternal);
1688
Makoto Onukia4f11972015-10-01 13:19:58 -07001689 // TODO Make sure restrictions are written to the file.
1690 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001691
Esteban Talavera548a04b2016-12-20 15:22:30 +00001692
1693 public void testDefaultEnabledUserRestrictions() throws Exception {
1694 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1695 mContext.callerPermissions.add(permission.MANAGE_USERS);
1696 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1697 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1698
1699 // First, set DO.
1700
1701 // Call from a process on the system user.
1702 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1703
1704 // Make sure admin1 is installed on system user.
1705 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1706
1707 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1708 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1709 UserHandle.USER_SYSTEM));
1710
1711 // Check that the user restrictions that are enabled by default are set. Then unset them.
1712 String[] defaultRestrictions = UserRestrictionsUtils
1713 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1714 assertTrue(defaultRestrictions.length > 0);
1715 DpmTestUtils.assertRestrictions(
1716 DpmTestUtils.newRestrictions(defaultRestrictions),
1717 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1718 );
1719 DpmTestUtils.assertRestrictions(
1720 DpmTestUtils.newRestrictions(defaultRestrictions),
1721 dpm.getUserRestrictions(admin1)
1722 );
1723 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1724 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001725 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001726 eq(true) /* isDeviceOwner */,
1727 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001728 );
1729 reset(mContext.userManagerInternal);
1730
1731 for (String restriction : defaultRestrictions) {
1732 dpm.clearUserRestriction(admin1, restriction);
1733 }
1734
1735 assertNoDeviceOwnerRestrictions();
1736
1737 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1738 reset(mContext.userManagerInternal);
1739 initializeDpms();
1740 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1741 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1742
1743 assertNoDeviceOwnerRestrictions();
1744
1745 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1746 // is set as it wasn't enabled during setDeviceOwner.
1747 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1748 assertFalse(UserRestrictionsUtils
1749 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1750 UserRestrictionsUtils
1751 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1752 try {
1753 reset(mContext.userManagerInternal);
1754 initializeDpms();
1755 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1756 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1757
1758 DpmTestUtils.assertRestrictions(
1759 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1760 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1761 );
1762 DpmTestUtils.assertRestrictions(
1763 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1764 dpm.getUserRestrictions(admin1)
1765 );
1766 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1767 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001768 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001769 eq(true) /* isDeviceOwner */,
1770 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001771 );
1772 reset(mContext.userManagerInternal);
1773
1774 // Remove the restriction.
1775 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1776
1777 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1778 initializeDpms();
1779 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1780 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1781 assertNoDeviceOwnerRestrictions();
1782 } finally {
1783 UserRestrictionsUtils
1784 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1785 }
1786 }
1787
1788 private void assertNoDeviceOwnerRestrictions() {
1789 DpmTestUtils.assertRestrictions(
1790 DpmTestUtils.newRestrictions(),
1791 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1792 );
1793 DpmTestUtils.assertRestrictions(
1794 DpmTestUtils.newRestrictions(),
1795 dpm.getUserRestrictions(admin1)
1796 );
1797 }
1798
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001799 public void testGetMacAddress() throws Exception {
1800 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1801 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1802 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1803
1804 // In this test, change the caller user to "system".
1805 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1806
1807 // Make sure admin1 is installed on system user.
1808 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1809
1810 // Test 1. Caller doesn't have DO or DA.
1811 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001812 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001813 fail();
1814 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001815 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001816 }
1817
1818 // DO needs to be an DA.
1819 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1820 assertTrue(dpm.isAdminActive(admin1));
1821
1822 // Test 2. Caller has DA, but not DO.
1823 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001824 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001825 fail();
1826 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001827 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001828 }
1829
1830 // Test 3. Caller has PO, but not DO.
1831 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1832 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001833 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001834 fail();
1835 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001836 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001837 }
1838
1839 // Remove PO.
1840 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001841 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001842 // Test 4, Caller is DO now.
1843 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1844
1845 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001846 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001847
1848 // 4-2. Returns WifiInfo, but with the default MAC.
1849 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001850 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001851
1852 // 4-3. With a real MAC address.
1853 final WifiInfo wi = new WifiInfo();
1854 wi.setMacAddress("11:22:33:44:55:66");
1855 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001856 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001857 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001858
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001859 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001860 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1861 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1862
1863 // In this test, change the caller user to "system".
1864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1865
1866 // Make sure admin1 is installed on system user.
1867 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1868
1869 // Set admin1 as DA.
1870 dpm.setActiveAdmin(admin1, false);
1871 assertTrue(dpm.isAdminActive(admin1));
1872 try {
1873 dpm.reboot(admin1);
1874 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1875 } catch (SecurityException expected) {
1876 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1877 }
1878
1879 // Set admin1 as PO.
1880 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1881 try {
1882 dpm.reboot(admin1);
1883 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1884 } catch (SecurityException expected) {
1885 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1886 }
1887
1888 // Remove PO and add DO.
1889 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001890 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001891 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1892
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001893 // admin1 is DO.
1894 // Set current call state of device to ringing.
1895 when(mContext.telephonyManager.getCallState())
1896 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1897 try {
1898 dpm.reboot(admin1);
1899 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1900 } catch (IllegalStateException expected) {
1901 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1902 }
1903
1904 // Set current call state of device to dialing/active.
1905 when(mContext.telephonyManager.getCallState())
1906 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1907 try {
1908 dpm.reboot(admin1);
1909 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1910 } catch (IllegalStateException expected) {
1911 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1912 }
1913
1914 // Set current call state of device to idle.
1915 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001916 dpm.reboot(admin1);
1917 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001918
1919 public void testSetGetSupportText() {
1920 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1921 dpm.setActiveAdmin(admin1, true);
1922 dpm.setActiveAdmin(admin2, true);
1923 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1924
1925 // Null default support messages.
1926 {
1927 assertNull(dpm.getLongSupportMessage(admin1));
1928 assertNull(dpm.getShortSupportMessage(admin1));
1929 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1930 assertNull(dpm.getShortSupportMessageForUser(admin1,
1931 DpmMockContext.CALLER_USER_HANDLE));
1932 assertNull(dpm.getLongSupportMessageForUser(admin1,
1933 DpmMockContext.CALLER_USER_HANDLE));
1934 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1935 }
1936
1937 // Only system can call the per user versions.
1938 {
1939 try {
1940 dpm.getShortSupportMessageForUser(admin1,
1941 DpmMockContext.CALLER_USER_HANDLE);
1942 fail("Only system should be able to call getXXXForUser versions");
1943 } catch (SecurityException expected) {
1944 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1945 }
1946 try {
1947 dpm.getLongSupportMessageForUser(admin1,
1948 DpmMockContext.CALLER_USER_HANDLE);
1949 fail("Only system should be able to call getXXXForUser versions");
1950 } catch (SecurityException expected) {
1951 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1952 }
1953 }
1954
1955 // Can't set message for admin in another uid.
1956 {
1957 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1958 try {
1959 dpm.setShortSupportMessage(admin1, "Some text");
1960 fail("Admins should only be able to change their own support text.");
1961 } catch (SecurityException expected) {
1962 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1963 }
1964 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1965 }
1966
1967 // Set/Get short returns what it sets and other admins text isn't changed.
1968 {
1969 final String supportText = "Some text to test with.";
1970 dpm.setShortSupportMessage(admin1, supportText);
1971 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1972 assertNull(dpm.getLongSupportMessage(admin1));
1973 assertNull(dpm.getShortSupportMessage(admin2));
1974
1975 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1976 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1977 DpmMockContext.CALLER_USER_HANDLE));
1978 assertNull(dpm.getShortSupportMessageForUser(admin2,
1979 DpmMockContext.CALLER_USER_HANDLE));
1980 assertNull(dpm.getLongSupportMessageForUser(admin1,
1981 DpmMockContext.CALLER_USER_HANDLE));
1982 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1983
1984 dpm.setShortSupportMessage(admin1, null);
1985 assertNull(dpm.getShortSupportMessage(admin1));
1986 }
1987
1988 // Set/Get long returns what it sets and other admins text isn't changed.
1989 {
1990 final String supportText = "Some text to test with.\nWith more text.";
1991 dpm.setLongSupportMessage(admin1, supportText);
1992 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1993 assertNull(dpm.getShortSupportMessage(admin1));
1994 assertNull(dpm.getLongSupportMessage(admin2));
1995
1996 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1997 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1998 DpmMockContext.CALLER_USER_HANDLE));
1999 assertNull(dpm.getLongSupportMessageForUser(admin2,
2000 DpmMockContext.CALLER_USER_HANDLE));
2001 assertNull(dpm.getShortSupportMessageForUser(admin1,
2002 DpmMockContext.CALLER_USER_HANDLE));
2003 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2004
2005 dpm.setLongSupportMessage(admin1, null);
2006 assertNull(dpm.getLongSupportMessage(admin1));
2007 }
2008 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002009
phweiss73145f42017-01-17 19:06:38 +01002010 public void testCreateAdminSupportIntent() throws Exception {
2011 // Setup device owner.
2012 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2013 setupDeviceOwner();
2014
2015 // Nonexisting permission returns null
2016 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2017 assertNull(intent);
2018
2019 // Existing permission that is not set returns null
2020 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2021 assertNull(intent);
2022
2023 // Existing permission that is not set by device/profile owner returns null
2024 when(mContext.userManager.hasUserRestriction(
2025 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2026 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2027 .thenReturn(true);
2028 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2029 assertNull(intent);
2030
2031 // Permission that is set by device owner returns correct intent
2032 when(mContext.userManager.getUserRestrictionSource(
2033 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2034 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2035 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2036 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2037 assertNotNull(intent);
2038 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2039 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2040 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2041 assertEquals(admin1,
2042 (ComponentName) intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
2043 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2044 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2045
2046 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2047 // user restrictions
2048
2049 // Camera is not disabled
2050 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2051 assertNull(intent);
2052
2053 // Camera is disabled
2054 dpm.setCameraDisabled(admin1, true);
2055 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2056 assertNotNull(intent);
2057 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2058 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2059
2060 // Screen capture is not disabled
2061 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2062 assertNull(intent);
2063
2064 // Screen capture is disabled
2065 dpm.setScreenCaptureDisabled(admin1, true);
2066 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2067 assertNotNull(intent);
2068 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2069 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2070
2071 // Same checks for different user
2072 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2073 // Camera should be disabled by device owner
2074 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2075 assertNotNull(intent);
2076 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2077 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2078 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2079 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2080 // ScreenCapture should not be disabled by device owner
2081 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2082 assertNull(intent);
2083 }
2084
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002085 /**
2086 * Test for:
2087 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002088 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002089 * {@link DevicePolicyManager#isAffiliatedUser}
2090 */
2091 public void testUserAffiliation() throws Exception {
2092 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2093 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2094 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2095
2096 // Check that the system user is unaffiliated.
2097 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2098 assertFalse(dpm.isAffiliatedUser());
2099
2100 // Set a device owner on the system user. Check that the system user becomes affiliated.
2101 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2102 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2103 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2104 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002105 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002106
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002107 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002108 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2109 setAsProfileOwner(admin2);
2110 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002111 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002112
2113 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2114 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002115 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002116 userAffiliationIds.add("red");
2117 userAffiliationIds.add("green");
2118 userAffiliationIds.add("blue");
2119 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002120 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002121 assertFalse(dpm.isAffiliatedUser());
2122
2123 // Have the device owner specify a set of affiliation ids that do not intersect with those
2124 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002125 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002126 deviceAffiliationIds.add("cyan");
2127 deviceAffiliationIds.add("yellow");
2128 deviceAffiliationIds.add("magenta");
2129 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2130 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002131 MoreAsserts.assertContentsInAnyOrder(
2132 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002133 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2134 assertFalse(dpm.isAffiliatedUser());
2135
2136 // Have the profile owner specify a set of affiliation ids that intersect with those
2137 // specified by the device owner. Check that the test user becomes affiliated.
2138 userAffiliationIds.add("yellow");
2139 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002140 MoreAsserts.assertContentsInAnyOrder(
2141 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002142 assertTrue(dpm.isAffiliatedUser());
2143
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002144 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
2145 dpm.setAffiliationIds(admin2, Collections.emptyList());
2146 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002147 assertFalse(dpm.isAffiliatedUser());
2148
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002149 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2150 dpm.setAffiliationIds(admin2, userAffiliationIds);
2151 assertTrue(dpm.isAffiliatedUser());
2152 dpm.clearProfileOwner(admin2);
2153 assertFalse(dpm.isAffiliatedUser());
2154
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002155 // Check that the system user remains affiliated.
2156 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2157 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002158
2159 // Clear the device owner - the user becomes unaffiliated.
2160 clearDeviceOwner();
2161 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002162 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002163
2164 public void testGetUserProvisioningState_defaultResult() {
2165 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2166 }
2167
2168 public void testSetUserProvisioningState_permission() throws Exception {
2169 setupProfileOwner();
2170 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2171
2172 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2173 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2174 }
2175
2176 public void testSetUserProvisioningState_unprivileged() throws Exception {
2177 setupProfileOwner();
2178 try {
2179 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2180 DpmMockContext.CALLER_USER_HANDLE);
2181 fail("Expected SecurityException");
2182 } catch (SecurityException expected) {
2183 }
2184 }
2185
2186 public void testSetUserProvisioningState_noManagement() {
2187 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2188 try {
2189 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2190 DpmMockContext.CALLER_USER_HANDLE);
2191 fail("IllegalStateException expected");
2192 } catch (IllegalStateException e) {
2193 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
2194 e.getMessage());
2195 }
2196 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2197 }
2198
2199 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2200 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2201 setupDeviceOwner();
2202 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2203
2204 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2205 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2206 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2207 }
2208
2209 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2210 throws Exception {
2211 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2212 setupDeviceOwner();
2213 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2214
2215 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2216 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2217 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2218 }
2219
2220 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2221 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2222 setupDeviceOwner();
2223 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2224
2225 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2226 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2227 }
2228
2229 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2230 throws Exception {
2231 setupProfileOwner();
2232 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2233
2234 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2235 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2236 DevicePolicyManager.STATE_USER_UNMANAGED);
2237 }
2238
2239 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2240 throws Exception {
2241 setupProfileOwner();
2242 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2243
2244 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2245 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2246 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2247 }
2248
2249 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2250 setupProfileOwner();
2251 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2252
2253 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2254 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2255 }
2256
2257 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2258 setupProfileOwner();
2259 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2260
2261 try {
2262 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2263 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2264 DevicePolicyManager.STATE_USER_UNMANAGED);
2265 fail("Expected IllegalStateException");
2266 } catch (IllegalStateException e) {
2267 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2268 e.getMessage());
2269 }
2270 }
2271
2272 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2273 throws Exception {
2274 setupProfileOwner();
2275 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2276
2277 try {
2278 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2279 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2280 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2281 fail("Expected IllegalStateException");
2282 } catch (IllegalStateException e) {
2283 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2284 e.getMessage());
2285 }
2286 }
2287
2288 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2289 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2290 for (int state : states) {
2291 dpm.setUserProvisioningState(state, userId);
2292 assertEquals(state, dpm.getUserProvisioningState());
2293 }
2294 }
2295
2296 private void setupProfileOwner() throws Exception {
2297 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2298
2299 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2300 dpm.setActiveAdmin(admin1, false);
2301 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2302
2303 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2304 }
2305
2306 private void setupDeviceOwner() throws Exception {
2307 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2308
2309 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2310 dpm.setActiveAdmin(admin1, false);
2311 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2312
2313 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2314 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002315
2316 public void testSetMaximumTimeToLock() {
2317 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2318
2319 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2320 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2321
2322 reset(mMockContext.powerManagerInternal);
2323 reset(mMockContext.settings);
2324
2325 dpm.setMaximumTimeToLock(admin1, 0);
2326 verifyScreenTimeoutCall(null, false);
2327 reset(mMockContext.powerManagerInternal);
2328 reset(mMockContext.settings);
2329
2330 dpm.setMaximumTimeToLock(admin1, 1);
2331 verifyScreenTimeoutCall(1, true);
2332 reset(mMockContext.powerManagerInternal);
2333 reset(mMockContext.settings);
2334
2335 dpm.setMaximumTimeToLock(admin2, 10);
2336 verifyScreenTimeoutCall(null, false);
2337 reset(mMockContext.powerManagerInternal);
2338 reset(mMockContext.settings);
2339
2340 dpm.setMaximumTimeToLock(admin1, 5);
2341 verifyScreenTimeoutCall(5, true);
2342 reset(mMockContext.powerManagerInternal);
2343 reset(mMockContext.settings);
2344
2345 dpm.setMaximumTimeToLock(admin2, 4);
2346 verifyScreenTimeoutCall(4, true);
2347 reset(mMockContext.powerManagerInternal);
2348 reset(mMockContext.settings);
2349
2350 dpm.setMaximumTimeToLock(admin1, 0);
2351 reset(mMockContext.powerManagerInternal);
2352 reset(mMockContext.settings);
2353
2354 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2355 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2356 reset(mMockContext.powerManagerInternal);
2357 reset(mMockContext.settings);
2358
2359 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2360 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2361 reset(mMockContext.powerManagerInternal);
2362 reset(mMockContext.settings);
2363
2364 dpm.setMaximumTimeToLock(admin2, 10);
2365 verifyScreenTimeoutCall(10, true);
2366 reset(mMockContext.powerManagerInternal);
2367 reset(mMockContext.settings);
2368
2369 // There's no restriction; shold be set to MAX.
2370 dpm.setMaximumTimeToLock(admin2, 0);
2371 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2372 }
2373
Michal Karpinski943aabd2016-10-06 11:09:25 +01002374 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2375 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2376 setupDeviceOwner();
2377 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2378
Michal Karpinskid084ca52017-01-18 15:54:18 +00002379 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2380 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2381 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2382 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2383 - ONE_MINUTE;
2384
2385 // verify that the minimum timeout cannot be modified on user builds (system property is
2386 // not being read)
2387 mContext.buildMock.isDebuggable = false;
2388
2389 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2390 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2391 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2392
2393 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2394
2395 // restore to the debuggable build state
2396 mContext.buildMock.isDebuggable = true;
2397
2398 // Always return the default (second arg) when getting system property for long type
2399 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2400 new Answer<Long>() {
2401 @Override
2402 public Long answer(InvocationOnMock invocation) throws Throwable {
2403 return (Long) invocation.getArguments()[1];
2404 }
2405 }
2406 );
2407
2408 // reset to default (0 means the admin is not participating, so default should be returned)
2409 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002410
2411 // aggregation should be the default if unset by any admin
2412 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2413 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2414
2415 // admin not participating by default
2416 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2417
2418 //clamping from the top
2419 dpm.setRequiredStrongAuthTimeout(admin1,
2420 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2421 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2422 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2423 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2424 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2425
Michal Karpinskid084ca52017-01-18 15:54:18 +00002426 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002427 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2428 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2429 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2430 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2431
2432 // clamping from the bottom
2433 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2434 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2435 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2436
Michal Karpinskid084ca52017-01-18 15:54:18 +00002437 // values within range
2438 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2439 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2440 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2441
2442 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2443 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2444 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002445
2446 // reset to default
2447 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2448 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2449 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2450 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2451
2452 // negative value
2453 try {
2454 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2455 fail("Didn't throw IllegalArgumentException");
2456 } catch (IllegalArgumentException iae) {
2457 }
2458 }
2459
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002460 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2461 boolean shouldStayOnWhilePluggedInBeCleared) {
2462 if (expectedTimeout == null) {
2463 verify(mMockContext.powerManagerInternal, times(0))
2464 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2465 } else {
2466 verify(mMockContext.powerManagerInternal, times(1))
2467 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2468 }
2469 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2470 // UnfinishedVerificationException.
2471 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002472
Esteban Talavera01576862016-12-15 11:16:44 +00002473 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002474 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2475 .thenReturn(false);
2476 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2477 .thenReturn(false);
2478 initializeDpms();
2479 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2480 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2481 .thenReturn(true);
2482 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2483
2484 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002485 }
Victor Chang3e794af2016-03-04 13:48:17 +00002486
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002487 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2488 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002489 mContext.packageName = admin1.getPackageName();
2490 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002491 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2492 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2493 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2494 false);
2495 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2496 }
2497
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002498 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2499 setup_DeviceAdminFeatureOff();
2500 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2501 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2502 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2503 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2504 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2505 assertCheckProvisioningPreCondition(
2506 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2507 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2508 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2509 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2510 }
2511
Esteban Talavera01576862016-12-15 11:16:44 +00002512 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002513 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2514 .thenReturn(false);
2515 initializeDpms();
2516 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2517 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2518 .thenReturn(true);
2519 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2520
2521 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002522 }
Victor Chang3e794af2016-03-04 13:48:17 +00002523
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002524 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2525 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002526 mContext.packageName = admin1.getPackageName();
2527 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002528 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2529 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2530 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2531 false);
2532 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2533
2534 // Test again when split user is on
2535 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2536 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2537 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2538 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2539 true);
2540 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2541 }
2542
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002543 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2544 setup_ManagedProfileFeatureOff();
2545 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2546 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2547 DevicePolicyManager.CODE_OK);
2548 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2549 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2550 assertCheckProvisioningPreCondition(
2551 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2552 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2553 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2554 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2555
2556 // Test again when split user is on
2557 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2558 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2559 DevicePolicyManager.CODE_OK);
2560 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2561 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2562 assertCheckProvisioningPreCondition(
2563 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2564 DevicePolicyManager.CODE_OK);
2565 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2566 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2567 }
2568
Esteban Talavera01576862016-12-15 11:16:44 +00002569 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002570 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2571 .thenReturn(true);
2572 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2573 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2574 .thenReturn(true);
2575 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2576
2577 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002578 }
Victor Chang3e794af2016-03-04 13:48:17 +00002579
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002580 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2581 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002582 mContext.packageName = admin1.getPackageName();
2583 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002584 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2585 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2586 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2587 false /* because of non-split user */);
2588 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2589 false /* because of non-split user */);
2590 }
2591
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002592 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002593 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002594 setup_nonSplitUser_firstBoot_primaryUser();
2595 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2596 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2597 DevicePolicyManager.CODE_OK);
2598 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2599 DevicePolicyManager.CODE_OK);
2600 assertCheckProvisioningPreCondition(
2601 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2602 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2603 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2604 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2605 }
2606
Esteban Talavera01576862016-12-15 11:16:44 +00002607 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002608 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2609 .thenReturn(true);
2610 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2611 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2612 .thenReturn(true);
2613 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2614
2615 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002616 }
Victor Chang3e794af2016-03-04 13:48:17 +00002617
Nicolas Prevot45d29072017-01-18 16:11:19 +00002618 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2619 setDeviceOwner();
2620 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2621 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2622 }
2623
2624 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2625 setup_nonSplitUser_withDo_primaryUser();
2626 final int MANAGED_PROFILE_USER_ID = 18;
2627 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2628 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2629 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2630 false /* we can't remove a managed profile */)).thenReturn(false);
2631 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2632 true)).thenReturn(true);
2633 }
2634
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002635 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2636 throws Exception {
2637 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002638 mContext.packageName = admin1.getPackageName();
2639 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002640 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2641 false/* because of completed device setup */);
2642 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2643 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2644 false/* because of non-split user */);
2645 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2646 false/* because of non-split user */);
2647 }
2648
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002649 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2650 throws Exception {
2651 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2652 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2653 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2654 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2655 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2656 DevicePolicyManager.CODE_OK);
2657 assertCheckProvisioningPreCondition(
2658 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2659 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2660 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2661 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2662 }
2663
Nicolas Prevot45d29072017-01-18 16:11:19 +00002664 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2665 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002666 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002667 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2668
2669 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2670 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002671 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002672
2673 // COMP mode is allowed.
2674 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2675 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002676 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002677
Nicolas Prevot45d29072017-01-18 16:11:19 +00002678 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002679 assertCheckProvisioningPreCondition(
2680 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002681 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002682 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002683 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2684 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2685 }
Esteban Talavera01576862016-12-15 11:16:44 +00002686
Nicolas Prevot45d29072017-01-18 16:11:19 +00002687 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2688 setup_nonSplitUser_withDo_primaryUser();
2689 mContext.packageName = admin1.getPackageName();
2690 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2691 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2692 // other packages should be forbidden.
Esteban Talavera01576862016-12-15 11:16:44 +00002693 when(mContext.userManager.hasUserRestriction(
2694 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2695 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2696 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002697 when(mContext.userManager.getUserRestrictionSource(
2698 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2699 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2700 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2701 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2702 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002703 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002704 assertCheckProvisioningPreCondition(
2705 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002706 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002707 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002708 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2709 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2710 }
Esteban Talavera01576862016-12-15 11:16:44 +00002711
Nicolas Prevot45d29072017-01-18 16:11:19 +00002712 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2713 throws Exception {
2714 setup_nonSplitUser_withDo_primaryUser();
2715 mContext.packageName = admin1.getPackageName();
2716 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002717 // The DO should not be allowed to initiate provisioning if the restriction is set by
2718 // another entity.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002719 when(mContext.userManager.hasUserRestriction(
2720 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2721 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2722 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002723 when(mContext.userManager.getUserRestrictionSource(
2724 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2725 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2726 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2727 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2728 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002729 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2730
2731 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002732 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002733 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002734 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002735 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2736 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2737 }
2738
2739 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2740 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2741 mContext.packageName = admin1.getPackageName();
2742 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2743
2744 // We can delete the managed profile to create a new one, so provisioning is allowed.
2745 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2746 DevicePolicyManager.CODE_OK);
2747 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2748 assertCheckProvisioningPreCondition(
2749 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2750 DpmMockContext.ANOTHER_PACKAGE_NAME,
2751 DevicePolicyManager.CODE_OK);
2752 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2753 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2754 }
2755
2756 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2757 throws Exception {
2758 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2759 mContext.packageName = admin1.getPackageName();
2760 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2761 when(mContext.userManager.hasUserRestriction(
2762 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2763 eq(UserHandle.SYSTEM)))
2764 .thenReturn(true);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002765 when(mContext.userManager.getUserRestrictionSource(
2766 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2767 eq(UserHandle.SYSTEM)))
2768 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002769
2770 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002771 assertCheckProvisioningPreCondition(
2772 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2773 DpmMockContext.ANOTHER_PACKAGE_NAME,
2774 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2775 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2776 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002777
2778 // But the device owner can still do it because it has set the restriction itself.
2779 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2780 DevicePolicyManager.CODE_OK);
2781 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002782 }
2783
2784 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002785 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2786 .thenReturn(true);
2787 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2788 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2789 .thenReturn(false);
2790 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2791
2792 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002793 }
Victor Chang3e794af2016-03-04 13:48:17 +00002794
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002795 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2796 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002797 mContext.packageName = admin1.getPackageName();
2798 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002799 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2800 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2801 false /* because canAddMoreManagedProfiles returns false */);
2802 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2803 true);
2804 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2805 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002806 }
2807
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002808 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2809 throws Exception {
2810 setup_splitUser_firstBoot_systemUser();
2811 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2812 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2813 DevicePolicyManager.CODE_OK);
2814 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002815 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002816 assertCheckProvisioningPreCondition(
2817 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2818 DevicePolicyManager.CODE_OK);
2819 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2820 DevicePolicyManager.CODE_SYSTEM_USER);
2821 }
2822
Esteban Talavera01576862016-12-15 11:16:44 +00002823 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002824 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2825 .thenReturn(true);
2826 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2827 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2828 .thenReturn(false);
2829 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2830
2831 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002832 }
Victor Chang3e794af2016-03-04 13:48:17 +00002833
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002834 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2835 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002836 mContext.packageName = admin1.getPackageName();
2837 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002838 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2839 true/* it's undefined behavior. Can be changed into false in the future */);
2840 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2841 false /* because canAddMoreManagedProfiles returns false */);
2842 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2843 true/* it's undefined behavior. Can be changed into false in the future */);
2844 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2845 false/* because calling uid is system user */);
2846 }
2847
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002848 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2849 throws Exception {
2850 setup_splitUser_afterDeviceSetup_systemUser();
2851 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2852 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2853 DevicePolicyManager.CODE_OK);
2854 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002855 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002856 assertCheckProvisioningPreCondition(
2857 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2858 DevicePolicyManager.CODE_OK);
2859 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2860 DevicePolicyManager.CODE_SYSTEM_USER);
2861 }
2862
Esteban Talavera01576862016-12-15 11:16:44 +00002863 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002864 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2865 .thenReturn(true);
2866 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2867 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2868 true)).thenReturn(true);
2869 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2870
2871 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002872 }
Victor Chang3e794af2016-03-04 13:48:17 +00002873
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002874 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2875 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002876 mContext.packageName = admin1.getPackageName();
2877 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002878 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2879 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2880 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2881 true);
2882 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002883 }
2884
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002885 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002886 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002887 setup_splitUser_firstBoot_primaryUser();
2888 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2889 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2890 DevicePolicyManager.CODE_OK);
2891 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2892 DevicePolicyManager.CODE_OK);
2893 assertCheckProvisioningPreCondition(
2894 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2895 DevicePolicyManager.CODE_OK);
2896 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2897 DevicePolicyManager.CODE_OK);
2898 }
2899
Esteban Talavera01576862016-12-15 11:16:44 +00002900 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002901 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2902 .thenReturn(true);
2903 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2904 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2905 true)).thenReturn(true);
2906 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2907
2908 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002909 }
Victor Chang3e794af2016-03-04 13:48:17 +00002910
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002911 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2912 throws Exception {
2913 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002914 mContext.packageName = admin1.getPackageName();
2915 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002916 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2917 true/* it's undefined behavior. Can be changed into false in the future */);
2918 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2919 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2920 true/* it's undefined behavior. Can be changed into false in the future */);
2921 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2922 false/* because user setup completed */);
2923 }
2924
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002925 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002926 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002927 setup_splitUser_afterDeviceSetup_primaryUser();
2928 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2929 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2930 DevicePolicyManager.CODE_OK);
2931 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2932 DevicePolicyManager.CODE_OK);
2933 assertCheckProvisioningPreCondition(
2934 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2935 DevicePolicyManager.CODE_OK);
2936 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2937 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2938 }
2939
Esteban Talavera01576862016-12-15 11:16:44 +00002940 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002941 setDeviceOwner();
2942
2943 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2944 .thenReturn(true);
2945 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2946 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2947 .thenReturn(false);
2948 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2949
2950 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002951 }
Victor Chang3e794af2016-03-04 13:48:17 +00002952
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002953 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2954 throws Exception {
2955 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002956 mContext.packageName = admin1.getPackageName();
2957 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002958 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2959 false /* can't provision managed profile on system user */);
2960 }
2961
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002962 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002963 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002964 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2965 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2966 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2967 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2968 }
2969
2970 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002971 setDeviceOwner();
2972
2973 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2974 .thenReturn(true);
2975 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2976 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2977 true)).thenReturn(true);
2978 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2979
2980 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002981 }
Victor Chang3e794af2016-03-04 13:48:17 +00002982
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002983 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2984 throws Exception {
2985 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002986 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2987 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002988 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2989 }
2990
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002991 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002992 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002993 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2994 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002995
2996 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002997 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2998 DevicePolicyManager.CODE_OK);
2999 }
3000
3001 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003002 setDeviceOwner();
3003
3004 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3005 .thenReturn(true);
3006 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003007 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003008 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3009 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003010 .thenReturn(true);
3011 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003012 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003013 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3014 true)).thenReturn(true);
3015 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3016
3017 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003018 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003019
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003020 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3021 throws Exception {
3022 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003023 mContext.packageName = admin1.getPackageName();
3024 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003025 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3026 }
3027
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003028 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3029 throws Exception {
3030 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3031 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3032 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3033 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3034 }
3035
3036 public void testCheckProvisioningPreCondition_permission() {
3037 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3038 try {
Esteban Talavera01576862016-12-15 11:16:44 +00003039 dpm.checkProvisioningPreCondition(
3040 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003041 fail("Didn't throw SecurityException");
3042 } catch (SecurityException expected) {
3043 }
3044 }
3045
Victor Chang3577ed22016-08-25 18:49:26 +01003046 public void testForceUpdateUserSetupComplete_permission() {
3047 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3048 try {
3049 dpm.forceUpdateUserSetupComplete();
3050 fail("Didn't throw SecurityException");
3051 } catch (SecurityException expected) {
3052 }
3053 }
3054
3055 public void testForceUpdateUserSetupComplete_systemUser() {
3056 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3057 // GIVEN calling from user 20
3058 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3059 try {
3060 dpm.forceUpdateUserSetupComplete();
3061 fail("Didn't throw SecurityException");
3062 } catch (SecurityException expected) {
3063 }
3064 }
3065
3066 public void testForceUpdateUserSetupComplete_userbuild() {
3067 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3068 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3069
3070 final int userId = UserHandle.USER_SYSTEM;
3071 // GIVEN userComplete is false in SettingsProvider
3072 setUserSetupCompleteForUser(false, userId);
3073
3074 // GIVEN userComplete is true in DPM
3075 DevicePolicyManagerService.DevicePolicyData userData =
3076 new DevicePolicyManagerService.DevicePolicyData(userId);
3077 userData.mUserSetupComplete = true;
3078 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3079
3080 // GIVEN it's user build
3081 mContext.buildMock.isDebuggable = false;
3082
3083 assertTrue(dpms.hasUserSetupCompleted());
3084
3085 dpm.forceUpdateUserSetupComplete();
3086
3087 // THEN the state in dpms is not changed
3088 assertTrue(dpms.hasUserSetupCompleted());
3089 }
3090
3091 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3092 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3093 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3094
3095 final int userId = UserHandle.USER_SYSTEM;
3096 // GIVEN userComplete is false in SettingsProvider
3097 setUserSetupCompleteForUser(false, userId);
3098
3099 // GIVEN userComplete is true in DPM
3100 DevicePolicyManagerService.DevicePolicyData userData =
3101 new DevicePolicyManagerService.DevicePolicyData(userId);
3102 userData.mUserSetupComplete = true;
3103 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3104
3105 // GIVEN it's userdebug build
3106 mContext.buildMock.isDebuggable = true;
3107
3108 assertTrue(dpms.hasUserSetupCompleted());
3109
3110 dpm.forceUpdateUserSetupComplete();
3111
3112 // THEN the state in dpms is not changed
3113 assertFalse(dpms.hasUserSetupCompleted());
3114 }
3115
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003116 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003117 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003118 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3119 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
3120 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
3121 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003122 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003123 }
3124
3125 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3126 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3127 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003128
3129 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3130 // feature is disabled because there are non-affiliated secondary users.
3131 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003132 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3133 .thenReturn(true);
3134
3135 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003136 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003137
3138 // Enabling logging should not change the timestamp.
3139 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003140 verify(mContext.settings)
3141 .securityLogSetLoggingEnabledProperty(true);
3142 when(mContext.settings.securityLogGetLoggingEnabledProperty())
3143 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003144 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003145
3146 // Retrieving the logs should update the timestamp.
3147 final long beforeRetrieval = System.currentTimeMillis();
3148 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003149 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003150 final long afterRetrieval = System.currentTimeMillis();
3151 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3152 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3153
3154 // Retrieving the pre-boot logs should update the timestamp.
3155 Thread.sleep(2);
3156 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003157 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003158 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3159
3160 // Checking the timestamp again should not change it.
3161 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003162 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003163
3164 // Retrieving the logs again should update the timestamp.
3165 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003166 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003167 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3168
3169 // Disabling logging should not change the timestamp.
3170 Thread.sleep(2);
3171 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003172 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003173
3174 // Restarting the DPMS should not lose the timestamp.
3175 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003176 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003177
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003178 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3179 mContext.binder.callingUid = 1234567;
3180 mContext.callerPermissions.add(permission.MANAGE_USERS);
3181 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3182 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3183
3184 // System can retrieve the timestamp.
3185 mContext.binder.clearCallingIdentity();
3186 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3187
3188 // Removing the device owner should clear the timestamp.
3189 clearDeviceOwner();
3190 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003191 }
3192
3193 public void testGetLastBugReportRequestTime() throws Exception {
3194 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3195 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003196
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003197 mContext.packageName = admin1.getPackageName();
3198 mContext.applicationInfo = new ApplicationInfo();
3199 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3200 .thenReturn(Color.WHITE);
3201 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3202 anyObject())).thenReturn(Color.WHITE);
3203
Esteban Talaverad36dd152016-12-15 08:51:45 +00003204 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3205 // feature is disabled because there are non-affiliated secondary users.
3206 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3207
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003208 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003209 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003210
3211 // Requesting a bug report should update the timestamp.
3212 final long beforeRequest = System.currentTimeMillis();
3213 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003214 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003215 final long afterRequest = System.currentTimeMillis();
3216 assertTrue(bugReportRequestTime >= beforeRequest);
3217 assertTrue(bugReportRequestTime <= afterRequest);
3218
3219 // Checking the timestamp again should not change it.
3220 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003221 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003222
3223 // Restarting the DPMS should not lose the timestamp.
3224 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003225 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003226
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003227 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3228 mContext.binder.callingUid = 1234567;
3229 mContext.callerPermissions.add(permission.MANAGE_USERS);
3230 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3231 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3232
3233 // System can retrieve the timestamp.
3234 mContext.binder.clearCallingIdentity();
3235 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3236
3237 // Removing the device owner should clear the timestamp.
3238 clearDeviceOwner();
3239 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003240 }
3241
3242 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3243 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3244 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003245 mContext.packageName = admin1.getPackageName();
3246 mContext.applicationInfo = new ApplicationInfo();
3247 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3248 .thenReturn(Color.WHITE);
3249 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3250 anyObject())).thenReturn(Color.WHITE);
3251
3252 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3253 // feature is disabled because there are non-affiliated secondary users.
3254 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003255 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3256 .thenReturn(true);
3257
3258 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003259 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003260
3261 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3262 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003263 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003264
3265 // Enabling logging should not change the timestamp.
3266 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003267 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003268
3269 // Retrieving the logs should update the timestamp.
3270 final long beforeRetrieval = System.currentTimeMillis();
3271 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003272 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003273 final long afterRetrieval = System.currentTimeMillis();
3274 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3275 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3276
3277 // Checking the timestamp again should not change it.
3278 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003279 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003280
3281 // Retrieving the logs again should update the timestamp.
3282 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003283 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003284 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3285
3286 // Disabling logging should not change the timestamp.
3287 Thread.sleep(2);
3288 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003289 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003290
3291 // Restarting the DPMS should not lose the timestamp.
3292 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003293 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3294
3295 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3296 mContext.binder.callingUid = 1234567;
3297 mContext.callerPermissions.add(permission.MANAGE_USERS);
3298 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3299 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3300
3301 // System can retrieve the timestamp.
3302 mContext.binder.clearCallingIdentity();
3303 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3304
3305 // Removing the device owner should clear the timestamp.
3306 clearDeviceOwner();
3307 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003308 }
3309
Tony Mak2f26b792016-11-28 17:54:51 +00003310 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3311 // Setup device owner.
3312 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3313 setupDeviceOwner();
3314
3315 // Only device owner is setup, the result list should be empty.
3316 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3317 MoreAsserts.assertEmpty(targetUsers);
3318
3319 // Setup a managed profile managed by the same admin.
3320 final int MANAGED_PROFILE_USER_ID = 15;
3321 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3322 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3323
3324 // Add a secondary user, it should never talk with.
3325 final int ANOTHER_USER_ID = 36;
3326 mContext.addUser(ANOTHER_USER_ID, 0);
3327
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003328 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3329 // other.
3330 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3331 MoreAsserts.assertEmpty(targetUsers);
3332
3333 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3334 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3335 MoreAsserts.assertEmpty(targetUsers);
3336
3337 // Setting affiliation ids
3338 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3339 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3340 dpm.setAffiliationIds(admin1, userAffiliationIds);
3341
3342 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3343 dpm.setAffiliationIds(admin1, userAffiliationIds);
3344
Tony Mak2f26b792016-11-28 17:54:51 +00003345 // Calling from device owner admin, the result list should just contain the managed
3346 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003347 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003348 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3349 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3350
3351 // Calling from managed profile admin, the result list should just contain the system
3352 // user id.
3353 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3354 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3355 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003356
3357 // Changing affiliation ids in one
3358 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3359
3360 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3361 // to each other.
3362 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3363 MoreAsserts.assertEmpty(targetUsers);
3364
3365 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3366 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3367 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003368 }
3369
3370 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3371 // Setup a device owner.
3372 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3373 setupDeviceOwner();
3374
3375 // Set up a managed profile managed by different package.
3376 final int MANAGED_PROFILE_USER_ID = 15;
3377 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3378 final ComponentName adminDifferentPackage =
3379 new ComponentName("another.package", "whatever.class");
3380 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3381
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003382 // Setting affiliation ids
3383 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3384 dpm.setAffiliationIds(admin1, userAffiliationIds);
3385
3386 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3387 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3388
Tony Mak2f26b792016-11-28 17:54:51 +00003389 // Calling from device owner admin, we should get zero bind device admin target users as
3390 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003391 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003392 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3393 MoreAsserts.assertEmpty(targetUsers);
3394
3395 // Calling from managed profile admin, we should still get zero target users for the same
3396 // reason.
3397 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3398 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3399 MoreAsserts.assertEmpty(targetUsers);
3400 }
3401
Esteban Talaverabdcada92017-02-01 14:20:06 +00003402 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3403 // Setup a device owner.
3404 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3405 setupDeviceOwner();
3406 // Lock task packages are updated when loading user data.
3407 verify(mContext.iactivityManager)
3408 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3409
3410 // Set up a managed profile managed by different package (package name shouldn't matter)
3411 final int MANAGED_PROFILE_USER_ID = 15;
3412 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3413 final ComponentName adminDifferentPackage =
3414 new ComponentName("another.package", "whatever.class");
3415 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3416 verify(mContext.iactivityManager)
3417 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3418
3419 // The DO can still set lock task packages
3420 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3421 final String[] doPackages = {"doPackage1", "doPackage2"};
3422 dpm.setLockTaskPackages(admin1, doPackages);
3423 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3424 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3425 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3426 verify(mContext.iactivityManager)
3427 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3428
3429 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3430 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3431 final String[] poPackages = {"poPackage1", "poPackage2"};
3432 try {
3433 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3434 fail("Didn't throw expected security exception.");
3435 } catch (SecurityException expected) {
3436 }
3437 try {
3438 dpm.getLockTaskPackages(adminDifferentPackage);
3439 fail("Didn't throw expected security exception.");
3440 } catch (SecurityException expected) {
3441 }
3442 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3443
3444 // Setting same affiliation ids
3445 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3446 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3447 dpm.setAffiliationIds(admin1, userAffiliationIds);
3448
3449 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3450 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3451
3452 // Now the managed profile can set lock task packages.
3453 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3454 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3455 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3456 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
3457 verify(mContext.iactivityManager)
3458 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3459
3460 // Unaffiliate the profile, lock task mode no longer available on the profile.
3461 dpm.setAffiliationIds(adminDifferentPackage, Collections.<String>emptyList());
3462 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3463 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
3464 verify(mContext.iactivityManager, times(2))
3465 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3466
3467 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3468 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3469 }
3470
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003471 public void testIsDeviceManaged() throws Exception {
3472 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3473 setupDeviceOwner();
3474
3475 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3476 // find out that the device has a device owner.
3477 assertTrue(dpm.isDeviceManaged());
3478 mContext.binder.callingUid = 1234567;
3479 mContext.callerPermissions.add(permission.MANAGE_USERS);
3480 assertTrue(dpm.isDeviceManaged());
3481 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3482 mContext.binder.clearCallingIdentity();
3483 assertTrue(dpm.isDeviceManaged());
3484
3485 clearDeviceOwner();
3486
3487 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3488 // not have a device owner.
3489 mContext.binder.callingUid = 1234567;
3490 mContext.callerPermissions.add(permission.MANAGE_USERS);
3491 assertFalse(dpm.isDeviceManaged());
3492 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3493 mContext.binder.clearCallingIdentity();
3494 assertFalse(dpm.isDeviceManaged());
3495 }
3496
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003497 public void testDeviceOwnerOrganizationName() throws Exception {
3498 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3499 setupDeviceOwner();
3500
3501 dpm.setOrganizationName(admin1, "organization");
3502
3503 // Device owner can retrieve organization managing the device.
3504 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3505
3506 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3507 mContext.binder.callingUid = 1234567;
3508 mContext.callerPermissions.add(permission.MANAGE_USERS);
3509 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3510 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3511
3512 // System can retrieve organization managing the device.
3513 mContext.binder.clearCallingIdentity();
3514 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3515
3516 // Removing the device owner clears the organization managing the device.
3517 clearDeviceOwner();
3518 assertNull(dpm.getDeviceOwnerOrganizationName());
3519 }
3520
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003521 public void testWipeDataManagedProfile() throws Exception {
3522 final int MANAGED_PROFILE_USER_ID = 15;
3523 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3524 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3525 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3526
3527 // Even if the caller is the managed profile, the current user is the user 0
3528 when(mContext.iactivityManager.getCurrentUser())
3529 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3530
3531 dpm.wipeData(0);
3532 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3533 MANAGED_PROFILE_USER_ID);
3534 }
3535
3536 public void testWipeDataManagedProfileDisallowed() throws Exception {
3537 final int MANAGED_PROFILE_USER_ID = 15;
3538 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3539 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3540
3541 // Even if the caller is the managed profile, the current user is the user 0
3542 when(mContext.iactivityManager.getCurrentUser())
3543 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3544
3545 when(mContext.userManager.getUserRestrictionSource(
3546 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3547 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3548 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3549 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3550 try {
3551 // The PO is not allowed to remove the profile if the user restriction was set on the
3552 // profile by the system
3553 dpm.wipeData(0);
3554 fail("SecurityException not thrown");
3555 } catch (SecurityException expected) {
3556 }
3557 }
3558
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003559 public void testWipeDataDeviceOwner() throws Exception {
3560 setDeviceOwner();
3561 when(mContext.userManager.getUserRestrictionSource(
3562 UserManager.DISALLOW_FACTORY_RESET,
3563 UserHandle.SYSTEM))
3564 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3565
3566 dpm.wipeData(0);
3567 verify(mContext.recoverySystem).rebootWipeUserData(
3568 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3569 }
3570
3571 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3572 setDeviceOwner();
3573 when(mContext.userManager.getUserRestrictionSource(
3574 UserManager.DISALLOW_FACTORY_RESET,
3575 UserHandle.SYSTEM))
3576 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3577 try {
3578 // The DO is not allowed to wipe the device if the user restriction was set
3579 // by the system
3580 dpm.wipeData(0);
3581 fail("SecurityException not thrown");
3582 } catch (SecurityException expected) {
3583 }
3584 }
3585
3586 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3587 final int MANAGED_PROFILE_USER_ID = 15;
3588 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3589 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3590
3591 // Even if the caller is the managed profile, the current user is the user 0
3592 when(mContext.iactivityManager.getCurrentUser())
3593 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3594
3595 when(mContext.userManager.getUserRestrictionSource(
3596 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3597 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3598 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3599
3600 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3601 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3602
3603 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3604 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3605 // Failed password attempts on the parent user are taken into account, as there isn't a
3606 // separate work challenge.
3607 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3608 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3609 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3610
3611 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3612 // both the user restriction and the policy were set by the PO.
3613 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3614 MANAGED_PROFILE_USER_ID);
3615 verifyZeroInteractions(mContext.recoverySystem);
3616 }
3617
3618 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3619 throws Exception {
3620 final int MANAGED_PROFILE_USER_ID = 15;
3621 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3622 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3623
3624 // Even if the caller is the managed profile, the current user is the user 0
3625 when(mContext.iactivityManager.getCurrentUser())
3626 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3627
3628 when(mContext.userManager.getUserRestrictionSource(
3629 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3630 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3631 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3632
3633 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3634 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3635
3636 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3637 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3638 // Failed password attempts on the parent user are taken into account, as there isn't a
3639 // separate work challenge.
3640 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3641 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3642 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3643
3644 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3645 // not wiped.
3646 verify(mContext.userManagerInternal, never())
3647 .removeUserEvenWhenDisallowed(anyInt());
3648 verifyZeroInteractions(mContext.recoverySystem);
3649 }
3650
3651 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3652 setDeviceOwner();
3653 when(mContext.userManager.getUserRestrictionSource(
3654 UserManager.DISALLOW_FACTORY_RESET,
3655 UserHandle.SYSTEM))
3656 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3657
3658 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3659
3660 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3661 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3662 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3663 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3664 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3665
3666 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3667 // user restriction and the policy were set by the DO.
3668 verify(mContext.recoverySystem).rebootWipeUserData(
3669 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3670 }
3671
3672 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3673 setDeviceOwner();
3674 when(mContext.userManager.getUserRestrictionSource(
3675 UserManager.DISALLOW_FACTORY_RESET,
3676 UserHandle.SYSTEM))
3677 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3678
3679 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3680
3681 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3682 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3683 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3684 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3685 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3686
3687 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
3688 verifyZeroInteractions(mContext.recoverySystem);
3689 verify(mContext.userManagerInternal, never())
3690 .removeUserEvenWhenDisallowed(anyInt());
3691 }
3692
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003693 public void testGetPermissionGrantState() throws Exception {
3694 final String permission = "some.permission";
3695 final String app1 = "com.example.app1";
3696 final String app2 = "com.example.app2";
3697
3698 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3699 .thenReturn(PackageManager.PERMISSION_GRANTED);
3700 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3701 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3702 when(mContext.packageManager.getPermissionFlags(permission, app1,
3703 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3704 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3705 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3706 .thenReturn(PackageManager.PERMISSION_DENIED);
3707 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3708 UserHandle.SYSTEM);
3709 when(mContext.packageManager.getPermissionFlags(permission, app2,
3710 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3711
3712 // System can retrieve permission grant state.
3713 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003714 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003715 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3716 dpm.getPermissionGrantState(null, app1, permission));
3717 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3718 dpm.getPermissionGrantState(null, app2, permission));
3719
3720 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003721 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3722 mContext.packageName = app1;
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003723 try {
3724 dpm.getPermissionGrantState(null, app1, permission);
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003725 fail("Didn't throw SecurityException");
3726 } catch (SecurityException expected) {
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003727 }
3728
3729 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003730 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3731 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003732 setAsProfileOwner(admin1);
3733 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3734 dpm.getPermissionGrantState(admin1, app1, permission));
3735 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3736 dpm.getPermissionGrantState(admin1, app2, permission));
3737 }
3738
Rubin Xuaab7a412016-12-30 21:13:29 +00003739 public void testResetPasswordWithToken() throws Exception {
3740 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3741 setupDeviceOwner();
3742 // test token validation
3743 try {
3744 dpm.setResetPasswordToken(admin1, new byte[31]);
3745 fail("should not have accepted tokens too short");
3746 } catch (IllegalArgumentException expected) {
3747 }
3748 // test adding a token
3749 final byte[] token = new byte[32];
3750 final long handle = 123456;
3751 final String password = "password";
3752 when(mContext.lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
3753 .thenReturn(handle);
3754 assertTrue(dpm.setResetPasswordToken(admin1, token));
3755
3756 // test password activation
3757 when(mContext.lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
3758 .thenReturn(true);
3759 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3760
3761 // test reset password with token
3762 when(mContext.lockPatternUtils.setLockCredentialWithToken(eq(password),
3763 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3764 eq(UserHandle.USER_SYSTEM)))
3765 .thenReturn(true);
3766 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3767
3768 // test removing a token
3769 when(mContext.lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
3770 .thenReturn(true);
3771 assertTrue(dpm.clearResetPasswordToken(admin1));
3772 }
3773
Victor Chang3e794af2016-03-04 13:48:17 +00003774 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
3775 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
3776 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
3777 dpms.notifyChangeToContentObserver(
3778 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
3779 }
3780
3781 private void assertProvisioningAllowed(String action, boolean expected) {
3782 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
3783 dpm.isProvisioningAllowed(action));
3784 }
Tony Mak2f26b792016-11-28 17:54:51 +00003785
Nicolas Prevot45d29072017-01-18 16:11:19 +00003786 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
3787 int uid) {
3788 String previousPackageName = mContext.packageName;
3789 int previousUid = mMockContext.binder.callingUid;
3790
3791 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
3792 mContext.packageName = packageName;
3793 mMockContext.binder.callingUid = uid;
3794 assertProvisioningAllowed(action, expected);
3795
3796 // Set the previous package name / calling uid to go back to the initial state.
3797 mContext.packageName = previousPackageName;
3798 mMockContext.binder.callingUid = previousUid;
3799 }
3800
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003801 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00003802 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
3803 }
3804
3805 private void assertCheckProvisioningPreCondition(
3806 String action, String packageName, int provisioningCondition) {
3807 assertEquals("checkProvisioningPreCondition("
3808 + action + ", " + packageName + ") returning unexpected result",
3809 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003810 }
3811
Tony Mak2f26b792016-11-28 17:54:51 +00003812 /**
3813 * Setup a managed profile with the specified admin and its uid.
3814 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
3815 * @param adminUid uid of the admin package.
3816 * @param copyFromAdmin package information for {@code admin} will be built based on this
3817 * component's information.
3818 */
3819 private void addManagedProfile(
3820 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
3821 final int userId = UserHandle.getUserId(adminUid);
3822 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
3823 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3824 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
3825 dpm.setActiveAdmin(admin, false, userId);
3826 assertTrue(dpm.setProfileOwner(admin, null, userId));
3827 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3828 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00003829
3830 /**
3831 * Convert String[] to ParceledListSlice&lt;ParcelableString&gt;.
3832 * <p>
3833 * TODO: This shouldn't be necessary. If ParcelableString does need to exist, it also needs
3834 * a real constructor.
3835 */
3836 private static ParceledListSlice<ParcelableString> asSlice(String[] s) {
3837 List<ParcelableString> list = new ArrayList<>(s.length);
3838 for (int i = 0; i < s.length; i++) {
3839 ParcelableString item = new ParcelableString();
3840 item.string = s[i];
3841 list.add(i, item);
3842 }
3843 return new ParceledListSlice<ParcelableString>(list);
3844 }
Victor Chang3e794af2016-03-04 13:48:17 +00003845}