blob: 57105306911187faace4fa36040b8fc5c3cd0e59 [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;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +010041import android.net.Uri;
Tony Mak2f26b792016-11-28 17:54:51 +000042import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080043import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080044import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070045import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000046import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080047import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070048import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070049import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010050import android.os.UserManagerInternal;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080051import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000052import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080053import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000054import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010055import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070056import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070057
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010058import com.android.internal.R;
Robin Lee7f5c91c2017-02-08 21:27:02 +000059import com.android.internal.util.ParcelableString;
Rubin Xuaab7a412016-12-30 21:13:29 +000060import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000061import com.android.server.LocalServices;
62import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000063import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000064
Robin Lee7f5c91c2017-02-08 21:27:02 +000065import org.hamcrest.BaseMatcher;
66import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070067import org.mockito.invocation.InvocationOnMock;
68import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070069
Makoto Onukic8a5a552015-11-19 14:29:12 -080070import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000071import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000072import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070073import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070074import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070075import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010076import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000077import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070078
Edman Anjosf9946772016-11-28 16:35:15 +010079import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
80import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
81
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070082import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070083import static org.mockito.Matchers.anyInt;
Michal Karpinskid084ca52017-01-18 15:54:18 +000084import static org.mockito.Matchers.anyLong;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010085import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070086import static org.mockito.Matchers.anyString;
Robin Lee7f5c91c2017-02-08 21:27:02 +000087import static org.mockito.Matchers.argThat;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070088import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070089import static org.mockito.Matchers.isNull;
Esteban Talavera548a04b2016-12-20 15:22:30 +000090import static org.mockito.Mockito.atLeast;
Makoto Onukib643fb02015-09-22 15:03:44 -070091import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070092import static org.mockito.Mockito.doReturn;
Robin Lee7f5c91c2017-02-08 21:27:02 +000093import static org.mockito.Mockito.mock;
Robin Leed2a73ed2016-12-19 09:07:16 +000094import static org.mockito.Mockito.never;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080095import static org.mockito.Mockito.reset;
Robin Lee7f5c91c2017-02-08 21:27:02 +000096import static org.mockito.Mockito.timeout;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070097import static org.mockito.Mockito.times;
98import static org.mockito.Mockito.verify;
Esteban Talaverab88f42b2017-01-24 16:47:16 +000099import static org.mockito.Mockito.verifyZeroInteractions;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100import static org.mockito.Mockito.when;
101
102/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700103 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000104 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700105 m FrameworksServicesTests &&
106 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000107 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800109 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700110
111 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000112 *
113 * , or:
114 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000116@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000118 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
119 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
120 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
121
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700122 private DpmMockContext mContext;
123 public DevicePolicyManager dpm;
124 public DevicePolicyManagerServiceTestable dpms;
125
126 @Override
127 protected void setUp() throws Exception {
128 super.setUp();
129
130 mContext = getContext();
131
132 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
133 .thenReturn(true);
134
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800135 // By default, pretend all users are running and unlocked.
136 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
137
Makoto Onukia52562c2015-10-01 16:12:31 -0700138 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700139
Makoto Onukid932f762015-09-29 16:53:38 -0700140 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
141 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
142 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800143 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700144
Makoto Onukib643fb02015-09-22 15:03:44 -0700145 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700146 }
147
Makoto Onukia52562c2015-10-01 16:12:31 -0700148 private void initializeDpms() {
149 // Need clearCallingIdentity() to pass permission checks.
150 final long ident = mContext.binder.clearCallingIdentity();
151 try {
152 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
153
154 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
155
156 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
157 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
158
159 dpm = new DevicePolicyManagerTestable(mContext, dpms);
160 } finally {
161 mContext.binder.restoreCallingIdentity(ident);
162 }
163 }
164
Makoto Onukib643fb02015-09-22 15:03:44 -0700165 private void setUpUserManager() {
166 // Emulate UserManager.set/getApplicationRestriction().
167 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
168
169 // UM.setApplicationRestrictions() will save to appRestrictions.
170 doAnswer(new Answer<Void>() {
171 @Override
172 public Void answer(InvocationOnMock invocation) throws Throwable {
173 String pkg = (String) invocation.getArguments()[0];
174 Bundle bundle = (Bundle) invocation.getArguments()[1];
175 UserHandle user = (UserHandle) invocation.getArguments()[2];
176
177 appRestrictions.put(Pair.create(pkg, user), bundle);
178
179 return null;
180 }
181 }).when(mContext.userManager).setApplicationRestrictions(
182 anyString(), any(Bundle.class), any(UserHandle.class));
183
184 // UM.getApplicationRestrictions() will read from appRestrictions.
185 doAnswer(new Answer<Bundle>() {
186 @Override
187 public Bundle answer(InvocationOnMock invocation) throws Throwable {
188 String pkg = (String) invocation.getArguments()[0];
189 UserHandle user = (UserHandle) invocation.getArguments()[1];
190
191 return appRestrictions.get(Pair.create(pkg, user));
192 }
193 }).when(mContext.userManager).getApplicationRestrictions(
194 anyString(), any(UserHandle.class));
195
Makoto Onukid932f762015-09-29 16:53:38 -0700196 // Add the first secondary user.
197 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700198 }
199
200 private void setAsProfileOwner(ComponentName admin) {
201 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
202 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
203
Makoto Onukia4f11972015-10-01 13:19:58 -0700204 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700205 dpm.setActiveAdmin(admin, /* replace =*/ false);
206
207 // Fire!
208 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
209
210 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700211 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700212 }
213
214 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700215 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
216 .thenReturn(false);
217
218 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
219 new DevicePolicyManagerServiceTestable(mContext, dataDir);
220
221 // If the device has no DPMS feature, it shouldn't register the local service.
222 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
223 }
224
225 /**
226 * Caller doesn't have proper permissions.
227 */
228 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700229 // 1. Failure cases.
230
231 // Caller doesn't have MANAGE_DEVICE_ADMINS.
232 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700233 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700234 fail("Didn't throw SecurityException");
235 } catch (SecurityException expected) {
236 }
237
238 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
239 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
240 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700241 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700242 fail("Didn't throw SecurityException");
243 } catch (SecurityException expected) {
244 }
245 }
246
Makoto Onukif76b06a2015-09-22 15:03:44 -0700247 /**
248 * Test for:
249 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800250 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700251 * {@link DevicePolicyManager#isAdminActive}
252 * {@link DevicePolicyManager#isAdminActiveAsUser}
253 * {@link DevicePolicyManager#getActiveAdmins}
254 * {@link DevicePolicyManager#getActiveAdminsAsUser}
255 */
256 public void testSetActiveAdmin() throws Exception {
257 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700258 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
259
Makoto Onukif76b06a2015-09-22 15:03:44 -0700260 // 2. Call the API.
261 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700262
263 // 3. Verify internal calls.
264
265 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700266 verify(mContext.spiedContext).sendBroadcastAsUser(
267 MockUtils.checkIntentAction(
268 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
269 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
270 verify(mContext.spiedContext).sendBroadcastAsUser(
271 MockUtils.checkIntentAction(
272 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700273 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
274
Makoto Onukif76b06a2015-09-22 15:03:44 -0700275 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
276 eq(admin1.getPackageName()),
277 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
278 eq(PackageManager.DONT_KILL_APP),
279 eq(DpmMockContext.CALLER_USER_HANDLE),
280 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700281
282 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700283
284 // Make sure it's active admin1.
285 assertTrue(dpm.isAdminActive(admin1));
286 assertFalse(dpm.isAdminActive(admin2));
287 assertFalse(dpm.isAdminActive(admin3));
288
289 // But not admin1 for a different user.
290
291 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
292 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
293 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
294
295 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
296 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
297
298 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
299
300 // Next, add one more admin.
301 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700302 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
303 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700304
305 dpm.setActiveAdmin(admin2, /* replace =*/ false);
306
307 // Now we have two admins.
308 assertTrue(dpm.isAdminActive(admin1));
309 assertTrue(dpm.isAdminActive(admin2));
310 assertFalse(dpm.isAdminActive(admin3));
311
312 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
313 // again. (times(1) because it was previously called for admin1)
314 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
315 eq(admin1.getPackageName()),
316 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
317 eq(PackageManager.DONT_KILL_APP),
318 eq(DpmMockContext.CALLER_USER_HANDLE),
319 anyString());
320
321 // 4. Add the same admin1 again without replace, which should throw.
322 try {
323 dpm.setActiveAdmin(admin1, /* replace =*/ false);
324 fail("Didn't throw");
325 } catch (IllegalArgumentException expected) {
326 }
327
328 // 5. Add the same admin1 again with replace, which should succeed.
329 dpm.setActiveAdmin(admin1, /* replace =*/ true);
330
331 // TODO make sure it's replaced.
332
333 // 6. Test getActiveAdmins()
334 List<ComponentName> admins = dpm.getActiveAdmins();
335 assertEquals(2, admins.size());
336 assertEquals(admin1, admins.get(0));
337 assertEquals(admin2, admins.get(1));
338
339 // Another user has no admins.
340 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
341
342 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
343 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
344
345 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
346 }
347
Makoto Onukid932f762015-09-29 16:53:38 -0700348 public void testSetActiveAdmin_multiUsers() throws Exception {
349
350 final int ANOTHER_USER_ID = 100;
351 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
352
353 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
354
355 // Set up pacakge manager for the other user.
356 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700357
358 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
359
360 dpm.setActiveAdmin(admin1, /* replace =*/ false);
361
362 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
363 dpm.setActiveAdmin(admin2, /* replace =*/ false);
364
365
366 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
367 assertTrue(dpm.isAdminActive(admin1));
368 assertFalse(dpm.isAdminActive(admin2));
369
370 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
371 assertFalse(dpm.isAdminActive(admin1));
372 assertTrue(dpm.isAdminActive(admin2));
373 }
374
Makoto Onukif76b06a2015-09-22 15:03:44 -0700375 /**
376 * Test for:
377 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800378 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700379 */
380 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
381 // 1. Make sure the caller has proper permissions.
382 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
383
384 dpm.setActiveAdmin(admin1, /* replace =*/ false);
385 assertTrue(dpm.isAdminActive(admin1));
386
387 // Add the same admin1 again without replace, which should throw.
388 try {
389 dpm.setActiveAdmin(admin1, /* replace =*/ false);
390 fail("Didn't throw");
391 } catch (IllegalArgumentException expected) {
392 }
393 }
394
395 /**
396 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800397 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
398 * BIND_DEVICE_ADMIN.
399 */
400 public void testSetActiveAdmin_permissionCheck() throws Exception {
401 // 1. Make sure the caller has proper permissions.
402 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
403
404 try {
405 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
406 fail();
407 } catch (IllegalArgumentException expected) {
408 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
409 }
410 assertFalse(dpm.isAdminActive(adminNoPerm));
411
412 // Change the target API level to MNC. Now it can be set as DA.
413 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
414 VERSION_CODES.M);
415 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
416 assertTrue(dpm.isAdminActive(adminNoPerm));
417
418 // TODO Test the "load from the file" case where DA will still be loaded even without
419 // BIND_DEVICE_ADMIN and target API is N.
420 }
421
422 /**
423 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700424 * {@link DevicePolicyManager#removeActiveAdmin}
425 */
426 public void testRemoveActiveAdmin_SecurityException() {
427 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
428
429 // Add admin.
430
431 dpm.setActiveAdmin(admin1, /* replace =*/ false);
432
433 assertTrue(dpm.isAdminActive(admin1));
434
435 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
436
437 // Directly call the DPMS method with a different userid, which should fail.
438 try {
439 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
440 fail("Didn't throw SecurityException");
441 } catch (SecurityException expected) {
442 }
443
444 // Try to remove active admin with a different caller userid should fail too, without
445 // having MANAGE_DEVICE_ADMINS.
446 mContext.callerPermissions.clear();
447
Makoto Onukid932f762015-09-29 16:53:38 -0700448 // Change the caller, and call into DPMS directly with a different user-id.
449
Makoto Onukif76b06a2015-09-22 15:03:44 -0700450 mContext.binder.callingUid = 1234567;
451 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700452 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700453 fail("Didn't throw SecurityException");
454 } catch (SecurityException expected) {
455 }
456 }
457
458 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800459 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
460 * (because we can't send the remove broadcast).
461 */
462 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
463 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
464
465 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
466
467 // Add admin.
468
469 dpm.setActiveAdmin(admin1, /* replace =*/ false);
470
471 assertTrue(dpm.isAdminActive(admin1));
472
473 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
474
475 // 1. User not unlocked.
476 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
477 .thenReturn(false);
478 try {
479 dpm.removeActiveAdmin(admin1);
480 fail("Didn't throw IllegalStateException");
481 } catch (IllegalStateException expected) {
482 MoreAsserts.assertContainsRegex(
483 "User must be running and unlocked", expected.getMessage());
484 }
485
486 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
487
488 // 2. User unlocked.
489 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
490 .thenReturn(true);
491
492 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700493 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800494 }
495
496 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700497 * Test for:
498 * {@link DevicePolicyManager#removeActiveAdmin}
499 */
Makoto Onukid932f762015-09-29 16:53:38 -0700500 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700501 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
502
503 // Add admin1.
504
505 dpm.setActiveAdmin(admin1, /* replace =*/ false);
506
507 assertTrue(dpm.isAdminActive(admin1));
508 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
509
510 // Different user, but should work, because caller has proper permissions.
511 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700512
513 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700514 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700515
516 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700517 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700518
519 // TODO DO Still can't be removed in this case.
520 }
521
522 /**
523 * Test for:
524 * {@link DevicePolicyManager#removeActiveAdmin}
525 */
526 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
527 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
528 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
529
530 // Add admin1.
531
532 dpm.setActiveAdmin(admin1, /* replace =*/ false);
533
534 assertTrue(dpm.isAdminActive(admin1));
535 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
536
537 // Broadcast from saveSettingsLocked().
538 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
539 MockUtils.checkIntentAction(
540 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
541 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
542
543 // Remove. No permissions, but same user, so it'll work.
544 mContext.callerPermissions.clear();
545 dpm.removeActiveAdmin(admin1);
546
Makoto Onukif76b06a2015-09-22 15:03:44 -0700547 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
548 MockUtils.checkIntentAction(
549 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
550 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
551 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700552 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700553 eq(dpms.mHandler),
554 eq(Activity.RESULT_OK),
555 isNull(String.class),
556 isNull(Bundle.class));
557
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700558 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700559
560 // Again broadcast from saveSettingsLocked().
561 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
562 MockUtils.checkIntentAction(
563 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
564 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
565
566 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700567 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700568
569 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000570 * Test for: @{link DevicePolicyManager#setActivePasswordState}
571 *
572 * Validates that when the password for a user changes, the notification broadcast intent
573 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
574 * addition to ones in the original user.
575 */
576 public void testSetActivePasswordState_sendToProfiles() throws Exception {
577 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
578
579 final int MANAGED_PROFILE_USER_ID = 78;
580 final int MANAGED_PROFILE_ADMIN_UID =
581 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
582
583 // Setup device owner.
584 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
585 mContext.packageName = admin1.getPackageName();
586 setupDeviceOwner();
587
588 // Add a managed profile belonging to the system user.
589 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
590
591 // Change the parent user's password.
592 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
593
594 // Both the device owner and the managed profile owner should receive this broadcast.
595 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
596 intent.setComponent(admin1);
597 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
598
599 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
600 MockUtils.checkIntent(intent),
601 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
602 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
603 MockUtils.checkIntent(intent),
604 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
605 }
606
607 /**
608 * Test for: @{link DevicePolicyManager#setActivePasswordState}
609 *
610 * Validates that when the password for a managed profile changes, the notification broadcast
611 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
612 * its parent.
613 */
614 public void testSetActivePasswordState_notSentToParent() throws Exception {
615 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
616
617 final int MANAGED_PROFILE_USER_ID = 78;
618 final int MANAGED_PROFILE_ADMIN_UID =
619 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
620
621 // Setup device owner.
622 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
623 mContext.packageName = admin1.getPackageName();
624 doReturn(true).when(mContext.lockPatternUtils)
625 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
626 setupDeviceOwner();
627
628 // Add a managed profile belonging to the system user.
629 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
630
631 // Change the profile's password.
632 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
633
634 // Both the device owner and the managed profile owner should receive this broadcast.
635 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
636 intent.setComponent(admin1);
637 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
638
639 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
640 MockUtils.checkIntent(intent),
641 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
642 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
643 MockUtils.checkIntent(intent),
644 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
645 }
646 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000647 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700648 */
649 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000650 setDeviceOwner();
651
652 // Try to set a profile owner on the same user, which should fail.
653 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
654 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
655 try {
656 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
657 fail("IllegalStateException not thrown");
658 } catch (IllegalStateException expected) {
659 assertTrue("Message was: " + expected.getMessage(),
660 expected.getMessage().contains("already has a device owner"));
661 }
662
663 // DO admin can't be deactivated.
664 dpm.removeActiveAdmin(admin1);
665 assertTrue(dpm.isAdminActive(admin1));
666
667 // TODO Test getDeviceOwnerName() too. To do so, we need to change
668 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
669 }
670
671 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700672 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800673 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700674 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
675 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
676
Makoto Onukid932f762015-09-29 16:53:38 -0700677 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700678 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
679
Makoto Onukid932f762015-09-29 16:53:38 -0700680 // Make sure admin1 is installed on system user.
681 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700682
Makoto Onukic8a5a552015-11-19 14:29:12 -0800683 // Check various get APIs.
684 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
685
Makoto Onukib643fb02015-09-22 15:03:44 -0700686 // DO needs to be an DA.
687 dpm.setActiveAdmin(admin1, /* replace =*/ false);
688
689 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700690 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700691
Makoto Onukic8a5a552015-11-19 14:29:12 -0800692 // getDeviceOwnerComponent should return the admin1 component.
693 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
694 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
695
696 // Check various get APIs.
697 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
698
699 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
700 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
701 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
702 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
703
704 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
705
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000706 // Verify internal calls.
707 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
708 eq(admin1.getPackageName()));
709
Makoto Onukib643fb02015-09-22 15:03:44 -0700710 // TODO We should check if the caller has called clearCallerIdentity().
711 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
712 eq(UserHandle.USER_SYSTEM), eq(false));
713
714 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
715 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
716 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
717
Makoto Onukic8a5a552015-11-19 14:29:12 -0800718 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700719 }
720
Makoto Onukic8a5a552015-11-19 14:29:12 -0800721 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
722 final int origCallingUser = mContext.binder.callingUid;
723 final List origPermissions = new ArrayList(mContext.callerPermissions);
724 mContext.callerPermissions.clear();
725
726 mContext.callerPermissions.add(permission.MANAGE_USERS);
727
728 mContext.binder.callingUid = Process.SYSTEM_UID;
729
730 // TODO Test getDeviceOwnerName() too. To do so, we need to change
731 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
732 if (hasDeviceOwner) {
733 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
734 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
735 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
736
737 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
738 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
739 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
740 } else {
741 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
742 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
743 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
744
745 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
746 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
747 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
748 }
749
750 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
751 if (hasDeviceOwner) {
752 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
753 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
754 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
755
756 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
757 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
758 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
759 } else {
760 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
761 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
762 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
763
764 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
765 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
766 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
767 }
768
769 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
770 // Still with MANAGE_USERS.
771 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
772 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
773 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
774
775 if (hasDeviceOwner) {
776 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
777 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
778 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
779 } else {
780 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
781 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
782 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
783 }
784
785 mContext.binder.callingUid = Process.SYSTEM_UID;
786 mContext.callerPermissions.remove(permission.MANAGE_USERS);
787 // System can still call "OnAnyUser" without MANAGE_USERS.
788 if (hasDeviceOwner) {
789 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
790 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
791 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
792
793 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
794 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
795 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
796 } else {
797 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
798 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
799 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
800
801 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
802 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
803 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
804 }
805
806 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
807 // Still no MANAGE_USERS.
808 if (hasDeviceOwner) {
809 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
810 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
811 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
812 } else {
813 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
814 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
815 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
816 }
817
818 try {
819 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
820 fail();
821 } catch (SecurityException expected) {
822 }
823 try {
824 dpm.getDeviceOwnerComponentOnAnyUser();
825 fail();
826 } catch (SecurityException expected) {
827 }
828 try {
829 dpm.getDeviceOwnerUserId();
830 fail();
831 } catch (SecurityException expected) {
832 }
833 try {
834 dpm.getDeviceOwnerNameOnAnyUser();
835 fail();
836 } catch (SecurityException expected) {
837 }
838
839 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
840 // Still no MANAGE_USERS.
841 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
842 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
843 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
844
845 try {
846 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
847 fail();
848 } catch (SecurityException expected) {
849 }
850 try {
851 dpm.getDeviceOwnerComponentOnAnyUser();
852 fail();
853 } catch (SecurityException expected) {
854 }
855 try {
856 dpm.getDeviceOwnerUserId();
857 fail();
858 } catch (SecurityException expected) {
859 }
860 try {
861 dpm.getDeviceOwnerNameOnAnyUser();
862 fail();
863 } catch (SecurityException expected) {
864 }
865
866 // Restore.
867 mContext.binder.callingUid = origCallingUser;
868 mContext.callerPermissions.addAll(origPermissions);
869 }
870
871
Makoto Onukib643fb02015-09-22 15:03:44 -0700872 /**
873 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
874 */
875 public void testSetDeviceOwner_noSuchPackage() {
876 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800877 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700878 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
879 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
880
881 // Call from a process on the system user.
882 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
883
Makoto Onukib643fb02015-09-22 15:03:44 -0700884 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700885 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700886 fail("Didn't throw IllegalArgumentException");
887 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700888 assertTrue("Message was: " + expected.getMessage(),
889 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700890 }
891 }
892
893 public void testSetDeviceOwner_failures() throws Exception {
894 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
895 }
896
Makoto Onukia52562c2015-10-01 16:12:31 -0700897 public void testClearDeviceOwner() throws Exception {
898 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800899 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700900 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
901 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
902
903 // Set admin1 as a DA to the secondary user.
904 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
905
906 dpm.setActiveAdmin(admin1, /* replace =*/ false);
907
908 // Set admin 1 as the DO to the system user.
909
910 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
911 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
912 dpm.setActiveAdmin(admin1, /* replace =*/ false);
913 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
914
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000915 // Verify internal calls.
916 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
917 eq(admin1.getPackageName()));
918
Makoto Onukic8a5a552015-11-19 14:29:12 -0800919 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700920
Makoto Onuki90b89652016-01-28 14:44:18 -0800921 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
922
923 assertTrue(dpm.isAdminActive(admin1));
924 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
925
Makoto Onukia52562c2015-10-01 16:12:31 -0700926 // Set up other mocks.
927 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
928
929 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700930 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700931 eq(admin1.getPackageName()),
932 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800933
934 // But first pretend the user is locked. Then it should fail.
935 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
936 try {
937 dpm.clearDeviceOwnerApp(admin1.getPackageName());
938 fail("Didn't throw IllegalStateException");
939 } catch (IllegalStateException expected) {
940 MoreAsserts.assertContainsRegex(
941 "User must be running and unlocked", expected.getMessage());
942 }
943
944 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800945 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700946 dpm.clearDeviceOwnerApp(admin1.getPackageName());
947
948 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800949 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700950
Makoto Onuki90b89652016-01-28 14:44:18 -0800951 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
952 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100953 eq(null),
954 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800955
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700956 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100957
958 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
959 // and once for clearing it.
960 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
961 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
962 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700963 // TODO Check other calls.
964 }
965
966 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
967 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800968 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700969 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
970 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
971
972 // Set admin1 as a DA to the secondary user.
973 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
974
975 dpm.setActiveAdmin(admin1, /* replace =*/ false);
976
977 // Set admin 1 as the DO to the system user.
978
979 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
980 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
981 dpm.setActiveAdmin(admin1, /* replace =*/ false);
982 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
983
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000984 // Verify internal calls.
985 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
986 eq(admin1.getPackageName()));
987
Makoto Onukic8a5a552015-11-19 14:29:12 -0800988 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700989
990 // Now call clear from the secondary user, which should throw.
991 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
992
993 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700994 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700995 eq(admin1.getPackageName()),
996 anyInt());
997 try {
998 dpm.clearDeviceOwnerApp(admin1.getPackageName());
999 fail("Didn't throw");
1000 } catch (SecurityException e) {
1001 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
1002 }
1003
Makoto Onukic8a5a552015-11-19 14:29:12 -08001004 // DO shouldn't be removed.
1005 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001006 }
1007
Makoto Onukib643fb02015-09-22 15:03:44 -07001008 public void testSetProfileOwner() throws Exception {
1009 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001010
Makoto Onuki90b89652016-01-28 14:44:18 -08001011 // PO admin can't be deactivated.
1012 dpm.removeActiveAdmin(admin1);
1013 assertTrue(dpm.isAdminActive(admin1));
1014
Makoto Onuki803d6752015-10-30 12:58:39 -07001015 // Try setting DO on the same user, which should fail.
1016 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1017 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1018 try {
1019 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1020 fail("IllegalStateException not thrown");
1021 } catch (IllegalStateException expected) {
1022 assertTrue("Message was: " + expected.getMessage(),
1023 expected.getMessage().contains("already has a profile owner"));
1024 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001025 }
1026
Makoto Onuki90b89652016-01-28 14:44:18 -08001027 public void testClearProfileOwner() throws Exception {
1028 setAsProfileOwner(admin1);
1029
1030 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1031
1032 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1033 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1034
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001035 // First try when the user is locked, which should fail.
1036 when(mContext.userManager.isUserUnlocked(anyInt()))
1037 .thenReturn(false);
1038 try {
1039 dpm.clearProfileOwner(admin1);
1040 fail("Didn't throw IllegalStateException");
1041 } catch (IllegalStateException expected) {
1042 MoreAsserts.assertContainsRegex(
1043 "User must be running and unlocked", expected.getMessage());
1044 }
1045 // Clear, really.
1046 when(mContext.userManager.isUserUnlocked(anyInt()))
1047 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001048 dpm.clearProfileOwner(admin1);
1049
1050 // Check
1051 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001052 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001053 }
1054
Makoto Onukib643fb02015-09-22 15:03:44 -07001055 public void testSetProfileOwner_failures() throws Exception {
1056 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1057 }
1058
Makoto Onukia52562c2015-10-01 16:12:31 -07001059 public void testGetDeviceOwnerAdminLocked() throws Exception {
1060 checkDeviceOwnerWithMultipleDeviceAdmins();
1061 }
1062
1063 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1064 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1065 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1066 // make sure it gets the right component from the right user.
1067
1068 final int ANOTHER_USER_ID = 100;
1069 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1070
1071 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1072
1073 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001074 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001075 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1076 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1077
1078 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1079
Victor Change29cd472016-03-02 20:57:42 +00001080 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1081
Makoto Onukia52562c2015-10-01 16:12:31 -07001082 // Make sure the admin packge is installed to each user.
1083 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1084 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1085
1086 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1087 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1088
1089 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1090
1091
1092 // Set active admins to the users.
1093 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1094 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1095
1096 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1097 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1098
1099 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1100
1101 // Set DO on the first non-system user.
1102 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1103 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1104
Makoto Onukic8a5a552015-11-19 14:29:12 -08001105 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001106
1107 // Then check getDeviceOwnerAdminLocked().
1108 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1109 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1110 }
1111
1112 /**
1113 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001114 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1115 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001116 *
1117 * We didn't use to persist the DO component class name, but now we do, and the above method
1118 * finds the right component from a package name upon migration.
1119 */
1120 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001121 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001122 checkDeviceOwnerWithMultipleDeviceAdmins();
1123
1124 // Overwrite the device owner setting and clears the clas name.
1125 dpms.mOwners.setDeviceOwner(
1126 new ComponentName(admin2.getPackageName(), ""),
1127 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1128 dpms.mOwners.writeDeviceOwner();
1129
1130 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001131 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001132
1133 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001134 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1135 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001136 initializeDpms();
1137
1138 // Now the DO component name is a full name.
1139 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1140 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001141 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001142 }
1143
Makoto Onukib643fb02015-09-22 15:03:44 -07001144 public void testSetGetApplicationRestriction() {
1145 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001146 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001147
1148 {
1149 Bundle rest = new Bundle();
1150 rest.putString("KEY_STRING", "Foo1");
1151 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1152 }
1153
1154 {
1155 Bundle rest = new Bundle();
1156 rest.putString("KEY_STRING", "Foo2");
1157 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1158 }
1159
1160 {
1161 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1162 assertNotNull(returned);
1163 assertEquals(returned.size(), 1);
1164 assertEquals(returned.get("KEY_STRING"), "Foo1");
1165 }
1166
1167 {
1168 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1169 assertNotNull(returned);
1170 assertEquals(returned.size(), 1);
1171 assertEquals(returned.get("KEY_STRING"), "Foo2");
1172 }
1173
1174 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1175 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1176 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001177
Edman Anjosf9946772016-11-28 16:35:15 +01001178 /**
1179 * Setup a package in the package manager mock. Useful for faking installed applications.
1180 *
1181 * @param packageName the name of the package to be setup
1182 * @param appId the application ID to be given to the package
1183 * @return the UID of the package as known by the mock package manager
1184 */
1185 private int setupPackageInPackageManager(final String packageName, final int appId)
1186 throws Exception {
1187 // Make the PackageManager return the package instead of throwing a NameNotFoundException
1188 final PackageInfo pi = new PackageInfo();
1189 pi.applicationInfo = new ApplicationInfo();
1190 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1191 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1192 eq(packageName),
1193 anyInt(),
1194 eq(DpmMockContext.CALLER_USER_HANDLE));
1195 // Setup application UID with the PackageManager
1196 final int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, appId);
1197 doReturn(uid).when(mContext.packageManager).getPackageUidAsUser(
1198 eq(packageName),
1199 eq(DpmMockContext.CALLER_USER_HANDLE));
1200 // Associate packageName to uid
1201 doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid));
1202 doReturn(new String[]{packageName})
1203 .when(mContext.ipackageManager).getPackagesForUid(eq(uid));
1204 return uid;
1205 }
1206
Robin Lee7f5c91c2017-02-08 21:27:02 +00001207 public void testCertificateDisclosure() throws Exception {
1208 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1209 final UserHandle user = UserHandle.of(userId);
1210
1211 mContext.applicationInfo = new ApplicationInfo();
1212 mContext.callerPermissions.add(permission.MANAGE_USERS);
1213 mContext.packageName = "com.android.frameworks.servicestests";
1214 mContext.userContexts.put(user, mContext);
1215 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1216
1217 ParceledListSlice<ParcelableString> oneCert = asSlice(new String[] {"1"});
1218 ParceledListSlice<ParcelableString> fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
1219
1220 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1221 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1222
1223 // Given that we have exactly one certificate installed,
1224 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
1225 // when that certificate is approved,
1226 dpms.approveCaCert(oneCert.getList().get(0).string, userId, true);
1227 // a notification should not be shown.
1228 verify(mContext.notificationManager, timeout(1000))
1229 .cancelAsUser(anyString(), anyInt(), eq(user));
1230
1231 // Given that we have four certificates installed,
1232 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
1233 // when two of them are approved (one of them approved twice hence no action),
1234 dpms.approveCaCert(fourCerts.getList().get(0).string, userId, true);
1235 dpms.approveCaCert(fourCerts.getList().get(1).string, userId, true);
1236 // a notification should be shown saying that there are two certificates left to approve.
1237 verify(mContext.notificationManager, timeout(1000))
1238 .notifyAsUser(anyString(), anyInt(), argThat(
1239 new BaseMatcher<Notification>() {
1240 @Override
1241 public boolean matches(Object item) {
1242 final Notification noti = (Notification) item;
1243 return TEST_STRING.equals(
1244 noti.extras.getString(Notification.EXTRA_TITLE));
1245 }
1246 @Override
1247 public void describeTo(Description description) {
1248 description.appendText(
1249 "Notification{title=\"" + TEST_STRING + "\"}");
1250 }
1251 }), eq(user));
1252 }
1253
Edman Anjosf9946772016-11-28 16:35:15 +01001254 /**
1255 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1256 * privileges can acually be exercised by a delegate are not covered here.
1257 */
1258 public void testDelegation() throws Exception {
1259 setAsProfileOwner(admin1);
1260
1261 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1262
1263 // Given two packages
1264 final String CERT_DELEGATE = "com.delegate.certs";
1265 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1266 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1267 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1268 20989);
1269
1270 // On delegation
1271 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1272 mContext.packageName = admin1.getPackageName();
1273 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1274 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1275
1276 // DPMS correctly stores and retrieves the delegates
1277 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1278 assertEquals(2, policy.mDelegationMap.size());
1279 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1280 DELEGATION_CERT_INSTALL);
1281 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1282 DELEGATION_CERT_INSTALL);
1283 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1284 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1285 DELEGATION_APP_RESTRICTIONS);
1286 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1287 DELEGATION_APP_RESTRICTIONS);
1288 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1289
1290 // On calling install certificate APIs from an unauthorized process
1291 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1292 mContext.packageName = RESTRICTIONS_DELEGATE;
1293
1294 // DPMS throws a SecurityException
1295 try {
1296 dpm.installCaCert(null, null);
1297 fail("Didn't throw SecurityException on unauthorized access");
1298 } catch (SecurityException expected) {
1299 }
1300
1301 // On calling install certificate APIs from an authorized process
1302 mContext.binder.callingUid = CERT_DELEGATE_UID;
1303 mContext.packageName = CERT_DELEGATE;
1304
1305 // DPMS executes without a SecurityException
1306 try {
1307 dpm.installCaCert(null, null);
1308 } catch (SecurityException unexpected) {
1309 fail("Threw SecurityException on authorized access");
1310 } catch (NullPointerException expected) {
1311 }
1312
1313 // On removing a delegate
1314 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1315 mContext.packageName = admin1.getPackageName();
1316 dpm.setCertInstallerPackage(admin1, null);
1317
1318 // DPMS does not allow access to ex-delegate
1319 mContext.binder.callingUid = CERT_DELEGATE_UID;
1320 mContext.packageName = CERT_DELEGATE;
1321 try {
1322 dpm.installCaCert(null, null);
1323 fail("Didn't throw SecurityException on unauthorized access");
1324 } catch (SecurityException expected) {
1325 }
1326
1327 // But still allows access to other existing delegates
1328 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1329 mContext.packageName = RESTRICTIONS_DELEGATE;
1330 try {
1331 dpm.getApplicationRestrictions(null, "pkg");
1332 } catch (SecurityException expected) {
1333 fail("Threw SecurityException on authorized access");
1334 }
1335 }
1336
Esteban Talaverabf60f722015-12-10 16:26:44 +00001337 public void testApplicationRestrictionsManagingApp() throws Exception {
1338 setAsProfileOwner(admin1);
1339
Rubin Xued1928a2016-02-11 17:23:06 +00001340 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001341 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1342 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001343 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1344 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001345
Esteban Talaverabf60f722015-12-10 16:26:44 +00001346 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1347 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001348 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1349 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001350 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1351 Bundle rest = new Bundle();
1352 rest.putString("KEY_STRING", "Foo1");
1353 try {
1354 dpm.setApplicationRestrictions(null, "pkg1", rest);
1355 fail("Didn't throw expected SecurityException");
1356 } catch (SecurityException expected) {
1357 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001358 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1359 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001360 }
1361 try {
1362 dpm.getApplicationRestrictions(null, "pkg1");
1363 fail("Didn't throw expected SecurityException");
1364 } catch (SecurityException expected) {
1365 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001366 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1367 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001368 }
1369
1370 // Check via the profile owner that no restrictions were set.
1371 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001372 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001373 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1374
Rubin Xued1928a2016-02-11 17:23:06 +00001375 // Check the API does not allow setting a non-existent package
1376 try {
1377 dpm.setApplicationRestrictionsManagingPackage(admin1,
1378 nonExistAppRestrictionsManagerPackage);
1379 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001380 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001381 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001382 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001383 }
1384
Esteban Talaverabf60f722015-12-10 16:26:44 +00001385 // Let appRestrictionsManagerPackage manage app restrictions
1386 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1387 assertEquals(appRestrictionsManagerPackage,
1388 dpm.getApplicationRestrictionsManagingPackage(admin1));
1389
1390 // Now that package should be able to set and retrieve app restrictions.
1391 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001392 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001393 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1394 dpm.setApplicationRestrictions(null, "pkg1", rest);
1395 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1396 assertEquals(1, returned.size(), 1);
1397 assertEquals("Foo1", returned.get("KEY_STRING"));
1398
1399 // The same app running on a separate user shouldn't be able to manage app restrictions.
1400 mContext.binder.callingUid = UserHandle.getUid(
1401 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1402 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1403 try {
1404 dpm.setApplicationRestrictions(null, "pkg1", rest);
1405 fail("Didn't throw expected SecurityException");
1406 } catch (SecurityException expected) {
1407 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001408 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1409 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001410 }
1411
1412 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1413 // too.
1414 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001415 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001416 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1417 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1418 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1419
1420 // Removing the ability for the package to manage app restrictions.
1421 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1422 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1423 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001424 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001425 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1426 try {
1427 dpm.setApplicationRestrictions(null, "pkg1", null);
1428 fail("Didn't throw expected SecurityException");
1429 } catch (SecurityException expected) {
1430 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001431 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1432 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001433 }
1434 }
1435
Makoto Onukia4f11972015-10-01 13:19:58 -07001436 public void testSetUserRestriction_asDo() throws Exception {
1437 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001438 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001439 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1440 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1441
1442 // First, set DO.
1443
1444 // Call from a process on the system user.
1445 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1446
1447 // Make sure admin1 is installed on system user.
1448 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001449
1450 // Call.
1451 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001452 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001453 UserHandle.USER_SYSTEM));
1454
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001455 // Check that the user restrictions that are enabled by default are set. Then unset them.
1456 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001457 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001458 DpmTestUtils.assertRestrictions(
1459 DpmTestUtils.newRestrictions(defaultRestrictions),
1460 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1461 );
1462 DpmTestUtils.assertRestrictions(
1463 DpmTestUtils.newRestrictions(defaultRestrictions),
1464 dpm.getUserRestrictions(admin1)
1465 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001466 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1467 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001468 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001469 eq(true) /* isDeviceOwner */,
1470 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001471 );
1472 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001473
1474 for (String restriction : defaultRestrictions) {
1475 dpm.clearUserRestriction(admin1, restriction);
1476 }
1477
Esteban Talavera548a04b2016-12-20 15:22:30 +00001478 assertNoDeviceOwnerRestrictions();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001479 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001480
1481 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1482 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1483 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001484 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1485 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001486 reset(mContext.userManagerInternal);
1487
Makoto Onukia4f11972015-10-01 13:19:58 -07001488 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001489 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1490 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001491 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1492 UserManager.DISALLOW_ADD_USER),
1493 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001494 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001495
Makoto Onuki068c54a2015-10-13 14:34:03 -07001496 DpmTestUtils.assertRestrictions(
1497 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001498 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001499 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1500 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001501 DpmTestUtils.assertRestrictions(
1502 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001503 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001504 dpm.getUserRestrictions(admin1)
1505 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001506
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001507 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1508 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1509 eq(UserHandle.USER_SYSTEM),
1510 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001511 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001512 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001513
Makoto Onuki068c54a2015-10-13 14:34:03 -07001514 DpmTestUtils.assertRestrictions(
1515 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1516 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1517 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001518 DpmTestUtils.assertRestrictions(
1519 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1520 dpm.getUserRestrictions(admin1)
1521 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001522
1523 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001524 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1525 eq(UserHandle.USER_SYSTEM),
1526 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001527 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001528 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001529
Esteban Talavera548a04b2016-12-20 15:22:30 +00001530 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001531
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001532 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1533 // DO sets them, the scope is global.
1534 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1535 reset(mContext.userManagerInternal);
1536 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1537 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1538 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001539 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001540 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1541 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001542 reset(mContext.userManagerInternal);
1543
1544 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1545 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov6a40f092016-10-25 15:46:51 +01001546 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001547
1548 // More tests.
1549 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1550 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1551 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001552 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1553 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001554 reset(mContext.userManagerInternal);
1555
1556 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1557 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1558 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001559 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001560 UserManager.DISALLOW_ADD_USER),
1561 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001562 reset(mContext.userManagerInternal);
1563
1564 dpm.setCameraDisabled(admin1, true);
1565 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1566 eq(UserHandle.USER_SYSTEM),
1567 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001568 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001569 UserManager.DISALLOW_ADD_USER),
1570 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001571 reset(mContext.userManagerInternal);
1572
1573 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1574 // locally.
1575 dpm.setCameraDisabled(admin1, false);
1576 reset(mContext.userManagerInternal);
1577
1578 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1579 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1580 dpm.setCameraDisabled(admin2, true);
1581
1582 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1583 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001584 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001585 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001586 UserManager.DISALLOW_ADD_USER),
1587 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001588 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001589 // TODO Make sure restrictions are written to the file.
1590 }
1591
1592 public void testSetUserRestriction_asPo() {
1593 setAsProfileOwner(admin1);
1594
Makoto Onuki068c54a2015-10-13 14:34:03 -07001595 DpmTestUtils.assertRestrictions(
1596 DpmTestUtils.newRestrictions(),
1597 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1598 .ensureUserRestrictions()
1599 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001600
1601 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001602 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1603 eq(DpmMockContext.CALLER_USER_HANDLE),
1604 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001605 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001606 reset(mContext.userManagerInternal);
1607
Makoto Onukia4f11972015-10-01 13:19:58 -07001608 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001609 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1610 eq(DpmMockContext.CALLER_USER_HANDLE),
1611 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1612 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001613 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001614 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001615
Makoto Onuki068c54a2015-10-13 14:34:03 -07001616 DpmTestUtils.assertRestrictions(
1617 DpmTestUtils.newRestrictions(
1618 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1619 UserManager.DISALLOW_OUTGOING_CALLS
1620 ),
1621 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1622 .ensureUserRestrictions()
1623 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001624 DpmTestUtils.assertRestrictions(
1625 DpmTestUtils.newRestrictions(
1626 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1627 UserManager.DISALLOW_OUTGOING_CALLS
1628 ),
1629 dpm.getUserRestrictions(admin1)
1630 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001631
1632 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001633 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1634 eq(DpmMockContext.CALLER_USER_HANDLE),
1635 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001636 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001637 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001638
1639 DpmTestUtils.assertRestrictions(
1640 DpmTestUtils.newRestrictions(
1641 UserManager.DISALLOW_OUTGOING_CALLS
1642 ),
1643 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1644 .ensureUserRestrictions()
1645 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001646 DpmTestUtils.assertRestrictions(
1647 DpmTestUtils.newRestrictions(
1648 UserManager.DISALLOW_OUTGOING_CALLS
1649 ),
1650 dpm.getUserRestrictions(admin1)
1651 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001652
1653 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001654 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1655 eq(DpmMockContext.CALLER_USER_HANDLE),
1656 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001657 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001658 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001659
Makoto Onuki068c54a2015-10-13 14:34:03 -07001660 DpmTestUtils.assertRestrictions(
1661 DpmTestUtils.newRestrictions(),
1662 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1663 .ensureUserRestrictions()
1664 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001665 DpmTestUtils.assertRestrictions(
1666 DpmTestUtils.newRestrictions(),
1667 dpm.getUserRestrictions(admin1)
1668 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001669
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001670 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1671 // though when DO sets them they'll be applied globally.
1672 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1673 reset(mContext.userManagerInternal);
1674 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1675 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1676 eq(DpmMockContext.CALLER_USER_HANDLE),
1677 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1678 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001679 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001680 reset(mContext.userManagerInternal);
1681
1682 dpm.setCameraDisabled(admin1, true);
1683 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1684 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001685 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001687 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001688 reset(mContext.userManagerInternal);
1689
Makoto Onukia4f11972015-10-01 13:19:58 -07001690 // TODO Make sure restrictions are written to the file.
1691 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001692
Esteban Talavera548a04b2016-12-20 15:22:30 +00001693
1694 public void testDefaultEnabledUserRestrictions() throws Exception {
1695 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1696 mContext.callerPermissions.add(permission.MANAGE_USERS);
1697 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1698 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1699
1700 // First, set DO.
1701
1702 // Call from a process on the system user.
1703 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1704
1705 // Make sure admin1 is installed on system user.
1706 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1707
1708 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1709 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1710 UserHandle.USER_SYSTEM));
1711
1712 // Check that the user restrictions that are enabled by default are set. Then unset them.
1713 String[] defaultRestrictions = UserRestrictionsUtils
1714 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1715 assertTrue(defaultRestrictions.length > 0);
1716 DpmTestUtils.assertRestrictions(
1717 DpmTestUtils.newRestrictions(defaultRestrictions),
1718 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1719 );
1720 DpmTestUtils.assertRestrictions(
1721 DpmTestUtils.newRestrictions(defaultRestrictions),
1722 dpm.getUserRestrictions(admin1)
1723 );
1724 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1725 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001726 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001727 eq(true) /* isDeviceOwner */,
1728 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001729 );
1730 reset(mContext.userManagerInternal);
1731
1732 for (String restriction : defaultRestrictions) {
1733 dpm.clearUserRestriction(admin1, restriction);
1734 }
1735
1736 assertNoDeviceOwnerRestrictions();
1737
1738 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1739 reset(mContext.userManagerInternal);
1740 initializeDpms();
1741 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1742 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1743
1744 assertNoDeviceOwnerRestrictions();
1745
1746 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1747 // is set as it wasn't enabled during setDeviceOwner.
1748 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1749 assertFalse(UserRestrictionsUtils
1750 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1751 UserRestrictionsUtils
1752 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1753 try {
1754 reset(mContext.userManagerInternal);
1755 initializeDpms();
1756 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1757 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1758
1759 DpmTestUtils.assertRestrictions(
1760 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1761 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1762 );
1763 DpmTestUtils.assertRestrictions(
1764 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1765 dpm.getUserRestrictions(admin1)
1766 );
1767 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1768 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001769 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001770 eq(true) /* isDeviceOwner */,
1771 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001772 );
1773 reset(mContext.userManagerInternal);
1774
1775 // Remove the restriction.
1776 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1777
1778 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1779 initializeDpms();
1780 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1781 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1782 assertNoDeviceOwnerRestrictions();
1783 } finally {
1784 UserRestrictionsUtils
1785 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1786 }
1787 }
1788
1789 private void assertNoDeviceOwnerRestrictions() {
1790 DpmTestUtils.assertRestrictions(
1791 DpmTestUtils.newRestrictions(),
1792 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1793 );
1794 DpmTestUtils.assertRestrictions(
1795 DpmTestUtils.newRestrictions(),
1796 dpm.getUserRestrictions(admin1)
1797 );
1798 }
1799
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001800 public void testGetMacAddress() throws Exception {
1801 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1802 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1803 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1804
1805 // In this test, change the caller user to "system".
1806 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1807
1808 // Make sure admin1 is installed on system user.
1809 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1810
1811 // Test 1. Caller doesn't have DO or DA.
1812 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001813 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001814 fail();
1815 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001816 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001817 }
1818
1819 // DO needs to be an DA.
1820 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1821 assertTrue(dpm.isAdminActive(admin1));
1822
1823 // Test 2. Caller has DA, but not DO.
1824 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001825 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001826 fail();
1827 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001828 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001829 }
1830
1831 // Test 3. Caller has PO, but not DO.
1832 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1833 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001834 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001835 fail();
1836 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001837 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001838 }
1839
1840 // Remove PO.
1841 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001842 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001843 // Test 4, Caller is DO now.
1844 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1845
1846 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001847 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001848
1849 // 4-2. Returns WifiInfo, but with the default MAC.
1850 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001851 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001852
1853 // 4-3. With a real MAC address.
1854 final WifiInfo wi = new WifiInfo();
1855 wi.setMacAddress("11:22:33:44:55:66");
1856 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001857 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001858 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001859
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001860 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001861 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1862 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1863
1864 // In this test, change the caller user to "system".
1865 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1866
1867 // Make sure admin1 is installed on system user.
1868 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1869
1870 // Set admin1 as DA.
1871 dpm.setActiveAdmin(admin1, false);
1872 assertTrue(dpm.isAdminActive(admin1));
1873 try {
1874 dpm.reboot(admin1);
1875 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1876 } catch (SecurityException expected) {
1877 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1878 }
1879
1880 // Set admin1 as PO.
1881 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1882 try {
1883 dpm.reboot(admin1);
1884 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1885 } catch (SecurityException expected) {
1886 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1887 }
1888
1889 // Remove PO and add DO.
1890 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001891 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001892 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1893
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001894 // admin1 is DO.
1895 // Set current call state of device to ringing.
1896 when(mContext.telephonyManager.getCallState())
1897 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1898 try {
1899 dpm.reboot(admin1);
1900 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1901 } catch (IllegalStateException expected) {
1902 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1903 }
1904
1905 // Set current call state of device to dialing/active.
1906 when(mContext.telephonyManager.getCallState())
1907 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1908 try {
1909 dpm.reboot(admin1);
1910 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1911 } catch (IllegalStateException expected) {
1912 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1913 }
1914
1915 // Set current call state of device to idle.
1916 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001917 dpm.reboot(admin1);
1918 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001919
1920 public void testSetGetSupportText() {
1921 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1922 dpm.setActiveAdmin(admin1, true);
1923 dpm.setActiveAdmin(admin2, true);
1924 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1925
1926 // Null default support messages.
1927 {
1928 assertNull(dpm.getLongSupportMessage(admin1));
1929 assertNull(dpm.getShortSupportMessage(admin1));
1930 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1931 assertNull(dpm.getShortSupportMessageForUser(admin1,
1932 DpmMockContext.CALLER_USER_HANDLE));
1933 assertNull(dpm.getLongSupportMessageForUser(admin1,
1934 DpmMockContext.CALLER_USER_HANDLE));
1935 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1936 }
1937
1938 // Only system can call the per user versions.
1939 {
1940 try {
1941 dpm.getShortSupportMessageForUser(admin1,
1942 DpmMockContext.CALLER_USER_HANDLE);
1943 fail("Only system should be able to call getXXXForUser versions");
1944 } catch (SecurityException expected) {
1945 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1946 }
1947 try {
1948 dpm.getLongSupportMessageForUser(admin1,
1949 DpmMockContext.CALLER_USER_HANDLE);
1950 fail("Only system should be able to call getXXXForUser versions");
1951 } catch (SecurityException expected) {
1952 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1953 }
1954 }
1955
1956 // Can't set message for admin in another uid.
1957 {
1958 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1959 try {
1960 dpm.setShortSupportMessage(admin1, "Some text");
1961 fail("Admins should only be able to change their own support text.");
1962 } catch (SecurityException expected) {
1963 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1964 }
1965 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1966 }
1967
1968 // Set/Get short returns what it sets and other admins text isn't changed.
1969 {
1970 final String supportText = "Some text to test with.";
1971 dpm.setShortSupportMessage(admin1, supportText);
1972 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1973 assertNull(dpm.getLongSupportMessage(admin1));
1974 assertNull(dpm.getShortSupportMessage(admin2));
1975
1976 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1977 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1978 DpmMockContext.CALLER_USER_HANDLE));
1979 assertNull(dpm.getShortSupportMessageForUser(admin2,
1980 DpmMockContext.CALLER_USER_HANDLE));
1981 assertNull(dpm.getLongSupportMessageForUser(admin1,
1982 DpmMockContext.CALLER_USER_HANDLE));
1983 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1984
1985 dpm.setShortSupportMessage(admin1, null);
1986 assertNull(dpm.getShortSupportMessage(admin1));
1987 }
1988
1989 // Set/Get long returns what it sets and other admins text isn't changed.
1990 {
1991 final String supportText = "Some text to test with.\nWith more text.";
1992 dpm.setLongSupportMessage(admin1, supportText);
1993 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1994 assertNull(dpm.getShortSupportMessage(admin1));
1995 assertNull(dpm.getLongSupportMessage(admin2));
1996
1997 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1998 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1999 DpmMockContext.CALLER_USER_HANDLE));
2000 assertNull(dpm.getLongSupportMessageForUser(admin2,
2001 DpmMockContext.CALLER_USER_HANDLE));
2002 assertNull(dpm.getShortSupportMessageForUser(admin1,
2003 DpmMockContext.CALLER_USER_HANDLE));
2004 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2005
2006 dpm.setLongSupportMessage(admin1, null);
2007 assertNull(dpm.getLongSupportMessage(admin1));
2008 }
2009 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002010
phweiss73145f42017-01-17 19:06:38 +01002011 public void testCreateAdminSupportIntent() throws Exception {
2012 // Setup device owner.
2013 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2014 setupDeviceOwner();
2015
2016 // Nonexisting permission returns null
2017 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2018 assertNull(intent);
2019
2020 // Existing permission that is not set returns null
2021 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2022 assertNull(intent);
2023
2024 // Existing permission that is not set by device/profile owner returns null
2025 when(mContext.userManager.hasUserRestriction(
2026 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2027 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2028 .thenReturn(true);
2029 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2030 assertNull(intent);
2031
2032 // Permission that is set by device owner returns correct intent
2033 when(mContext.userManager.getUserRestrictionSource(
2034 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2035 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2036 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2037 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2038 assertNotNull(intent);
2039 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2040 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2041 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2042 assertEquals(admin1,
2043 (ComponentName) intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
2044 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2045 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2046
2047 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2048 // user restrictions
2049
2050 // Camera is not disabled
2051 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2052 assertNull(intent);
2053
2054 // Camera is disabled
2055 dpm.setCameraDisabled(admin1, true);
2056 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2057 assertNotNull(intent);
2058 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2059 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2060
2061 // Screen capture is not disabled
2062 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2063 assertNull(intent);
2064
2065 // Screen capture is disabled
2066 dpm.setScreenCaptureDisabled(admin1, true);
2067 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2068 assertNotNull(intent);
2069 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2070 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2071
2072 // Same checks for different user
2073 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2074 // Camera should be disabled by device owner
2075 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2076 assertNotNull(intent);
2077 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2078 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2079 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2080 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2081 // ScreenCapture should not be disabled by device owner
2082 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2083 assertNull(intent);
2084 }
2085
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002086 /**
2087 * Test for:
2088 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002089 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002090 * {@link DevicePolicyManager#isAffiliatedUser}
2091 */
2092 public void testUserAffiliation() throws Exception {
2093 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2094 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2095 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2096
2097 // Check that the system user is unaffiliated.
2098 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2099 assertFalse(dpm.isAffiliatedUser());
2100
2101 // Set a device owner on the system user. Check that the system user becomes affiliated.
2102 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2103 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2104 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2105 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002106 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002107
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002108 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002109 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2110 setAsProfileOwner(admin2);
2111 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002112 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002113
2114 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2115 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002116 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002117 userAffiliationIds.add("red");
2118 userAffiliationIds.add("green");
2119 userAffiliationIds.add("blue");
2120 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002121 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002122 assertFalse(dpm.isAffiliatedUser());
2123
2124 // Have the device owner specify a set of affiliation ids that do not intersect with those
2125 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002126 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002127 deviceAffiliationIds.add("cyan");
2128 deviceAffiliationIds.add("yellow");
2129 deviceAffiliationIds.add("magenta");
2130 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2131 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002132 MoreAsserts.assertContentsInAnyOrder(
2133 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002134 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2135 assertFalse(dpm.isAffiliatedUser());
2136
2137 // Have the profile owner specify a set of affiliation ids that intersect with those
2138 // specified by the device owner. Check that the test user becomes affiliated.
2139 userAffiliationIds.add("yellow");
2140 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002141 MoreAsserts.assertContentsInAnyOrder(
2142 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002143 assertTrue(dpm.isAffiliatedUser());
2144
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002145 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
2146 dpm.setAffiliationIds(admin2, Collections.emptyList());
2147 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002148 assertFalse(dpm.isAffiliatedUser());
2149
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002150 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2151 dpm.setAffiliationIds(admin2, userAffiliationIds);
2152 assertTrue(dpm.isAffiliatedUser());
2153 dpm.clearProfileOwner(admin2);
2154 assertFalse(dpm.isAffiliatedUser());
2155
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002156 // Check that the system user remains affiliated.
2157 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2158 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002159
2160 // Clear the device owner - the user becomes unaffiliated.
2161 clearDeviceOwner();
2162 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002163 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002164
2165 public void testGetUserProvisioningState_defaultResult() {
2166 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2167 }
2168
2169 public void testSetUserProvisioningState_permission() throws Exception {
2170 setupProfileOwner();
2171 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2172
2173 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2174 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2175 }
2176
2177 public void testSetUserProvisioningState_unprivileged() throws Exception {
2178 setupProfileOwner();
2179 try {
2180 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2181 DpmMockContext.CALLER_USER_HANDLE);
2182 fail("Expected SecurityException");
2183 } catch (SecurityException expected) {
2184 }
2185 }
2186
2187 public void testSetUserProvisioningState_noManagement() {
2188 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2189 try {
2190 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2191 DpmMockContext.CALLER_USER_HANDLE);
2192 fail("IllegalStateException expected");
2193 } catch (IllegalStateException e) {
2194 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
2195 e.getMessage());
2196 }
2197 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2198 }
2199
2200 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2201 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2202 setupDeviceOwner();
2203 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2204
2205 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2206 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2207 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2208 }
2209
2210 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2211 throws Exception {
2212 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2213 setupDeviceOwner();
2214 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2215
2216 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2217 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2218 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2219 }
2220
2221 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2222 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2223 setupDeviceOwner();
2224 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2225
2226 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2227 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2228 }
2229
2230 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2231 throws Exception {
2232 setupProfileOwner();
2233 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2234
2235 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2236 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2237 DevicePolicyManager.STATE_USER_UNMANAGED);
2238 }
2239
2240 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2241 throws Exception {
2242 setupProfileOwner();
2243 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2244
2245 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2246 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2247 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2248 }
2249
2250 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2251 setupProfileOwner();
2252 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2253
2254 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2255 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2256 }
2257
2258 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2259 setupProfileOwner();
2260 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2261
2262 try {
2263 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2264 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2265 DevicePolicyManager.STATE_USER_UNMANAGED);
2266 fail("Expected IllegalStateException");
2267 } catch (IllegalStateException e) {
2268 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2269 e.getMessage());
2270 }
2271 }
2272
2273 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2274 throws Exception {
2275 setupProfileOwner();
2276 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2277
2278 try {
2279 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2280 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2281 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2282 fail("Expected IllegalStateException");
2283 } catch (IllegalStateException e) {
2284 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2285 e.getMessage());
2286 }
2287 }
2288
2289 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2290 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2291 for (int state : states) {
2292 dpm.setUserProvisioningState(state, userId);
2293 assertEquals(state, dpm.getUserProvisioningState());
2294 }
2295 }
2296
2297 private void setupProfileOwner() throws Exception {
2298 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2299
2300 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2301 dpm.setActiveAdmin(admin1, false);
2302 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2303
2304 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2305 }
2306
2307 private void setupDeviceOwner() throws Exception {
2308 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2309
2310 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2311 dpm.setActiveAdmin(admin1, false);
2312 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2313
2314 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2315 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002316
2317 public void testSetMaximumTimeToLock() {
2318 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2319
2320 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2321 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2322
2323 reset(mMockContext.powerManagerInternal);
2324 reset(mMockContext.settings);
2325
2326 dpm.setMaximumTimeToLock(admin1, 0);
2327 verifyScreenTimeoutCall(null, false);
2328 reset(mMockContext.powerManagerInternal);
2329 reset(mMockContext.settings);
2330
2331 dpm.setMaximumTimeToLock(admin1, 1);
2332 verifyScreenTimeoutCall(1, true);
2333 reset(mMockContext.powerManagerInternal);
2334 reset(mMockContext.settings);
2335
2336 dpm.setMaximumTimeToLock(admin2, 10);
2337 verifyScreenTimeoutCall(null, false);
2338 reset(mMockContext.powerManagerInternal);
2339 reset(mMockContext.settings);
2340
2341 dpm.setMaximumTimeToLock(admin1, 5);
2342 verifyScreenTimeoutCall(5, true);
2343 reset(mMockContext.powerManagerInternal);
2344 reset(mMockContext.settings);
2345
2346 dpm.setMaximumTimeToLock(admin2, 4);
2347 verifyScreenTimeoutCall(4, true);
2348 reset(mMockContext.powerManagerInternal);
2349 reset(mMockContext.settings);
2350
2351 dpm.setMaximumTimeToLock(admin1, 0);
2352 reset(mMockContext.powerManagerInternal);
2353 reset(mMockContext.settings);
2354
2355 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2356 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2357 reset(mMockContext.powerManagerInternal);
2358 reset(mMockContext.settings);
2359
2360 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2361 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2362 reset(mMockContext.powerManagerInternal);
2363 reset(mMockContext.settings);
2364
2365 dpm.setMaximumTimeToLock(admin2, 10);
2366 verifyScreenTimeoutCall(10, true);
2367 reset(mMockContext.powerManagerInternal);
2368 reset(mMockContext.settings);
2369
2370 // There's no restriction; shold be set to MAX.
2371 dpm.setMaximumTimeToLock(admin2, 0);
2372 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2373 }
2374
Michal Karpinski943aabd2016-10-06 11:09:25 +01002375 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2376 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2377 setupDeviceOwner();
2378 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2379
Michal Karpinskid084ca52017-01-18 15:54:18 +00002380 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2381 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2382 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2383 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2384 - ONE_MINUTE;
2385
2386 // verify that the minimum timeout cannot be modified on user builds (system property is
2387 // not being read)
2388 mContext.buildMock.isDebuggable = false;
2389
2390 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2391 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2392 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2393
2394 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2395
2396 // restore to the debuggable build state
2397 mContext.buildMock.isDebuggable = true;
2398
2399 // Always return the default (second arg) when getting system property for long type
2400 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2401 new Answer<Long>() {
2402 @Override
2403 public Long answer(InvocationOnMock invocation) throws Throwable {
2404 return (Long) invocation.getArguments()[1];
2405 }
2406 }
2407 );
2408
2409 // reset to default (0 means the admin is not participating, so default should be returned)
2410 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002411
2412 // aggregation should be the default if unset by any admin
2413 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2414 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2415
2416 // admin not participating by default
2417 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2418
2419 //clamping from the top
2420 dpm.setRequiredStrongAuthTimeout(admin1,
2421 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2422 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2423 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2424 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2425 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2426
Michal Karpinskid084ca52017-01-18 15:54:18 +00002427 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002428 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2429 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2430 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2431 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2432
2433 // clamping from the bottom
2434 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2435 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2436 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2437
Michal Karpinskid084ca52017-01-18 15:54:18 +00002438 // values within range
2439 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2440 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2441 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2442
2443 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2444 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2445 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002446
2447 // reset to default
2448 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2449 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2450 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2451 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2452
2453 // negative value
2454 try {
2455 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2456 fail("Didn't throw IllegalArgumentException");
2457 } catch (IllegalArgumentException iae) {
2458 }
2459 }
2460
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002461 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2462 boolean shouldStayOnWhilePluggedInBeCleared) {
2463 if (expectedTimeout == null) {
2464 verify(mMockContext.powerManagerInternal, times(0))
2465 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2466 } else {
2467 verify(mMockContext.powerManagerInternal, times(1))
2468 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2469 }
2470 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2471 // UnfinishedVerificationException.
2472 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002473
Esteban Talavera01576862016-12-15 11:16:44 +00002474 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002475 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2476 .thenReturn(false);
2477 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2478 .thenReturn(false);
2479 initializeDpms();
2480 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2481 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2482 .thenReturn(true);
2483 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2484
2485 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002486 }
Victor Chang3e794af2016-03-04 13:48:17 +00002487
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002488 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2489 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002490 mContext.packageName = admin1.getPackageName();
2491 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002492 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2493 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2494 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2495 false);
2496 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2497 }
2498
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002499 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2500 setup_DeviceAdminFeatureOff();
2501 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2502 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2503 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2504 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2505 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2506 assertCheckProvisioningPreCondition(
2507 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2508 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2509 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2510 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2511 }
2512
Esteban Talavera01576862016-12-15 11:16:44 +00002513 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002514 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2515 .thenReturn(false);
2516 initializeDpms();
2517 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2518 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2519 .thenReturn(true);
2520 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2521
2522 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002523 }
Victor Chang3e794af2016-03-04 13:48:17 +00002524
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002525 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2526 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002527 mContext.packageName = admin1.getPackageName();
2528 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002529 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2530 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2531 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2532 false);
2533 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2534
2535 // Test again when split user is on
2536 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2537 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2538 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2539 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2540 true);
2541 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2542 }
2543
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002544 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2545 setup_ManagedProfileFeatureOff();
2546 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2547 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2548 DevicePolicyManager.CODE_OK);
2549 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2550 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2551 assertCheckProvisioningPreCondition(
2552 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2553 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2554 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2555 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2556
2557 // Test again when split user is on
2558 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2559 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2560 DevicePolicyManager.CODE_OK);
2561 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2562 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2563 assertCheckProvisioningPreCondition(
2564 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2565 DevicePolicyManager.CODE_OK);
2566 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2567 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2568 }
2569
Esteban Talavera01576862016-12-15 11:16:44 +00002570 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002571 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2572 .thenReturn(true);
2573 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2574 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2575 .thenReturn(true);
2576 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2577
2578 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002579 }
Victor Chang3e794af2016-03-04 13:48:17 +00002580
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002581 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2582 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002583 mContext.packageName = admin1.getPackageName();
2584 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002585 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2586 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2587 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2588 false /* because of non-split user */);
2589 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2590 false /* because of non-split user */);
2591 }
2592
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002593 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002594 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002595 setup_nonSplitUser_firstBoot_primaryUser();
2596 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2597 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2598 DevicePolicyManager.CODE_OK);
2599 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2600 DevicePolicyManager.CODE_OK);
2601 assertCheckProvisioningPreCondition(
2602 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2603 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2604 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2605 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2606 }
2607
Esteban Talavera01576862016-12-15 11:16:44 +00002608 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002609 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2610 .thenReturn(true);
2611 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2612 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2613 .thenReturn(true);
2614 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2615
2616 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002617 }
Victor Chang3e794af2016-03-04 13:48:17 +00002618
Nicolas Prevot45d29072017-01-18 16:11:19 +00002619 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2620 setDeviceOwner();
2621 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2622 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2623 }
2624
2625 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2626 setup_nonSplitUser_withDo_primaryUser();
2627 final int MANAGED_PROFILE_USER_ID = 18;
2628 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2629 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2630 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2631 false /* we can't remove a managed profile */)).thenReturn(false);
2632 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2633 true)).thenReturn(true);
2634 }
2635
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002636 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2637 throws Exception {
2638 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002639 mContext.packageName = admin1.getPackageName();
2640 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002641 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2642 false/* because of completed device setup */);
2643 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2644 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2645 false/* because of non-split user */);
2646 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2647 false/* because of non-split user */);
2648 }
2649
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002650 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2651 throws Exception {
2652 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2653 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2654 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2655 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2656 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2657 DevicePolicyManager.CODE_OK);
2658 assertCheckProvisioningPreCondition(
2659 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2660 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2661 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2662 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2663 }
2664
Nicolas Prevot45d29072017-01-18 16:11:19 +00002665 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2666 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002667 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002668 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2669
2670 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2671 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002672 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002673
2674 // COMP mode is allowed.
2675 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2676 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002677 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002678
Nicolas Prevot45d29072017-01-18 16:11:19 +00002679 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002680 assertCheckProvisioningPreCondition(
2681 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002682 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002683 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002684 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2685 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2686 }
Esteban Talavera01576862016-12-15 11:16:44 +00002687
Nicolas Prevot45d29072017-01-18 16:11:19 +00002688 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2689 setup_nonSplitUser_withDo_primaryUser();
2690 mContext.packageName = admin1.getPackageName();
2691 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2692 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2693 // other packages should be forbidden.
Esteban Talavera01576862016-12-15 11:16:44 +00002694 when(mContext.userManager.hasUserRestriction(
2695 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2696 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2697 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002698 when(mContext.userManager.getUserRestrictionSource(
2699 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2700 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2701 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2702 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2703 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002704 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002705 assertCheckProvisioningPreCondition(
2706 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002707 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002708 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002709 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2710 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2711 }
Esteban Talavera01576862016-12-15 11:16:44 +00002712
Nicolas Prevot45d29072017-01-18 16:11:19 +00002713 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2714 throws Exception {
2715 setup_nonSplitUser_withDo_primaryUser();
2716 mContext.packageName = admin1.getPackageName();
2717 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002718 // The DO should not be allowed to initiate provisioning if the restriction is set by
2719 // another entity.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002720 when(mContext.userManager.hasUserRestriction(
2721 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2722 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2723 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002724 when(mContext.userManager.getUserRestrictionSource(
2725 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2726 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2727 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2728 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2729 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002730 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2731
2732 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002733 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002734 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002735 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002736 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2737 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2738 }
2739
2740 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2741 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2742 mContext.packageName = admin1.getPackageName();
2743 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2744
2745 // We can delete the managed profile to create a new one, so provisioning is allowed.
2746 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2747 DevicePolicyManager.CODE_OK);
2748 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2749 assertCheckProvisioningPreCondition(
2750 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2751 DpmMockContext.ANOTHER_PACKAGE_NAME,
2752 DevicePolicyManager.CODE_OK);
2753 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2754 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2755 }
2756
2757 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2758 throws Exception {
2759 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2760 mContext.packageName = admin1.getPackageName();
2761 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2762 when(mContext.userManager.hasUserRestriction(
2763 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2764 eq(UserHandle.SYSTEM)))
2765 .thenReturn(true);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002766 when(mContext.userManager.getUserRestrictionSource(
2767 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2768 eq(UserHandle.SYSTEM)))
2769 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002770
2771 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002772 assertCheckProvisioningPreCondition(
2773 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2774 DpmMockContext.ANOTHER_PACKAGE_NAME,
2775 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2776 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2777 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002778
2779 // But the device owner can still do it because it has set the restriction itself.
2780 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2781 DevicePolicyManager.CODE_OK);
2782 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002783 }
2784
2785 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002786 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2787 .thenReturn(true);
2788 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2789 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2790 .thenReturn(false);
2791 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2792
2793 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002794 }
Victor Chang3e794af2016-03-04 13:48:17 +00002795
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002796 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2797 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002798 mContext.packageName = admin1.getPackageName();
2799 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002800 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2801 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2802 false /* because canAddMoreManagedProfiles returns false */);
2803 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2804 true);
2805 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2806 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002807 }
2808
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002809 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2810 throws Exception {
2811 setup_splitUser_firstBoot_systemUser();
2812 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2813 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2814 DevicePolicyManager.CODE_OK);
2815 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002816 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002817 assertCheckProvisioningPreCondition(
2818 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2819 DevicePolicyManager.CODE_OK);
2820 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2821 DevicePolicyManager.CODE_SYSTEM_USER);
2822 }
2823
Esteban Talavera01576862016-12-15 11:16:44 +00002824 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002825 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2826 .thenReturn(true);
2827 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2828 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2829 .thenReturn(false);
2830 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2831
2832 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002833 }
Victor Chang3e794af2016-03-04 13:48:17 +00002834
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002835 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2836 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002837 mContext.packageName = admin1.getPackageName();
2838 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002839 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2840 true/* it's undefined behavior. Can be changed into false in the future */);
2841 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2842 false /* because canAddMoreManagedProfiles returns false */);
2843 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2844 true/* it's undefined behavior. Can be changed into false in the future */);
2845 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2846 false/* because calling uid is system user */);
2847 }
2848
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002849 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2850 throws Exception {
2851 setup_splitUser_afterDeviceSetup_systemUser();
2852 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2853 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2854 DevicePolicyManager.CODE_OK);
2855 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002856 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002857 assertCheckProvisioningPreCondition(
2858 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2859 DevicePolicyManager.CODE_OK);
2860 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2861 DevicePolicyManager.CODE_SYSTEM_USER);
2862 }
2863
Esteban Talavera01576862016-12-15 11:16:44 +00002864 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002865 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2866 .thenReturn(true);
2867 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2868 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2869 true)).thenReturn(true);
2870 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2871
2872 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002873 }
Victor Chang3e794af2016-03-04 13:48:17 +00002874
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002875 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2876 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002877 mContext.packageName = admin1.getPackageName();
2878 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002879 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2880 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2881 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2882 true);
2883 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002884 }
2885
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002886 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002887 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002888 setup_splitUser_firstBoot_primaryUser();
2889 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2890 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2891 DevicePolicyManager.CODE_OK);
2892 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2893 DevicePolicyManager.CODE_OK);
2894 assertCheckProvisioningPreCondition(
2895 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2896 DevicePolicyManager.CODE_OK);
2897 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2898 DevicePolicyManager.CODE_OK);
2899 }
2900
Esteban Talavera01576862016-12-15 11:16:44 +00002901 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002902 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2903 .thenReturn(true);
2904 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2905 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2906 true)).thenReturn(true);
2907 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2908
2909 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002910 }
Victor Chang3e794af2016-03-04 13:48:17 +00002911
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002912 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2913 throws Exception {
2914 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002915 mContext.packageName = admin1.getPackageName();
2916 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002917 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2918 true/* it's undefined behavior. Can be changed into false in the future */);
2919 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2920 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2921 true/* it's undefined behavior. Can be changed into false in the future */);
2922 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2923 false/* because user setup completed */);
2924 }
2925
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002926 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002927 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002928 setup_splitUser_afterDeviceSetup_primaryUser();
2929 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2930 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2931 DevicePolicyManager.CODE_OK);
2932 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2933 DevicePolicyManager.CODE_OK);
2934 assertCheckProvisioningPreCondition(
2935 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2936 DevicePolicyManager.CODE_OK);
2937 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2938 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2939 }
2940
Esteban Talavera01576862016-12-15 11:16:44 +00002941 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002942 setDeviceOwner();
2943
2944 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2945 .thenReturn(true);
2946 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2947 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2948 .thenReturn(false);
2949 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2950
2951 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002952 }
Victor Chang3e794af2016-03-04 13:48:17 +00002953
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002954 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2955 throws Exception {
2956 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002957 mContext.packageName = admin1.getPackageName();
2958 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002959 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2960 false /* can't provision managed profile on system user */);
2961 }
2962
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002963 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002964 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002965 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2966 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2967 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2968 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2969 }
2970
2971 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002972 setDeviceOwner();
2973
2974 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2975 .thenReturn(true);
2976 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2977 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2978 true)).thenReturn(true);
2979 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2980
2981 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002982 }
Victor Chang3e794af2016-03-04 13:48:17 +00002983
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002984 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2985 throws Exception {
2986 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002987 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2988 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002989 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2990 }
2991
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002992 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002993 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002994 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2995 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002996
2997 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002998 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2999 DevicePolicyManager.CODE_OK);
3000 }
3001
3002 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003003 setDeviceOwner();
3004
3005 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3006 .thenReturn(true);
3007 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003008 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003009 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3010 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003011 .thenReturn(true);
3012 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003013 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003014 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3015 true)).thenReturn(true);
3016 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3017
3018 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003019 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003020
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003021 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3022 throws Exception {
3023 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003024 mContext.packageName = admin1.getPackageName();
3025 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003026 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3027 }
3028
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003029 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3030 throws Exception {
3031 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3032 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3033 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3034 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3035 }
3036
3037 public void testCheckProvisioningPreCondition_permission() {
3038 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3039 try {
Esteban Talavera01576862016-12-15 11:16:44 +00003040 dpm.checkProvisioningPreCondition(
3041 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003042 fail("Didn't throw SecurityException");
3043 } catch (SecurityException expected) {
3044 }
3045 }
3046
Victor Chang3577ed22016-08-25 18:49:26 +01003047 public void testForceUpdateUserSetupComplete_permission() {
3048 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3049 try {
3050 dpm.forceUpdateUserSetupComplete();
3051 fail("Didn't throw SecurityException");
3052 } catch (SecurityException expected) {
3053 }
3054 }
3055
3056 public void testForceUpdateUserSetupComplete_systemUser() {
3057 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3058 // GIVEN calling from user 20
3059 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3060 try {
3061 dpm.forceUpdateUserSetupComplete();
3062 fail("Didn't throw SecurityException");
3063 } catch (SecurityException expected) {
3064 }
3065 }
3066
3067 public void testForceUpdateUserSetupComplete_userbuild() {
3068 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3069 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3070
3071 final int userId = UserHandle.USER_SYSTEM;
3072 // GIVEN userComplete is false in SettingsProvider
3073 setUserSetupCompleteForUser(false, userId);
3074
3075 // GIVEN userComplete is true in DPM
3076 DevicePolicyManagerService.DevicePolicyData userData =
3077 new DevicePolicyManagerService.DevicePolicyData(userId);
3078 userData.mUserSetupComplete = true;
3079 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3080
3081 // GIVEN it's user build
3082 mContext.buildMock.isDebuggable = false;
3083
3084 assertTrue(dpms.hasUserSetupCompleted());
3085
3086 dpm.forceUpdateUserSetupComplete();
3087
3088 // THEN the state in dpms is not changed
3089 assertTrue(dpms.hasUserSetupCompleted());
3090 }
3091
3092 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3093 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3094 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3095
3096 final int userId = UserHandle.USER_SYSTEM;
3097 // GIVEN userComplete is false in SettingsProvider
3098 setUserSetupCompleteForUser(false, userId);
3099
3100 // GIVEN userComplete is true in DPM
3101 DevicePolicyManagerService.DevicePolicyData userData =
3102 new DevicePolicyManagerService.DevicePolicyData(userId);
3103 userData.mUserSetupComplete = true;
3104 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3105
3106 // GIVEN it's userdebug build
3107 mContext.buildMock.isDebuggable = true;
3108
3109 assertTrue(dpms.hasUserSetupCompleted());
3110
3111 dpm.forceUpdateUserSetupComplete();
3112
3113 // THEN the state in dpms is not changed
3114 assertFalse(dpms.hasUserSetupCompleted());
3115 }
3116
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003117 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003118 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003119 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3120 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
3121 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
3122 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003123 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003124 }
3125
3126 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3127 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3128 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003129
3130 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3131 // feature is disabled because there are non-affiliated secondary users.
3132 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003133 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3134 .thenReturn(true);
3135
3136 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003137 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003138
3139 // Enabling logging should not change the timestamp.
3140 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003141 verify(mContext.settings)
3142 .securityLogSetLoggingEnabledProperty(true);
3143 when(mContext.settings.securityLogGetLoggingEnabledProperty())
3144 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003145 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003146
3147 // Retrieving the logs should update the timestamp.
3148 final long beforeRetrieval = System.currentTimeMillis();
3149 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003150 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003151 final long afterRetrieval = System.currentTimeMillis();
3152 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3153 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3154
3155 // Retrieving the pre-boot logs should update the timestamp.
3156 Thread.sleep(2);
3157 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003158 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003159 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3160
3161 // Checking the timestamp again should not change it.
3162 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003163 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003164
3165 // Retrieving the logs again should update the timestamp.
3166 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003167 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003168 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3169
3170 // Disabling logging should not change the timestamp.
3171 Thread.sleep(2);
3172 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003173 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003174
3175 // Restarting the DPMS should not lose the timestamp.
3176 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003177 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003178
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003179 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3180 mContext.binder.callingUid = 1234567;
3181 mContext.callerPermissions.add(permission.MANAGE_USERS);
3182 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3183 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3184
3185 // System can retrieve the timestamp.
3186 mContext.binder.clearCallingIdentity();
3187 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3188
3189 // Removing the device owner should clear the timestamp.
3190 clearDeviceOwner();
3191 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003192 }
3193
3194 public void testGetLastBugReportRequestTime() throws Exception {
3195 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3196 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003197
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003198 mContext.packageName = admin1.getPackageName();
3199 mContext.applicationInfo = new ApplicationInfo();
3200 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3201 .thenReturn(Color.WHITE);
3202 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3203 anyObject())).thenReturn(Color.WHITE);
3204
Esteban Talaverad36dd152016-12-15 08:51:45 +00003205 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3206 // feature is disabled because there are non-affiliated secondary users.
3207 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3208
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003209 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003210 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003211
3212 // Requesting a bug report should update the timestamp.
3213 final long beforeRequest = System.currentTimeMillis();
3214 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003215 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003216 final long afterRequest = System.currentTimeMillis();
3217 assertTrue(bugReportRequestTime >= beforeRequest);
3218 assertTrue(bugReportRequestTime <= afterRequest);
3219
3220 // Checking the timestamp again should not change it.
3221 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003222 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003223
3224 // Restarting the DPMS should not lose the timestamp.
3225 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003226 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003227
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003228 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3229 mContext.binder.callingUid = 1234567;
3230 mContext.callerPermissions.add(permission.MANAGE_USERS);
3231 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3232 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3233
3234 // System can retrieve the timestamp.
3235 mContext.binder.clearCallingIdentity();
3236 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3237
3238 // Removing the device owner should clear the timestamp.
3239 clearDeviceOwner();
3240 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003241 }
3242
3243 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3244 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3245 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003246 mContext.packageName = admin1.getPackageName();
3247 mContext.applicationInfo = new ApplicationInfo();
3248 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3249 .thenReturn(Color.WHITE);
3250 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3251 anyObject())).thenReturn(Color.WHITE);
3252
3253 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3254 // feature is disabled because there are non-affiliated secondary users.
3255 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003256 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3257 .thenReturn(true);
3258
3259 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003260 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003261
3262 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3263 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003264 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003265
3266 // Enabling logging should not change the timestamp.
3267 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003268 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003269
3270 // Retrieving the logs should update the timestamp.
3271 final long beforeRetrieval = System.currentTimeMillis();
3272 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003273 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003274 final long afterRetrieval = System.currentTimeMillis();
3275 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3276 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3277
3278 // Checking the timestamp again should not change it.
3279 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003280 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003281
3282 // Retrieving the logs again should update the timestamp.
3283 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003284 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003285 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3286
3287 // Disabling logging should not change the timestamp.
3288 Thread.sleep(2);
3289 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003290 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003291
3292 // Restarting the DPMS should not lose the timestamp.
3293 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003294 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3295
3296 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3297 mContext.binder.callingUid = 1234567;
3298 mContext.callerPermissions.add(permission.MANAGE_USERS);
3299 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3300 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3301
3302 // System can retrieve the timestamp.
3303 mContext.binder.clearCallingIdentity();
3304 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3305
3306 // Removing the device owner should clear the timestamp.
3307 clearDeviceOwner();
3308 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003309 }
3310
Tony Mak2f26b792016-11-28 17:54:51 +00003311 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3312 // Setup device owner.
3313 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3314 setupDeviceOwner();
3315
3316 // Only device owner is setup, the result list should be empty.
3317 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3318 MoreAsserts.assertEmpty(targetUsers);
3319
3320 // Setup a managed profile managed by the same admin.
3321 final int MANAGED_PROFILE_USER_ID = 15;
3322 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3323 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3324
3325 // Add a secondary user, it should never talk with.
3326 final int ANOTHER_USER_ID = 36;
3327 mContext.addUser(ANOTHER_USER_ID, 0);
3328
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003329 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3330 // other.
3331 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3332 MoreAsserts.assertEmpty(targetUsers);
3333
3334 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3335 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3336 MoreAsserts.assertEmpty(targetUsers);
3337
3338 // Setting affiliation ids
3339 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3340 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3341 dpm.setAffiliationIds(admin1, userAffiliationIds);
3342
3343 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3344 dpm.setAffiliationIds(admin1, userAffiliationIds);
3345
Tony Mak2f26b792016-11-28 17:54:51 +00003346 // Calling from device owner admin, the result list should just contain the managed
3347 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003348 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003349 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3350 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3351
3352 // Calling from managed profile admin, the result list should just contain the system
3353 // user id.
3354 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3355 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3356 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003357
3358 // Changing affiliation ids in one
3359 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3360
3361 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3362 // to each other.
3363 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3364 MoreAsserts.assertEmpty(targetUsers);
3365
3366 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3367 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3368 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003369 }
3370
3371 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3372 // Setup a device owner.
3373 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3374 setupDeviceOwner();
3375
3376 // Set up a managed profile managed by different package.
3377 final int MANAGED_PROFILE_USER_ID = 15;
3378 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3379 final ComponentName adminDifferentPackage =
3380 new ComponentName("another.package", "whatever.class");
3381 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3382
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003383 // Setting affiliation ids
3384 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3385 dpm.setAffiliationIds(admin1, userAffiliationIds);
3386
3387 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3388 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3389
Tony Mak2f26b792016-11-28 17:54:51 +00003390 // Calling from device owner admin, we should get zero bind device admin target users as
3391 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003392 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003393 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3394 MoreAsserts.assertEmpty(targetUsers);
3395
3396 // Calling from managed profile admin, we should still get zero target users for the same
3397 // reason.
3398 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3399 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3400 MoreAsserts.assertEmpty(targetUsers);
3401 }
3402
Esteban Talaverabdcada92017-02-01 14:20:06 +00003403 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3404 // Setup a device owner.
3405 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3406 setupDeviceOwner();
3407 // Lock task packages are updated when loading user data.
3408 verify(mContext.iactivityManager)
3409 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3410
3411 // Set up a managed profile managed by different package (package name shouldn't matter)
3412 final int MANAGED_PROFILE_USER_ID = 15;
3413 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3414 final ComponentName adminDifferentPackage =
3415 new ComponentName("another.package", "whatever.class");
3416 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3417 verify(mContext.iactivityManager)
3418 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3419
3420 // The DO can still set lock task packages
3421 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3422 final String[] doPackages = {"doPackage1", "doPackage2"};
3423 dpm.setLockTaskPackages(admin1, doPackages);
3424 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3425 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3426 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3427 verify(mContext.iactivityManager)
3428 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3429
3430 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3431 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3432 final String[] poPackages = {"poPackage1", "poPackage2"};
3433 try {
3434 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3435 fail("Didn't throw expected security exception.");
3436 } catch (SecurityException expected) {
3437 }
3438 try {
3439 dpm.getLockTaskPackages(adminDifferentPackage);
3440 fail("Didn't throw expected security exception.");
3441 } catch (SecurityException expected) {
3442 }
3443 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3444
3445 // Setting same affiliation ids
3446 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3447 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3448 dpm.setAffiliationIds(admin1, userAffiliationIds);
3449
3450 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3451 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3452
3453 // Now the managed profile can set lock task packages.
3454 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3455 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3456 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3457 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
3458 verify(mContext.iactivityManager)
3459 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3460
3461 // Unaffiliate the profile, lock task mode no longer available on the profile.
3462 dpm.setAffiliationIds(adminDifferentPackage, Collections.<String>emptyList());
3463 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3464 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
3465 verify(mContext.iactivityManager, times(2))
3466 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3467
3468 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3469 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3470 }
3471
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003472 public void testIsDeviceManaged() throws Exception {
3473 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3474 setupDeviceOwner();
3475
3476 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3477 // find out that the device has a device owner.
3478 assertTrue(dpm.isDeviceManaged());
3479 mContext.binder.callingUid = 1234567;
3480 mContext.callerPermissions.add(permission.MANAGE_USERS);
3481 assertTrue(dpm.isDeviceManaged());
3482 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3483 mContext.binder.clearCallingIdentity();
3484 assertTrue(dpm.isDeviceManaged());
3485
3486 clearDeviceOwner();
3487
3488 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3489 // not have a device owner.
3490 mContext.binder.callingUid = 1234567;
3491 mContext.callerPermissions.add(permission.MANAGE_USERS);
3492 assertFalse(dpm.isDeviceManaged());
3493 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3494 mContext.binder.clearCallingIdentity();
3495 assertFalse(dpm.isDeviceManaged());
3496 }
3497
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003498 public void testDeviceOwnerOrganizationName() throws Exception {
3499 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3500 setupDeviceOwner();
3501
3502 dpm.setOrganizationName(admin1, "organization");
3503
3504 // Device owner can retrieve organization managing the device.
3505 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3506
3507 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3508 mContext.binder.callingUid = 1234567;
3509 mContext.callerPermissions.add(permission.MANAGE_USERS);
3510 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3511 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3512
3513 // System can retrieve organization managing the device.
3514 mContext.binder.clearCallingIdentity();
3515 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3516
3517 // Removing the device owner clears the organization managing the device.
3518 clearDeviceOwner();
3519 assertNull(dpm.getDeviceOwnerOrganizationName());
3520 }
3521
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003522 public void testWipeDataManagedProfile() throws Exception {
3523 final int MANAGED_PROFILE_USER_ID = 15;
3524 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3525 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3526 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3527
3528 // Even if the caller is the managed profile, the current user is the user 0
3529 when(mContext.iactivityManager.getCurrentUser())
3530 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3531
3532 dpm.wipeData(0);
3533 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3534 MANAGED_PROFILE_USER_ID);
3535 }
3536
3537 public void testWipeDataManagedProfileDisallowed() throws Exception {
3538 final int MANAGED_PROFILE_USER_ID = 15;
3539 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3540 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3541
3542 // Even if the caller is the managed profile, the current user is the user 0
3543 when(mContext.iactivityManager.getCurrentUser())
3544 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3545
3546 when(mContext.userManager.getUserRestrictionSource(
3547 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3548 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3549 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3550 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3551 try {
3552 // The PO is not allowed to remove the profile if the user restriction was set on the
3553 // profile by the system
3554 dpm.wipeData(0);
3555 fail("SecurityException not thrown");
3556 } catch (SecurityException expected) {
3557 }
3558 }
3559
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003560 public void testWipeDataDeviceOwner() throws Exception {
3561 setDeviceOwner();
3562 when(mContext.userManager.getUserRestrictionSource(
3563 UserManager.DISALLOW_FACTORY_RESET,
3564 UserHandle.SYSTEM))
3565 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3566
3567 dpm.wipeData(0);
3568 verify(mContext.recoverySystem).rebootWipeUserData(
3569 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3570 }
3571
3572 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3573 setDeviceOwner();
3574 when(mContext.userManager.getUserRestrictionSource(
3575 UserManager.DISALLOW_FACTORY_RESET,
3576 UserHandle.SYSTEM))
3577 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3578 try {
3579 // The DO is not allowed to wipe the device if the user restriction was set
3580 // by the system
3581 dpm.wipeData(0);
3582 fail("SecurityException not thrown");
3583 } catch (SecurityException expected) {
3584 }
3585 }
3586
3587 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3588 final int MANAGED_PROFILE_USER_ID = 15;
3589 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3590 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3591
3592 // Even if the caller is the managed profile, the current user is the user 0
3593 when(mContext.iactivityManager.getCurrentUser())
3594 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3595
3596 when(mContext.userManager.getUserRestrictionSource(
3597 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3598 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3599 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3600
3601 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3602 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3603
3604 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3605 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3606 // Failed password attempts on the parent user are taken into account, as there isn't a
3607 // separate work challenge.
3608 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3609 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3610 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3611
3612 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3613 // both the user restriction and the policy were set by the PO.
3614 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3615 MANAGED_PROFILE_USER_ID);
3616 verifyZeroInteractions(mContext.recoverySystem);
3617 }
3618
3619 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3620 throws Exception {
3621 final int MANAGED_PROFILE_USER_ID = 15;
3622 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3623 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3624
3625 // Even if the caller is the managed profile, the current user is the user 0
3626 when(mContext.iactivityManager.getCurrentUser())
3627 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3628
3629 when(mContext.userManager.getUserRestrictionSource(
3630 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3631 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3632 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3633
3634 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3635 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3636
3637 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3638 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3639 // Failed password attempts on the parent user are taken into account, as there isn't a
3640 // separate work challenge.
3641 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3642 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3643 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3644
3645 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3646 // not wiped.
3647 verify(mContext.userManagerInternal, never())
3648 .removeUserEvenWhenDisallowed(anyInt());
3649 verifyZeroInteractions(mContext.recoverySystem);
3650 }
3651
3652 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3653 setDeviceOwner();
3654 when(mContext.userManager.getUserRestrictionSource(
3655 UserManager.DISALLOW_FACTORY_RESET,
3656 UserHandle.SYSTEM))
3657 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3658
3659 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3660
3661 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3662 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3663 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3664 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3665 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3666
3667 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3668 // user restriction and the policy were set by the DO.
3669 verify(mContext.recoverySystem).rebootWipeUserData(
3670 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3671 }
3672
3673 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3674 setDeviceOwner();
3675 when(mContext.userManager.getUserRestrictionSource(
3676 UserManager.DISALLOW_FACTORY_RESET,
3677 UserHandle.SYSTEM))
3678 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3679
3680 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3681
3682 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3683 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3684 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3685 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3686 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3687
3688 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
3689 verifyZeroInteractions(mContext.recoverySystem);
3690 verify(mContext.userManagerInternal, never())
3691 .removeUserEvenWhenDisallowed(anyInt());
3692 }
3693
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003694 public void testGetPermissionGrantState() throws Exception {
3695 final String permission = "some.permission";
3696 final String app1 = "com.example.app1";
3697 final String app2 = "com.example.app2";
3698
3699 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3700 .thenReturn(PackageManager.PERMISSION_GRANTED);
3701 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3702 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3703 when(mContext.packageManager.getPermissionFlags(permission, app1,
3704 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3705 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3706 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3707 .thenReturn(PackageManager.PERMISSION_DENIED);
3708 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3709 UserHandle.SYSTEM);
3710 when(mContext.packageManager.getPermissionFlags(permission, app2,
3711 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3712
3713 // System can retrieve permission grant state.
3714 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003715 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003716 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3717 dpm.getPermissionGrantState(null, app1, permission));
3718 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3719 dpm.getPermissionGrantState(null, app2, permission));
3720
3721 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003722 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3723 mContext.packageName = app1;
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003724 try {
3725 dpm.getPermissionGrantState(null, app1, permission);
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003726 fail("Didn't throw SecurityException");
3727 } catch (SecurityException expected) {
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003728 }
3729
3730 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003731 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3732 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003733 setAsProfileOwner(admin1);
3734 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3735 dpm.getPermissionGrantState(admin1, app1, permission));
3736 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3737 dpm.getPermissionGrantState(admin1, app2, permission));
3738 }
3739
Rubin Xuaab7a412016-12-30 21:13:29 +00003740 public void testResetPasswordWithToken() throws Exception {
3741 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3742 setupDeviceOwner();
3743 // test token validation
3744 try {
3745 dpm.setResetPasswordToken(admin1, new byte[31]);
3746 fail("should not have accepted tokens too short");
3747 } catch (IllegalArgumentException expected) {
3748 }
3749 // test adding a token
3750 final byte[] token = new byte[32];
3751 final long handle = 123456;
3752 final String password = "password";
3753 when(mContext.lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
3754 .thenReturn(handle);
3755 assertTrue(dpm.setResetPasswordToken(admin1, token));
3756
3757 // test password activation
3758 when(mContext.lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
3759 .thenReturn(true);
3760 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3761
3762 // test reset password with token
3763 when(mContext.lockPatternUtils.setLockCredentialWithToken(eq(password),
3764 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3765 eq(UserHandle.USER_SYSTEM)))
3766 .thenReturn(true);
3767 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3768
3769 // test removing a token
3770 when(mContext.lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
3771 .thenReturn(true);
3772 assertTrue(dpm.clearResetPasswordToken(admin1));
3773 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003774
3775 public void testIsDefaultInputMethodSetByOwnerForDeviceOwner() throws Exception {
3776 final String defaultIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3777 final Uri defaultImeUri = Settings.Secure.getUriFor(defaultIme);
3778 final UserHandle firstUser = UserHandle.SYSTEM;
3779 final UserHandle secondUser = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
3780
3781 // Set up a Device Owner.
3782 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3783 setupDeviceOwner();
3784
3785 // First and second user set default IMEs manually.
3786 final long ident = mContext.binder.clearCallingIdentity();
3787 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3788 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3789 mContext.binder.restoreCallingIdentity(ident);
3790
3791 // Device Owner changes default IME for first user.
3792 when(mContext.settings.settingsSecureGetStringForUser(defaultIme, UserHandle.USER_SYSTEM))
3793 .thenReturn("ime1");
3794 dpm.setSecureSetting(admin1, defaultIme, "ime2");
3795 verify(mContext.settings).settingsSecurePutStringForUser(defaultIme, "ime2",
3796 UserHandle.USER_SYSTEM);
3797 reset(mContext.settings);
3798 dpms.notifyChangeToContentObserver(defaultImeUri, UserHandle.USER_SYSTEM);
3799 mContext.binder.clearCallingIdentity();
3800 assertTrue(dpm.isDefaultInputMethodSetByOwner(firstUser));
3801 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3802 mContext.binder.restoreCallingIdentity(ident);
3803
3804 // Second user changes default IME manually.
3805 dpms.notifyChangeToContentObserver(defaultImeUri, DpmMockContext.CALLER_USER_HANDLE);
3806 mContext.binder.clearCallingIdentity();
3807 assertTrue(dpm.isDefaultInputMethodSetByOwner(firstUser));
3808 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3809 mContext.binder.restoreCallingIdentity(ident);
3810
3811 // First user changes default IME manually.
3812 dpms.notifyChangeToContentObserver(defaultImeUri, UserHandle.USER_SYSTEM);
3813 mContext.binder.clearCallingIdentity();
3814 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3815 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3816 mContext.binder.restoreCallingIdentity(ident);
3817
3818 // Device Owner changes default IME for first user again.
3819 when(mContext.settings.settingsSecureGetStringForUser(defaultIme, UserHandle.USER_SYSTEM))
3820 .thenReturn("ime2");
3821 dpm.setSecureSetting(admin1, defaultIme, "ime3");
3822 verify(mContext.settings).settingsSecurePutStringForUser(defaultIme, "ime3",
3823 UserHandle.USER_SYSTEM);
3824 dpms.notifyChangeToContentObserver(defaultImeUri, UserHandle.USER_SYSTEM);
3825 mContext.binder.clearCallingIdentity();
3826 assertTrue(dpm.isDefaultInputMethodSetByOwner(firstUser));
3827 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3828
3829 // Restarting the DPMS should not lose information.
3830 initializeDpms();
3831 assertTrue(dpm.isDefaultInputMethodSetByOwner(firstUser));
3832 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3833 mContext.binder.restoreCallingIdentity(ident);
3834
3835 // Device Owner can find out whether it set the default IME itself.
3836 assertTrue(dpm.isDefaultInputMethodSetByOwner(firstUser));
3837
3838 // Removing the Device Owner should clear the information that it set the default IME.
3839 clearDeviceOwner();
3840 mContext.binder.clearCallingIdentity();
3841 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3842 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3843 }
3844
3845 public void testIsDefaultInputMethodSetByOwnerForProfileOwner() throws Exception {
3846 final String defaultIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3847 final Uri defaultImeUri = Settings.Secure.getUriFor(defaultIme);
3848 final UserHandle firstUser = UserHandle.SYSTEM;
3849 final UserHandle secondUser = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
3850
3851 // Set up a profile owner.
3852 setupProfileOwner();
3853
3854 // First and second user set default IMEs manually.
3855 final long ident = mContext.binder.clearCallingIdentity();
3856 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3857 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3858 mContext.binder.restoreCallingIdentity(ident);
3859
3860 // Profile Owner changes default IME for second user.
3861 when(mContext.settings.settingsSecureGetStringForUser(defaultIme,
3862 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
3863 dpm.setSecureSetting(admin1, defaultIme, "ime2");
3864 verify(mContext.settings).settingsSecurePutStringForUser(defaultIme, "ime2",
3865 DpmMockContext.CALLER_USER_HANDLE);
3866 reset(mContext.settings);
3867 dpms.notifyChangeToContentObserver(defaultImeUri, DpmMockContext.CALLER_USER_HANDLE);
3868 mContext.binder.clearCallingIdentity();
3869 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3870 assertTrue(dpm.isDefaultInputMethodSetByOwner(secondUser));
3871 mContext.binder.restoreCallingIdentity(ident);
3872
3873 // First user changes default IME manually.
3874 dpms.notifyChangeToContentObserver(defaultImeUri, UserHandle.USER_SYSTEM);
3875 mContext.binder.clearCallingIdentity();
3876 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3877 assertTrue(dpm.isDefaultInputMethodSetByOwner(secondUser));
3878 mContext.binder.restoreCallingIdentity(ident);
3879
3880 // Second user changes default IME manually.
3881 dpms.notifyChangeToContentObserver(defaultImeUri, DpmMockContext.CALLER_USER_HANDLE);
3882 mContext.binder.clearCallingIdentity();
3883 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3884 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3885 mContext.binder.restoreCallingIdentity(ident);
3886
3887 // Profile Owner changes default IME for second user again.
3888 when(mContext.settings.settingsSecureGetStringForUser(defaultIme,
3889 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
3890 dpm.setSecureSetting(admin1, defaultIme, "ime3");
3891 verify(mContext.settings).settingsSecurePutStringForUser(defaultIme, "ime3",
3892 DpmMockContext.CALLER_USER_HANDLE);
3893 dpms.notifyChangeToContentObserver(defaultImeUri, DpmMockContext.CALLER_USER_HANDLE);
3894 mContext.binder.clearCallingIdentity();
3895 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3896 assertTrue(dpm.isDefaultInputMethodSetByOwner(secondUser));
3897
3898 // Restarting the DPMS should not lose information.
3899 initializeDpms();
3900 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3901 assertTrue(dpm.isDefaultInputMethodSetByOwner(secondUser));
3902 mContext.binder.restoreCallingIdentity(ident);
3903
3904 // Profile Owner can find out whether it set the default IME itself.
3905 assertTrue(dpm.isDefaultInputMethodSetByOwner(secondUser));
3906
3907 // Removing the Profile Owner should clear the information that it set the default IME.
3908 dpm.clearProfileOwner(admin1);
3909 mContext.binder.clearCallingIdentity();
3910 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3911 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3912 }
Rubin Xuaab7a412016-12-30 21:13:29 +00003913
Victor Chang3e794af2016-03-04 13:48:17 +00003914 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
3915 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
3916 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
3917 dpms.notifyChangeToContentObserver(
3918 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
3919 }
3920
3921 private void assertProvisioningAllowed(String action, boolean expected) {
3922 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
3923 dpm.isProvisioningAllowed(action));
3924 }
Tony Mak2f26b792016-11-28 17:54:51 +00003925
Nicolas Prevot45d29072017-01-18 16:11:19 +00003926 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
3927 int uid) {
3928 String previousPackageName = mContext.packageName;
3929 int previousUid = mMockContext.binder.callingUid;
3930
3931 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
3932 mContext.packageName = packageName;
3933 mMockContext.binder.callingUid = uid;
3934 assertProvisioningAllowed(action, expected);
3935
3936 // Set the previous package name / calling uid to go back to the initial state.
3937 mContext.packageName = previousPackageName;
3938 mMockContext.binder.callingUid = previousUid;
3939 }
3940
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003941 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00003942 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
3943 }
3944
3945 private void assertCheckProvisioningPreCondition(
3946 String action, String packageName, int provisioningCondition) {
3947 assertEquals("checkProvisioningPreCondition("
3948 + action + ", " + packageName + ") returning unexpected result",
3949 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003950 }
3951
Tony Mak2f26b792016-11-28 17:54:51 +00003952 /**
3953 * Setup a managed profile with the specified admin and its uid.
3954 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
3955 * @param adminUid uid of the admin package.
3956 * @param copyFromAdmin package information for {@code admin} will be built based on this
3957 * component's information.
3958 */
3959 private void addManagedProfile(
3960 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
3961 final int userId = UserHandle.getUserId(adminUid);
3962 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
3963 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3964 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
3965 dpm.setActiveAdmin(admin, false, userId);
3966 assertTrue(dpm.setProfileOwner(admin, null, userId));
3967 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3968 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00003969
3970 /**
3971 * Convert String[] to ParceledListSlice&lt;ParcelableString&gt;.
3972 * <p>
3973 * TODO: This shouldn't be necessary. If ParcelableString does need to exist, it also needs
3974 * a real constructor.
3975 */
3976 private static ParceledListSlice<ParcelableString> asSlice(String[] s) {
3977 List<ParcelableString> list = new ArrayList<>(s.length);
3978 for (int i = 0; i < s.length; i++) {
3979 ParcelableString item = new ParcelableString();
3980 item.string = s[i];
3981 list.add(i, item);
3982 }
3983 return new ParceledListSlice<ParcelableString>(list);
3984 }
Victor Chang3e794af2016-03-04 13:48:17 +00003985}