blob: 3ceab6f9c5a51362f9a0b7b78461c9697ca10fae [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;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070024import android.app.admin.DeviceAdminReceiver;
25import android.app.admin.DevicePolicyManager;
26import android.app.admin.DevicePolicyManagerInternal;
Makoto Onukif76b06a2015-09-22 15:03:44 -070027import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070028import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000029import android.content.Context;
30import android.content.Intent;
31import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000032import android.content.pm.ApplicationInfo;
33import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070034import android.content.pm.PackageManager;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010035import android.content.res.Resources;
36import android.graphics.Color;
37import android.net.IIpConnectivityMetrics;
Tony Mak2f26b792016-11-28 17:54:51 +000038import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080039import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080040import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070041import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000042import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080043import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070044import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070045import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010046import android.os.UserManagerInternal;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080047import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000048import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080049import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000050import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010051import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070052import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070053
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010054import com.android.internal.R;
Alan Treadwayafad8782016-01-19 15:15:08 +000055import com.android.server.LocalServices;
56import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000057import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000058
Makoto Onukib643fb02015-09-22 15:03:44 -070059import org.mockito.invocation.InvocationOnMock;
60import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061
Makoto Onukic8a5a552015-11-19 14:29:12 -080062import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000063import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000064import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070065import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070066import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070067import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010068import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000069import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070070
Edman Anjosf9946772016-11-28 16:35:15 +010071import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
72import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
73
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070074import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070075import static org.mockito.Matchers.anyInt;
Michal Karpinskid084ca52017-01-18 15:54:18 +000076import static org.mockito.Matchers.anyLong;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010077import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070078import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070079import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070080import static org.mockito.Matchers.isNull;
Esteban Talavera548a04b2016-12-20 15:22:30 +000081import static org.mockito.Mockito.atLeast;
Makoto Onukib643fb02015-09-22 15:03:44 -070082import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070083import static org.mockito.Mockito.doReturn;
Robin Leed2a73ed2016-12-19 09:07:16 +000084import static org.mockito.Mockito.never;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080085import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070086import static org.mockito.Mockito.times;
87import static org.mockito.Mockito.verify;
88import static org.mockito.Mockito.when;
89
90/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070091 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +000092 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070093 m FrameworksServicesTests &&
94 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000095 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070096 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080097 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098
99 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000100 *
101 * , or:
102 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000104@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700105public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000106 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
107 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
108 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
109
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700110 private DpmMockContext mContext;
111 public DevicePolicyManager dpm;
112 public DevicePolicyManagerServiceTestable dpms;
113
114 @Override
115 protected void setUp() throws Exception {
116 super.setUp();
117
118 mContext = getContext();
119
120 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
121 .thenReturn(true);
122
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800123 // By default, pretend all users are running and unlocked.
124 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
125
Makoto Onukia52562c2015-10-01 16:12:31 -0700126 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700127
Makoto Onukid932f762015-09-29 16:53:38 -0700128 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
129 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
130 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800131 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700132
Makoto Onukib643fb02015-09-22 15:03:44 -0700133 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700134 }
135
Makoto Onukia52562c2015-10-01 16:12:31 -0700136 private void initializeDpms() {
137 // Need clearCallingIdentity() to pass permission checks.
138 final long ident = mContext.binder.clearCallingIdentity();
139 try {
140 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
141
142 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
143
144 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
145 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
146
147 dpm = new DevicePolicyManagerTestable(mContext, dpms);
148 } finally {
149 mContext.binder.restoreCallingIdentity(ident);
150 }
151 }
152
Makoto Onukib643fb02015-09-22 15:03:44 -0700153 private void setUpUserManager() {
154 // Emulate UserManager.set/getApplicationRestriction().
155 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
156
157 // UM.setApplicationRestrictions() will save to appRestrictions.
158 doAnswer(new Answer<Void>() {
159 @Override
160 public Void answer(InvocationOnMock invocation) throws Throwable {
161 String pkg = (String) invocation.getArguments()[0];
162 Bundle bundle = (Bundle) invocation.getArguments()[1];
163 UserHandle user = (UserHandle) invocation.getArguments()[2];
164
165 appRestrictions.put(Pair.create(pkg, user), bundle);
166
167 return null;
168 }
169 }).when(mContext.userManager).setApplicationRestrictions(
170 anyString(), any(Bundle.class), any(UserHandle.class));
171
172 // UM.getApplicationRestrictions() will read from appRestrictions.
173 doAnswer(new Answer<Bundle>() {
174 @Override
175 public Bundle answer(InvocationOnMock invocation) throws Throwable {
176 String pkg = (String) invocation.getArguments()[0];
177 UserHandle user = (UserHandle) invocation.getArguments()[1];
178
179 return appRestrictions.get(Pair.create(pkg, user));
180 }
181 }).when(mContext.userManager).getApplicationRestrictions(
182 anyString(), any(UserHandle.class));
183
Makoto Onukid932f762015-09-29 16:53:38 -0700184 // Add the first secondary user.
185 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700186 }
187
188 private void setAsProfileOwner(ComponentName admin) {
189 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
190 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
191
Makoto Onukia4f11972015-10-01 13:19:58 -0700192 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700193 dpm.setActiveAdmin(admin, /* replace =*/ false);
194
195 // Fire!
196 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
197
198 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700199 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700200 }
201
202 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700203 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
204 .thenReturn(false);
205
206 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
207 new DevicePolicyManagerServiceTestable(mContext, dataDir);
208
209 // If the device has no DPMS feature, it shouldn't register the local service.
210 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
211 }
212
213 /**
214 * Caller doesn't have proper permissions.
215 */
216 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700217 // 1. Failure cases.
218
219 // Caller doesn't have MANAGE_DEVICE_ADMINS.
220 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700221 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700222 fail("Didn't throw SecurityException");
223 } catch (SecurityException expected) {
224 }
225
226 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
227 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
228 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700229 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700230 fail("Didn't throw SecurityException");
231 } catch (SecurityException expected) {
232 }
233 }
234
Makoto Onukif76b06a2015-09-22 15:03:44 -0700235 /**
236 * Test for:
237 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800238 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700239 * {@link DevicePolicyManager#isAdminActive}
240 * {@link DevicePolicyManager#isAdminActiveAsUser}
241 * {@link DevicePolicyManager#getActiveAdmins}
242 * {@link DevicePolicyManager#getActiveAdminsAsUser}
243 */
244 public void testSetActiveAdmin() throws Exception {
245 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700246 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
247
Makoto Onukif76b06a2015-09-22 15:03:44 -0700248 // 2. Call the API.
249 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700250
251 // 3. Verify internal calls.
252
253 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700254 verify(mContext.spiedContext).sendBroadcastAsUser(
255 MockUtils.checkIntentAction(
256 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
257 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
258 verify(mContext.spiedContext).sendBroadcastAsUser(
259 MockUtils.checkIntentAction(
260 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700261 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
262
Makoto Onukif76b06a2015-09-22 15:03:44 -0700263 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
264 eq(admin1.getPackageName()),
265 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
266 eq(PackageManager.DONT_KILL_APP),
267 eq(DpmMockContext.CALLER_USER_HANDLE),
268 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700269
270 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700271
272 // Make sure it's active admin1.
273 assertTrue(dpm.isAdminActive(admin1));
274 assertFalse(dpm.isAdminActive(admin2));
275 assertFalse(dpm.isAdminActive(admin3));
276
277 // But not admin1 for a different user.
278
279 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
280 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
281 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
282
283 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
284 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
285
286 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
287
288 // Next, add one more admin.
289 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700290 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
291 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700292
293 dpm.setActiveAdmin(admin2, /* replace =*/ false);
294
295 // Now we have two admins.
296 assertTrue(dpm.isAdminActive(admin1));
297 assertTrue(dpm.isAdminActive(admin2));
298 assertFalse(dpm.isAdminActive(admin3));
299
300 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
301 // again. (times(1) because it was previously called for admin1)
302 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
303 eq(admin1.getPackageName()),
304 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
305 eq(PackageManager.DONT_KILL_APP),
306 eq(DpmMockContext.CALLER_USER_HANDLE),
307 anyString());
308
309 // 4. Add the same admin1 again without replace, which should throw.
310 try {
311 dpm.setActiveAdmin(admin1, /* replace =*/ false);
312 fail("Didn't throw");
313 } catch (IllegalArgumentException expected) {
314 }
315
316 // 5. Add the same admin1 again with replace, which should succeed.
317 dpm.setActiveAdmin(admin1, /* replace =*/ true);
318
319 // TODO make sure it's replaced.
320
321 // 6. Test getActiveAdmins()
322 List<ComponentName> admins = dpm.getActiveAdmins();
323 assertEquals(2, admins.size());
324 assertEquals(admin1, admins.get(0));
325 assertEquals(admin2, admins.get(1));
326
327 // Another user has no admins.
328 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
329
330 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
331 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
332
333 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
334 }
335
Makoto Onukid932f762015-09-29 16:53:38 -0700336 public void testSetActiveAdmin_multiUsers() throws Exception {
337
338 final int ANOTHER_USER_ID = 100;
339 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
340
341 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
342
343 // Set up pacakge manager for the other user.
344 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700345
346 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
347
348 dpm.setActiveAdmin(admin1, /* replace =*/ false);
349
350 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
351 dpm.setActiveAdmin(admin2, /* replace =*/ false);
352
353
354 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
355 assertTrue(dpm.isAdminActive(admin1));
356 assertFalse(dpm.isAdminActive(admin2));
357
358 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
359 assertFalse(dpm.isAdminActive(admin1));
360 assertTrue(dpm.isAdminActive(admin2));
361 }
362
Makoto Onukif76b06a2015-09-22 15:03:44 -0700363 /**
364 * Test for:
365 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800366 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700367 */
368 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
369 // 1. Make sure the caller has proper permissions.
370 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
371
372 dpm.setActiveAdmin(admin1, /* replace =*/ false);
373 assertTrue(dpm.isAdminActive(admin1));
374
375 // Add the same admin1 again without replace, which should throw.
376 try {
377 dpm.setActiveAdmin(admin1, /* replace =*/ false);
378 fail("Didn't throw");
379 } catch (IllegalArgumentException expected) {
380 }
381 }
382
383 /**
384 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800385 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
386 * BIND_DEVICE_ADMIN.
387 */
388 public void testSetActiveAdmin_permissionCheck() throws Exception {
389 // 1. Make sure the caller has proper permissions.
390 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
391
392 try {
393 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
394 fail();
395 } catch (IllegalArgumentException expected) {
396 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
397 }
398 assertFalse(dpm.isAdminActive(adminNoPerm));
399
400 // Change the target API level to MNC. Now it can be set as DA.
401 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
402 VERSION_CODES.M);
403 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
404 assertTrue(dpm.isAdminActive(adminNoPerm));
405
406 // TODO Test the "load from the file" case where DA will still be loaded even without
407 // BIND_DEVICE_ADMIN and target API is N.
408 }
409
410 /**
411 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700412 * {@link DevicePolicyManager#removeActiveAdmin}
413 */
414 public void testRemoveActiveAdmin_SecurityException() {
415 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
416
417 // Add admin.
418
419 dpm.setActiveAdmin(admin1, /* replace =*/ false);
420
421 assertTrue(dpm.isAdminActive(admin1));
422
423 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
424
425 // Directly call the DPMS method with a different userid, which should fail.
426 try {
427 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
428 fail("Didn't throw SecurityException");
429 } catch (SecurityException expected) {
430 }
431
432 // Try to remove active admin with a different caller userid should fail too, without
433 // having MANAGE_DEVICE_ADMINS.
434 mContext.callerPermissions.clear();
435
Makoto Onukid932f762015-09-29 16:53:38 -0700436 // Change the caller, and call into DPMS directly with a different user-id.
437
Makoto Onukif76b06a2015-09-22 15:03:44 -0700438 mContext.binder.callingUid = 1234567;
439 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700440 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700441 fail("Didn't throw SecurityException");
442 } catch (SecurityException expected) {
443 }
444 }
445
446 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800447 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
448 * (because we can't send the remove broadcast).
449 */
450 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
451 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
452
453 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
454
455 // Add admin.
456
457 dpm.setActiveAdmin(admin1, /* replace =*/ false);
458
459 assertTrue(dpm.isAdminActive(admin1));
460
461 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
462
463 // 1. User not unlocked.
464 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
465 .thenReturn(false);
466 try {
467 dpm.removeActiveAdmin(admin1);
468 fail("Didn't throw IllegalStateException");
469 } catch (IllegalStateException expected) {
470 MoreAsserts.assertContainsRegex(
471 "User must be running and unlocked", expected.getMessage());
472 }
473
474 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
475
476 // 2. User unlocked.
477 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
478 .thenReturn(true);
479
480 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700481 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800482 }
483
484 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700485 * Test for:
486 * {@link DevicePolicyManager#removeActiveAdmin}
487 */
Makoto Onukid932f762015-09-29 16:53:38 -0700488 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700489 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
490
491 // Add admin1.
492
493 dpm.setActiveAdmin(admin1, /* replace =*/ false);
494
495 assertTrue(dpm.isAdminActive(admin1));
496 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
497
498 // Different user, but should work, because caller has proper permissions.
499 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700500
501 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700502 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700503
504 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700505 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700506
507 // TODO DO Still can't be removed in this case.
508 }
509
510 /**
511 * Test for:
512 * {@link DevicePolicyManager#removeActiveAdmin}
513 */
514 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
515 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
516 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
517
518 // Add admin1.
519
520 dpm.setActiveAdmin(admin1, /* replace =*/ false);
521
522 assertTrue(dpm.isAdminActive(admin1));
523 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
524
525 // Broadcast from saveSettingsLocked().
526 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
527 MockUtils.checkIntentAction(
528 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
529 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
530
531 // Remove. No permissions, but same user, so it'll work.
532 mContext.callerPermissions.clear();
533 dpm.removeActiveAdmin(admin1);
534
Makoto Onukif76b06a2015-09-22 15:03:44 -0700535 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
536 MockUtils.checkIntentAction(
537 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
538 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
539 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700540 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700541 eq(dpms.mHandler),
542 eq(Activity.RESULT_OK),
543 isNull(String.class),
544 isNull(Bundle.class));
545
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700546 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700547
548 // Again broadcast from saveSettingsLocked().
549 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
550 MockUtils.checkIntentAction(
551 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
552 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
553
554 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700555 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700556
557 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000558 * Test for: @{link DevicePolicyManager#setActivePasswordState}
559 *
560 * Validates that when the password for a user changes, the notification broadcast intent
561 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
562 * addition to ones in the original user.
563 */
564 public void testSetActivePasswordState_sendToProfiles() throws Exception {
565 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
566
567 final int MANAGED_PROFILE_USER_ID = 78;
568 final int MANAGED_PROFILE_ADMIN_UID =
569 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
570
571 // Setup device owner.
572 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
573 mContext.packageName = admin1.getPackageName();
574 setupDeviceOwner();
575
576 // Add a managed profile belonging to the system user.
577 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
578
579 // Change the parent user's password.
580 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
581
582 // Both the device owner and the managed profile owner should receive this broadcast.
583 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
584 intent.setComponent(admin1);
585 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
586
587 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
588 MockUtils.checkIntent(intent),
589 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
590 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
591 MockUtils.checkIntent(intent),
592 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
593 }
594
595 /**
596 * Test for: @{link DevicePolicyManager#setActivePasswordState}
597 *
598 * Validates that when the password for a managed profile changes, the notification broadcast
599 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
600 * its parent.
601 */
602 public void testSetActivePasswordState_notSentToParent() throws Exception {
603 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
604
605 final int MANAGED_PROFILE_USER_ID = 78;
606 final int MANAGED_PROFILE_ADMIN_UID =
607 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
608
609 // Setup device owner.
610 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
611 mContext.packageName = admin1.getPackageName();
612 doReturn(true).when(mContext.lockPatternUtils)
613 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
614 setupDeviceOwner();
615
616 // Add a managed profile belonging to the system user.
617 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
618
619 // Change the profile's password.
620 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
621
622 // Both the device owner and the managed profile owner should receive this broadcast.
623 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
624 intent.setComponent(admin1);
625 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
626
627 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
628 MockUtils.checkIntent(intent),
629 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
630 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
631 MockUtils.checkIntent(intent),
632 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
633 }
634 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000635 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700636 */
637 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000638 setDeviceOwner();
639
640 // Try to set a profile owner on the same user, which should fail.
641 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
642 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
643 try {
644 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
645 fail("IllegalStateException not thrown");
646 } catch (IllegalStateException expected) {
647 assertTrue("Message was: " + expected.getMessage(),
648 expected.getMessage().contains("already has a device owner"));
649 }
650
651 // DO admin can't be deactivated.
652 dpm.removeActiveAdmin(admin1);
653 assertTrue(dpm.isAdminActive(admin1));
654
655 // TODO Test getDeviceOwnerName() too. To do so, we need to change
656 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
657 }
658
659 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700660 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800661 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700662 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
663 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
664
Makoto Onukid932f762015-09-29 16:53:38 -0700665 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700666 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
667
Makoto Onukid932f762015-09-29 16:53:38 -0700668 // Make sure admin1 is installed on system user.
669 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700670
Makoto Onukic8a5a552015-11-19 14:29:12 -0800671 // Check various get APIs.
672 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
673
Makoto Onukib643fb02015-09-22 15:03:44 -0700674 // DO needs to be an DA.
675 dpm.setActiveAdmin(admin1, /* replace =*/ false);
676
677 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700678 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700679
Makoto Onukic8a5a552015-11-19 14:29:12 -0800680 // getDeviceOwnerComponent should return the admin1 component.
681 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
682 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
683
684 // Check various get APIs.
685 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
686
687 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
688 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
689 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
690 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
691
692 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
693
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000694 // Verify internal calls.
695 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
696 eq(admin1.getPackageName()));
697
Makoto Onukib643fb02015-09-22 15:03:44 -0700698 // TODO We should check if the caller has called clearCallerIdentity().
699 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
700 eq(UserHandle.USER_SYSTEM), eq(false));
701
702 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
703 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
704 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
705
Makoto Onukic8a5a552015-11-19 14:29:12 -0800706 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700707 }
708
Makoto Onukic8a5a552015-11-19 14:29:12 -0800709 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
710 final int origCallingUser = mContext.binder.callingUid;
711 final List origPermissions = new ArrayList(mContext.callerPermissions);
712 mContext.callerPermissions.clear();
713
714 mContext.callerPermissions.add(permission.MANAGE_USERS);
715
716 mContext.binder.callingUid = Process.SYSTEM_UID;
717
718 // TODO Test getDeviceOwnerName() too. To do so, we need to change
719 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
720 if (hasDeviceOwner) {
721 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
722 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
723 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
724
725 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
726 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
727 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
728 } else {
729 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
730 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
731 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
732
733 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
734 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
735 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
736 }
737
738 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
739 if (hasDeviceOwner) {
740 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
741 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
742 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
743
744 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
745 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
746 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
747 } else {
748 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
749 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
750 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
751
752 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
753 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
754 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
755 }
756
757 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
758 // Still with MANAGE_USERS.
759 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
760 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
761 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
762
763 if (hasDeviceOwner) {
764 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
765 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
766 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
767 } else {
768 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
769 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
770 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
771 }
772
773 mContext.binder.callingUid = Process.SYSTEM_UID;
774 mContext.callerPermissions.remove(permission.MANAGE_USERS);
775 // System can still call "OnAnyUser" without MANAGE_USERS.
776 if (hasDeviceOwner) {
777 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
778 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
779 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
780
781 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
782 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
783 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
784 } else {
785 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
786 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
787 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
788
789 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
790 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
791 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
792 }
793
794 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
795 // Still no MANAGE_USERS.
796 if (hasDeviceOwner) {
797 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
798 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
799 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
800 } else {
801 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
802 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
803 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
804 }
805
806 try {
807 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
808 fail();
809 } catch (SecurityException expected) {
810 }
811 try {
812 dpm.getDeviceOwnerComponentOnAnyUser();
813 fail();
814 } catch (SecurityException expected) {
815 }
816 try {
817 dpm.getDeviceOwnerUserId();
818 fail();
819 } catch (SecurityException expected) {
820 }
821 try {
822 dpm.getDeviceOwnerNameOnAnyUser();
823 fail();
824 } catch (SecurityException expected) {
825 }
826
827 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
828 // Still no MANAGE_USERS.
829 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
830 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
831 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
832
833 try {
834 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
835 fail();
836 } catch (SecurityException expected) {
837 }
838 try {
839 dpm.getDeviceOwnerComponentOnAnyUser();
840 fail();
841 } catch (SecurityException expected) {
842 }
843 try {
844 dpm.getDeviceOwnerUserId();
845 fail();
846 } catch (SecurityException expected) {
847 }
848 try {
849 dpm.getDeviceOwnerNameOnAnyUser();
850 fail();
851 } catch (SecurityException expected) {
852 }
853
854 // Restore.
855 mContext.binder.callingUid = origCallingUser;
856 mContext.callerPermissions.addAll(origPermissions);
857 }
858
859
Makoto Onukib643fb02015-09-22 15:03:44 -0700860 /**
861 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
862 */
863 public void testSetDeviceOwner_noSuchPackage() {
864 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800865 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700866 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
867 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
868
869 // Call from a process on the system user.
870 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
871
Makoto Onukib643fb02015-09-22 15:03:44 -0700872 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700873 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700874 fail("Didn't throw IllegalArgumentException");
875 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700876 assertTrue("Message was: " + expected.getMessage(),
877 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700878 }
879 }
880
881 public void testSetDeviceOwner_failures() throws Exception {
882 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
883 }
884
Makoto Onukia52562c2015-10-01 16:12:31 -0700885 public void testClearDeviceOwner() throws Exception {
886 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800887 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700888 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
889 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
890
891 // Set admin1 as a DA to the secondary user.
892 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
893
894 dpm.setActiveAdmin(admin1, /* replace =*/ false);
895
896 // Set admin 1 as the DO to the system user.
897
898 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
899 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
900 dpm.setActiveAdmin(admin1, /* replace =*/ false);
901 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
902
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000903 // Verify internal calls.
904 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
905 eq(admin1.getPackageName()));
906
Makoto Onukic8a5a552015-11-19 14:29:12 -0800907 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700908
Makoto Onuki90b89652016-01-28 14:44:18 -0800909 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
910
911 assertTrue(dpm.isAdminActive(admin1));
912 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
913
Makoto Onukia52562c2015-10-01 16:12:31 -0700914 // Set up other mocks.
915 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
916
917 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700918 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700919 eq(admin1.getPackageName()),
920 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800921
922 // But first pretend the user is locked. Then it should fail.
923 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
924 try {
925 dpm.clearDeviceOwnerApp(admin1.getPackageName());
926 fail("Didn't throw IllegalStateException");
927 } catch (IllegalStateException expected) {
928 MoreAsserts.assertContainsRegex(
929 "User must be running and unlocked", expected.getMessage());
930 }
931
932 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800933 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700934 dpm.clearDeviceOwnerApp(admin1.getPackageName());
935
936 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800937 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700938
Makoto Onuki90b89652016-01-28 14:44:18 -0800939 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
940 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100941 eq(null),
942 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800943
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700944 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100945
946 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
947 // and once for clearing it.
948 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
949 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
950 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700951 // TODO Check other calls.
952 }
953
954 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
955 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800956 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700957 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
958 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
959
960 // Set admin1 as a DA to the secondary user.
961 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
962
963 dpm.setActiveAdmin(admin1, /* replace =*/ false);
964
965 // Set admin 1 as the DO to the system user.
966
967 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
968 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
969 dpm.setActiveAdmin(admin1, /* replace =*/ false);
970 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
971
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000972 // Verify internal calls.
973 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
974 eq(admin1.getPackageName()));
975
Makoto Onukic8a5a552015-11-19 14:29:12 -0800976 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700977
978 // Now call clear from the secondary user, which should throw.
979 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
980
981 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700982 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700983 eq(admin1.getPackageName()),
984 anyInt());
985 try {
986 dpm.clearDeviceOwnerApp(admin1.getPackageName());
987 fail("Didn't throw");
988 } catch (SecurityException e) {
989 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
990 }
991
Makoto Onukic8a5a552015-11-19 14:29:12 -0800992 // DO shouldn't be removed.
993 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700994 }
995
Makoto Onukib643fb02015-09-22 15:03:44 -0700996 public void testSetProfileOwner() throws Exception {
997 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700998
Makoto Onuki90b89652016-01-28 14:44:18 -0800999 // PO admin can't be deactivated.
1000 dpm.removeActiveAdmin(admin1);
1001 assertTrue(dpm.isAdminActive(admin1));
1002
Makoto Onuki803d6752015-10-30 12:58:39 -07001003 // Try setting DO on the same user, which should fail.
1004 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1005 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1006 try {
1007 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1008 fail("IllegalStateException not thrown");
1009 } catch (IllegalStateException expected) {
1010 assertTrue("Message was: " + expected.getMessage(),
1011 expected.getMessage().contains("already has a profile owner"));
1012 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001013 }
1014
Makoto Onuki90b89652016-01-28 14:44:18 -08001015 public void testClearProfileOwner() throws Exception {
1016 setAsProfileOwner(admin1);
1017
1018 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1019
1020 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1021 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1022
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001023 // First try when the user is locked, which should fail.
1024 when(mContext.userManager.isUserUnlocked(anyInt()))
1025 .thenReturn(false);
1026 try {
1027 dpm.clearProfileOwner(admin1);
1028 fail("Didn't throw IllegalStateException");
1029 } catch (IllegalStateException expected) {
1030 MoreAsserts.assertContainsRegex(
1031 "User must be running and unlocked", expected.getMessage());
1032 }
1033 // Clear, really.
1034 when(mContext.userManager.isUserUnlocked(anyInt()))
1035 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001036 dpm.clearProfileOwner(admin1);
1037
1038 // Check
1039 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001040 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001041 }
1042
Makoto Onukib643fb02015-09-22 15:03:44 -07001043 public void testSetProfileOwner_failures() throws Exception {
1044 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1045 }
1046
Makoto Onukia52562c2015-10-01 16:12:31 -07001047 public void testGetDeviceOwnerAdminLocked() throws Exception {
1048 checkDeviceOwnerWithMultipleDeviceAdmins();
1049 }
1050
1051 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1052 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1053 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1054 // make sure it gets the right component from the right user.
1055
1056 final int ANOTHER_USER_ID = 100;
1057 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1058
1059 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1060
1061 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001062 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001063 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1064 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1065
1066 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1067
Victor Change29cd472016-03-02 20:57:42 +00001068 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1069
Makoto Onukia52562c2015-10-01 16:12:31 -07001070 // Make sure the admin packge is installed to each user.
1071 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1072 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1073
1074 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1075 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1076
1077 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1078
1079
1080 // Set active admins to the users.
1081 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1082 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1083
1084 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1085 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1086
1087 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1088
1089 // Set DO on the first non-system user.
1090 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1091 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1092
Makoto Onukic8a5a552015-11-19 14:29:12 -08001093 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001094
1095 // Then check getDeviceOwnerAdminLocked().
1096 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1097 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1098 }
1099
1100 /**
1101 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001102 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1103 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001104 *
1105 * We didn't use to persist the DO component class name, but now we do, and the above method
1106 * finds the right component from a package name upon migration.
1107 */
1108 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001109 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001110 checkDeviceOwnerWithMultipleDeviceAdmins();
1111
1112 // Overwrite the device owner setting and clears the clas name.
1113 dpms.mOwners.setDeviceOwner(
1114 new ComponentName(admin2.getPackageName(), ""),
1115 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1116 dpms.mOwners.writeDeviceOwner();
1117
1118 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001119 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001120
1121 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001122 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1123 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001124 initializeDpms();
1125
1126 // Now the DO component name is a full name.
1127 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1128 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001129 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001130 }
1131
Makoto Onukib643fb02015-09-22 15:03:44 -07001132 public void testSetGetApplicationRestriction() {
1133 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001134 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001135
1136 {
1137 Bundle rest = new Bundle();
1138 rest.putString("KEY_STRING", "Foo1");
1139 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1140 }
1141
1142 {
1143 Bundle rest = new Bundle();
1144 rest.putString("KEY_STRING", "Foo2");
1145 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1146 }
1147
1148 {
1149 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1150 assertNotNull(returned);
1151 assertEquals(returned.size(), 1);
1152 assertEquals(returned.get("KEY_STRING"), "Foo1");
1153 }
1154
1155 {
1156 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1157 assertNotNull(returned);
1158 assertEquals(returned.size(), 1);
1159 assertEquals(returned.get("KEY_STRING"), "Foo2");
1160 }
1161
1162 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1163 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1164 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001165
Edman Anjosf9946772016-11-28 16:35:15 +01001166 /**
1167 * Setup a package in the package manager mock. Useful for faking installed applications.
1168 *
1169 * @param packageName the name of the package to be setup
1170 * @param appId the application ID to be given to the package
1171 * @return the UID of the package as known by the mock package manager
1172 */
1173 private int setupPackageInPackageManager(final String packageName, final int appId)
1174 throws Exception {
1175 // Make the PackageManager return the package instead of throwing a NameNotFoundException
1176 final PackageInfo pi = new PackageInfo();
1177 pi.applicationInfo = new ApplicationInfo();
1178 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1179 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1180 eq(packageName),
1181 anyInt(),
1182 eq(DpmMockContext.CALLER_USER_HANDLE));
1183 // Setup application UID with the PackageManager
1184 final int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, appId);
1185 doReturn(uid).when(mContext.packageManager).getPackageUidAsUser(
1186 eq(packageName),
1187 eq(DpmMockContext.CALLER_USER_HANDLE));
1188 // Associate packageName to uid
1189 doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid));
1190 doReturn(new String[]{packageName})
1191 .when(mContext.ipackageManager).getPackagesForUid(eq(uid));
1192 return uid;
1193 }
1194
1195 /**
1196 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1197 * privileges can acually be exercised by a delegate are not covered here.
1198 */
1199 public void testDelegation() throws Exception {
1200 setAsProfileOwner(admin1);
1201
1202 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1203
1204 // Given two packages
1205 final String CERT_DELEGATE = "com.delegate.certs";
1206 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1207 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1208 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1209 20989);
1210
1211 // On delegation
1212 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1213 mContext.packageName = admin1.getPackageName();
1214 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1215 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1216
1217 // DPMS correctly stores and retrieves the delegates
1218 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1219 assertEquals(2, policy.mDelegationMap.size());
1220 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1221 DELEGATION_CERT_INSTALL);
1222 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1223 DELEGATION_CERT_INSTALL);
1224 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1225 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1226 DELEGATION_APP_RESTRICTIONS);
1227 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1228 DELEGATION_APP_RESTRICTIONS);
1229 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1230
1231 // On calling install certificate APIs from an unauthorized process
1232 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1233 mContext.packageName = RESTRICTIONS_DELEGATE;
1234
1235 // DPMS throws a SecurityException
1236 try {
1237 dpm.installCaCert(null, null);
1238 fail("Didn't throw SecurityException on unauthorized access");
1239 } catch (SecurityException expected) {
1240 }
1241
1242 // On calling install certificate APIs from an authorized process
1243 mContext.binder.callingUid = CERT_DELEGATE_UID;
1244 mContext.packageName = CERT_DELEGATE;
1245
1246 // DPMS executes without a SecurityException
1247 try {
1248 dpm.installCaCert(null, null);
1249 } catch (SecurityException unexpected) {
1250 fail("Threw SecurityException on authorized access");
1251 } catch (NullPointerException expected) {
1252 }
1253
1254 // On removing a delegate
1255 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1256 mContext.packageName = admin1.getPackageName();
1257 dpm.setCertInstallerPackage(admin1, null);
1258
1259 // DPMS does not allow access to ex-delegate
1260 mContext.binder.callingUid = CERT_DELEGATE_UID;
1261 mContext.packageName = CERT_DELEGATE;
1262 try {
1263 dpm.installCaCert(null, null);
1264 fail("Didn't throw SecurityException on unauthorized access");
1265 } catch (SecurityException expected) {
1266 }
1267
1268 // But still allows access to other existing delegates
1269 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1270 mContext.packageName = RESTRICTIONS_DELEGATE;
1271 try {
1272 dpm.getApplicationRestrictions(null, "pkg");
1273 } catch (SecurityException expected) {
1274 fail("Threw SecurityException on authorized access");
1275 }
1276 }
1277
Esteban Talaverabf60f722015-12-10 16:26:44 +00001278 public void testApplicationRestrictionsManagingApp() throws Exception {
1279 setAsProfileOwner(admin1);
1280
Rubin Xued1928a2016-02-11 17:23:06 +00001281 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001282 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1283 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001284 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1285 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001286
Esteban Talaverabf60f722015-12-10 16:26:44 +00001287 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1288 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001289 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1290 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001291 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1292 Bundle rest = new Bundle();
1293 rest.putString("KEY_STRING", "Foo1");
1294 try {
1295 dpm.setApplicationRestrictions(null, "pkg1", rest);
1296 fail("Didn't throw expected SecurityException");
1297 } catch (SecurityException expected) {
1298 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001299 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1300 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001301 }
1302 try {
1303 dpm.getApplicationRestrictions(null, "pkg1");
1304 fail("Didn't throw expected SecurityException");
1305 } catch (SecurityException expected) {
1306 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001307 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1308 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001309 }
1310
1311 // Check via the profile owner that no restrictions were set.
1312 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001313 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001314 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1315
Rubin Xued1928a2016-02-11 17:23:06 +00001316 // Check the API does not allow setting a non-existent package
1317 try {
1318 dpm.setApplicationRestrictionsManagingPackage(admin1,
1319 nonExistAppRestrictionsManagerPackage);
1320 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001321 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001322 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001323 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001324 }
1325
Esteban Talaverabf60f722015-12-10 16:26:44 +00001326 // Let appRestrictionsManagerPackage manage app restrictions
1327 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1328 assertEquals(appRestrictionsManagerPackage,
1329 dpm.getApplicationRestrictionsManagingPackage(admin1));
1330
1331 // Now that package should be able to set and retrieve app restrictions.
1332 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001333 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001334 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1335 dpm.setApplicationRestrictions(null, "pkg1", rest);
1336 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1337 assertEquals(1, returned.size(), 1);
1338 assertEquals("Foo1", returned.get("KEY_STRING"));
1339
1340 // The same app running on a separate user shouldn't be able to manage app restrictions.
1341 mContext.binder.callingUid = UserHandle.getUid(
1342 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1343 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1344 try {
1345 dpm.setApplicationRestrictions(null, "pkg1", rest);
1346 fail("Didn't throw expected SecurityException");
1347 } catch (SecurityException expected) {
1348 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001349 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1350 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001351 }
1352
1353 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1354 // too.
1355 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001356 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001357 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1358 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1359 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1360
1361 // Removing the ability for the package to manage app restrictions.
1362 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1363 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1364 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001365 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001366 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1367 try {
1368 dpm.setApplicationRestrictions(null, "pkg1", null);
1369 fail("Didn't throw expected SecurityException");
1370 } catch (SecurityException expected) {
1371 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001372 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1373 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001374 }
1375 }
1376
Makoto Onukia4f11972015-10-01 13:19:58 -07001377 public void testSetUserRestriction_asDo() throws Exception {
1378 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001379 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001380 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1381 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1382
1383 // First, set DO.
1384
1385 // Call from a process on the system user.
1386 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1387
1388 // Make sure admin1 is installed on system user.
1389 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001390
1391 // Call.
1392 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001393 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001394 UserHandle.USER_SYSTEM));
1395
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001396 // Check that the user restrictions that are enabled by default are set. Then unset them.
1397 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001398 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001399 DpmTestUtils.assertRestrictions(
1400 DpmTestUtils.newRestrictions(defaultRestrictions),
1401 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1402 );
1403 DpmTestUtils.assertRestrictions(
1404 DpmTestUtils.newRestrictions(defaultRestrictions),
1405 dpm.getUserRestrictions(admin1)
1406 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001407 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1408 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001409 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001410 eq(true) /* isDeviceOwner */,
1411 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001412 );
1413 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001414
1415 for (String restriction : defaultRestrictions) {
1416 dpm.clearUserRestriction(admin1, restriction);
1417 }
1418
Esteban Talavera548a04b2016-12-20 15:22:30 +00001419 assertNoDeviceOwnerRestrictions();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001420 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001421
1422 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1423 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1424 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001425 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1426 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001427 reset(mContext.userManagerInternal);
1428
Makoto Onukia4f11972015-10-01 13:19:58 -07001429 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001430 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1431 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001432 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1433 UserManager.DISALLOW_ADD_USER),
1434 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001435 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001436
Makoto Onuki068c54a2015-10-13 14:34:03 -07001437 DpmTestUtils.assertRestrictions(
1438 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001439 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001440 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1441 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001442 DpmTestUtils.assertRestrictions(
1443 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001444 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001445 dpm.getUserRestrictions(admin1)
1446 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001447
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1449 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1450 eq(UserHandle.USER_SYSTEM),
1451 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001452 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001453 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001454
Makoto Onuki068c54a2015-10-13 14:34:03 -07001455 DpmTestUtils.assertRestrictions(
1456 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1457 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1458 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001459 DpmTestUtils.assertRestrictions(
1460 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1461 dpm.getUserRestrictions(admin1)
1462 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001463
1464 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001465 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1466 eq(UserHandle.USER_SYSTEM),
1467 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001468 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001469 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001470
Esteban Talavera548a04b2016-12-20 15:22:30 +00001471 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001472
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001473 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1474 // DO sets them, the scope is global.
1475 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1476 reset(mContext.userManagerInternal);
1477 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1478 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1479 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001480 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001481 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1482 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001483 reset(mContext.userManagerInternal);
1484
1485 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1486 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov6a40f092016-10-25 15:46:51 +01001487 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001488
1489 // More tests.
1490 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1491 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1492 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001493 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1494 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001495 reset(mContext.userManagerInternal);
1496
1497 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1498 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1499 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001500 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001501 UserManager.DISALLOW_ADD_USER),
1502 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001503 reset(mContext.userManagerInternal);
1504
1505 dpm.setCameraDisabled(admin1, true);
1506 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1507 eq(UserHandle.USER_SYSTEM),
1508 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001509 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001510 UserManager.DISALLOW_ADD_USER),
1511 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001512 reset(mContext.userManagerInternal);
1513
1514 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1515 // locally.
1516 dpm.setCameraDisabled(admin1, false);
1517 reset(mContext.userManagerInternal);
1518
1519 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1520 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1521 dpm.setCameraDisabled(admin2, true);
1522
1523 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1524 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001525 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001526 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001527 UserManager.DISALLOW_ADD_USER),
1528 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001529 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001530 // TODO Make sure restrictions are written to the file.
1531 }
1532
1533 public void testSetUserRestriction_asPo() {
1534 setAsProfileOwner(admin1);
1535
Makoto Onuki068c54a2015-10-13 14:34:03 -07001536 DpmTestUtils.assertRestrictions(
1537 DpmTestUtils.newRestrictions(),
1538 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1539 .ensureUserRestrictions()
1540 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001541
1542 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001543 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1544 eq(DpmMockContext.CALLER_USER_HANDLE),
1545 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001546 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001547 reset(mContext.userManagerInternal);
1548
Makoto Onukia4f11972015-10-01 13:19:58 -07001549 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001550 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1551 eq(DpmMockContext.CALLER_USER_HANDLE),
1552 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1553 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001554 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001555 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001556
Makoto Onuki068c54a2015-10-13 14:34:03 -07001557 DpmTestUtils.assertRestrictions(
1558 DpmTestUtils.newRestrictions(
1559 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1560 UserManager.DISALLOW_OUTGOING_CALLS
1561 ),
1562 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1563 .ensureUserRestrictions()
1564 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001565 DpmTestUtils.assertRestrictions(
1566 DpmTestUtils.newRestrictions(
1567 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1568 UserManager.DISALLOW_OUTGOING_CALLS
1569 ),
1570 dpm.getUserRestrictions(admin1)
1571 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001572
1573 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001574 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1575 eq(DpmMockContext.CALLER_USER_HANDLE),
1576 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001577 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001578 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001579
1580 DpmTestUtils.assertRestrictions(
1581 DpmTestUtils.newRestrictions(
1582 UserManager.DISALLOW_OUTGOING_CALLS
1583 ),
1584 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1585 .ensureUserRestrictions()
1586 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001587 DpmTestUtils.assertRestrictions(
1588 DpmTestUtils.newRestrictions(
1589 UserManager.DISALLOW_OUTGOING_CALLS
1590 ),
1591 dpm.getUserRestrictions(admin1)
1592 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001593
1594 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001595 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1596 eq(DpmMockContext.CALLER_USER_HANDLE),
1597 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001598 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001599 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001600
Makoto Onuki068c54a2015-10-13 14:34:03 -07001601 DpmTestUtils.assertRestrictions(
1602 DpmTestUtils.newRestrictions(),
1603 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1604 .ensureUserRestrictions()
1605 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001606 DpmTestUtils.assertRestrictions(
1607 DpmTestUtils.newRestrictions(),
1608 dpm.getUserRestrictions(admin1)
1609 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001610
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001611 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1612 // though when DO sets them they'll be applied globally.
1613 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1614 reset(mContext.userManagerInternal);
1615 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1616 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1617 eq(DpmMockContext.CALLER_USER_HANDLE),
1618 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1619 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001620 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001621 reset(mContext.userManagerInternal);
1622
1623 dpm.setCameraDisabled(admin1, true);
1624 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1625 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001626 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001627 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001628 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001629 reset(mContext.userManagerInternal);
1630
Makoto Onukia4f11972015-10-01 13:19:58 -07001631 // TODO Make sure restrictions are written to the file.
1632 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001633
Esteban Talavera548a04b2016-12-20 15:22:30 +00001634
1635 public void testDefaultEnabledUserRestrictions() throws Exception {
1636 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1637 mContext.callerPermissions.add(permission.MANAGE_USERS);
1638 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1639 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1640
1641 // First, set DO.
1642
1643 // Call from a process on the system user.
1644 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1645
1646 // Make sure admin1 is installed on system user.
1647 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1648
1649 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1650 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1651 UserHandle.USER_SYSTEM));
1652
1653 // Check that the user restrictions that are enabled by default are set. Then unset them.
1654 String[] defaultRestrictions = UserRestrictionsUtils
1655 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1656 assertTrue(defaultRestrictions.length > 0);
1657 DpmTestUtils.assertRestrictions(
1658 DpmTestUtils.newRestrictions(defaultRestrictions),
1659 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1660 );
1661 DpmTestUtils.assertRestrictions(
1662 DpmTestUtils.newRestrictions(defaultRestrictions),
1663 dpm.getUserRestrictions(admin1)
1664 );
1665 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1666 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001667 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001668 eq(true) /* isDeviceOwner */,
1669 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001670 );
1671 reset(mContext.userManagerInternal);
1672
1673 for (String restriction : defaultRestrictions) {
1674 dpm.clearUserRestriction(admin1, restriction);
1675 }
1676
1677 assertNoDeviceOwnerRestrictions();
1678
1679 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1680 reset(mContext.userManagerInternal);
1681 initializeDpms();
1682 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1683 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1684
1685 assertNoDeviceOwnerRestrictions();
1686
1687 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1688 // is set as it wasn't enabled during setDeviceOwner.
1689 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1690 assertFalse(UserRestrictionsUtils
1691 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1692 UserRestrictionsUtils
1693 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1694 try {
1695 reset(mContext.userManagerInternal);
1696 initializeDpms();
1697 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1698 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1699
1700 DpmTestUtils.assertRestrictions(
1701 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1702 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1703 );
1704 DpmTestUtils.assertRestrictions(
1705 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1706 dpm.getUserRestrictions(admin1)
1707 );
1708 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1709 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001710 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001711 eq(true) /* isDeviceOwner */,
1712 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001713 );
1714 reset(mContext.userManagerInternal);
1715
1716 // Remove the restriction.
1717 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1718
1719 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1720 initializeDpms();
1721 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1722 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1723 assertNoDeviceOwnerRestrictions();
1724 } finally {
1725 UserRestrictionsUtils
1726 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1727 }
1728 }
1729
1730 private void assertNoDeviceOwnerRestrictions() {
1731 DpmTestUtils.assertRestrictions(
1732 DpmTestUtils.newRestrictions(),
1733 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1734 );
1735 DpmTestUtils.assertRestrictions(
1736 DpmTestUtils.newRestrictions(),
1737 dpm.getUserRestrictions(admin1)
1738 );
1739 }
1740
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001741 public void testGetMacAddress() throws Exception {
1742 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1743 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1744 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1745
1746 // In this test, change the caller user to "system".
1747 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1748
1749 // Make sure admin1 is installed on system user.
1750 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1751
1752 // Test 1. Caller doesn't have DO or DA.
1753 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001754 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001755 fail();
1756 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001757 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001758 }
1759
1760 // DO needs to be an DA.
1761 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1762 assertTrue(dpm.isAdminActive(admin1));
1763
1764 // Test 2. Caller has DA, but not DO.
1765 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001766 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001767 fail();
1768 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001769 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001770 }
1771
1772 // Test 3. Caller has PO, but not DO.
1773 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1774 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001775 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001776 fail();
1777 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001778 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001779 }
1780
1781 // Remove PO.
1782 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001783 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001784 // Test 4, Caller is DO now.
1785 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1786
1787 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001788 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001789
1790 // 4-2. Returns WifiInfo, but with the default MAC.
1791 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001792 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001793
1794 // 4-3. With a real MAC address.
1795 final WifiInfo wi = new WifiInfo();
1796 wi.setMacAddress("11:22:33:44:55:66");
1797 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001798 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001799 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001800
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001801 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001802 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1803 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
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 // Set admin1 as DA.
1812 dpm.setActiveAdmin(admin1, false);
1813 assertTrue(dpm.isAdminActive(admin1));
1814 try {
1815 dpm.reboot(admin1);
1816 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1817 } catch (SecurityException expected) {
1818 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1819 }
1820
1821 // Set admin1 as PO.
1822 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1823 try {
1824 dpm.reboot(admin1);
1825 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1826 } catch (SecurityException expected) {
1827 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1828 }
1829
1830 // Remove PO and add DO.
1831 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001832 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001833 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1834
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001835 // admin1 is DO.
1836 // Set current call state of device to ringing.
1837 when(mContext.telephonyManager.getCallState())
1838 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1839 try {
1840 dpm.reboot(admin1);
1841 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1842 } catch (IllegalStateException expected) {
1843 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1844 }
1845
1846 // Set current call state of device to dialing/active.
1847 when(mContext.telephonyManager.getCallState())
1848 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1849 try {
1850 dpm.reboot(admin1);
1851 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1852 } catch (IllegalStateException expected) {
1853 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1854 }
1855
1856 // Set current call state of device to idle.
1857 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001858 dpm.reboot(admin1);
1859 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001860
1861 public void testSetGetSupportText() {
1862 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1863 dpm.setActiveAdmin(admin1, true);
1864 dpm.setActiveAdmin(admin2, true);
1865 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1866
1867 // Null default support messages.
1868 {
1869 assertNull(dpm.getLongSupportMessage(admin1));
1870 assertNull(dpm.getShortSupportMessage(admin1));
1871 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1872 assertNull(dpm.getShortSupportMessageForUser(admin1,
1873 DpmMockContext.CALLER_USER_HANDLE));
1874 assertNull(dpm.getLongSupportMessageForUser(admin1,
1875 DpmMockContext.CALLER_USER_HANDLE));
1876 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1877 }
1878
1879 // Only system can call the per user versions.
1880 {
1881 try {
1882 dpm.getShortSupportMessageForUser(admin1,
1883 DpmMockContext.CALLER_USER_HANDLE);
1884 fail("Only system should be able to call getXXXForUser versions");
1885 } catch (SecurityException expected) {
1886 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1887 }
1888 try {
1889 dpm.getLongSupportMessageForUser(admin1,
1890 DpmMockContext.CALLER_USER_HANDLE);
1891 fail("Only system should be able to call getXXXForUser versions");
1892 } catch (SecurityException expected) {
1893 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1894 }
1895 }
1896
1897 // Can't set message for admin in another uid.
1898 {
1899 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1900 try {
1901 dpm.setShortSupportMessage(admin1, "Some text");
1902 fail("Admins should only be able to change their own support text.");
1903 } catch (SecurityException expected) {
1904 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1905 }
1906 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1907 }
1908
1909 // Set/Get short returns what it sets and other admins text isn't changed.
1910 {
1911 final String supportText = "Some text to test with.";
1912 dpm.setShortSupportMessage(admin1, supportText);
1913 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1914 assertNull(dpm.getLongSupportMessage(admin1));
1915 assertNull(dpm.getShortSupportMessage(admin2));
1916
1917 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1918 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1919 DpmMockContext.CALLER_USER_HANDLE));
1920 assertNull(dpm.getShortSupportMessageForUser(admin2,
1921 DpmMockContext.CALLER_USER_HANDLE));
1922 assertNull(dpm.getLongSupportMessageForUser(admin1,
1923 DpmMockContext.CALLER_USER_HANDLE));
1924 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1925
1926 dpm.setShortSupportMessage(admin1, null);
1927 assertNull(dpm.getShortSupportMessage(admin1));
1928 }
1929
1930 // Set/Get long returns what it sets and other admins text isn't changed.
1931 {
1932 final String supportText = "Some text to test with.\nWith more text.";
1933 dpm.setLongSupportMessage(admin1, supportText);
1934 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1935 assertNull(dpm.getShortSupportMessage(admin1));
1936 assertNull(dpm.getLongSupportMessage(admin2));
1937
1938 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1939 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1940 DpmMockContext.CALLER_USER_HANDLE));
1941 assertNull(dpm.getLongSupportMessageForUser(admin2,
1942 DpmMockContext.CALLER_USER_HANDLE));
1943 assertNull(dpm.getShortSupportMessageForUser(admin1,
1944 DpmMockContext.CALLER_USER_HANDLE));
1945 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1946
1947 dpm.setLongSupportMessage(admin1, null);
1948 assertNull(dpm.getLongSupportMessage(admin1));
1949 }
1950 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001951
1952 /**
1953 * Test for:
1954 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001955 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001956 * {@link DevicePolicyManager#isAffiliatedUser}
1957 */
1958 public void testUserAffiliation() throws Exception {
1959 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1960 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1961 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1962
1963 // Check that the system user is unaffiliated.
1964 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1965 assertFalse(dpm.isAffiliatedUser());
1966
1967 // Set a device owner on the system user. Check that the system user becomes affiliated.
1968 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1969 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1970 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1971 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001972 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001973
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001974 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001975 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1976 setAsProfileOwner(admin2);
1977 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001978 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001979
1980 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1981 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001982 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001983 userAffiliationIds.add("red");
1984 userAffiliationIds.add("green");
1985 userAffiliationIds.add("blue");
1986 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001987 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001988 assertFalse(dpm.isAffiliatedUser());
1989
1990 // Have the device owner specify a set of affiliation ids that do not intersect with those
1991 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001992 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001993 deviceAffiliationIds.add("cyan");
1994 deviceAffiliationIds.add("yellow");
1995 deviceAffiliationIds.add("magenta");
1996 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1997 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001998 MoreAsserts.assertContentsInAnyOrder(
1999 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002000 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2001 assertFalse(dpm.isAffiliatedUser());
2002
2003 // Have the profile owner specify a set of affiliation ids that intersect with those
2004 // specified by the device owner. Check that the test user becomes affiliated.
2005 userAffiliationIds.add("yellow");
2006 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002007 MoreAsserts.assertContentsInAnyOrder(
2008 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002009 assertTrue(dpm.isAffiliatedUser());
2010
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002011 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
2012 dpm.setAffiliationIds(admin2, Collections.emptyList());
2013 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002014 assertFalse(dpm.isAffiliatedUser());
2015
2016 // Check that the system user remains affiliated.
2017 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2018 assertTrue(dpm.isAffiliatedUser());
2019 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002020
2021 public void testGetUserProvisioningState_defaultResult() {
2022 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2023 }
2024
2025 public void testSetUserProvisioningState_permission() throws Exception {
2026 setupProfileOwner();
2027 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2028
2029 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2030 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2031 }
2032
2033 public void testSetUserProvisioningState_unprivileged() throws Exception {
2034 setupProfileOwner();
2035 try {
2036 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2037 DpmMockContext.CALLER_USER_HANDLE);
2038 fail("Expected SecurityException");
2039 } catch (SecurityException expected) {
2040 }
2041 }
2042
2043 public void testSetUserProvisioningState_noManagement() {
2044 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2045 try {
2046 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2047 DpmMockContext.CALLER_USER_HANDLE);
2048 fail("IllegalStateException expected");
2049 } catch (IllegalStateException e) {
2050 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
2051 e.getMessage());
2052 }
2053 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2054 }
2055
2056 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2057 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2058 setupDeviceOwner();
2059 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2060
2061 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2062 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2063 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2064 }
2065
2066 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2067 throws Exception {
2068 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2069 setupDeviceOwner();
2070 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2071
2072 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2073 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2074 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2075 }
2076
2077 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2078 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2079 setupDeviceOwner();
2080 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2081
2082 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2083 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2084 }
2085
2086 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2087 throws Exception {
2088 setupProfileOwner();
2089 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2090
2091 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2092 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2093 DevicePolicyManager.STATE_USER_UNMANAGED);
2094 }
2095
2096 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2097 throws Exception {
2098 setupProfileOwner();
2099 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2100
2101 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2102 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2103 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2104 }
2105
2106 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2107 setupProfileOwner();
2108 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2109
2110 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2111 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2112 }
2113
2114 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2115 setupProfileOwner();
2116 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2117
2118 try {
2119 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2120 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2121 DevicePolicyManager.STATE_USER_UNMANAGED);
2122 fail("Expected IllegalStateException");
2123 } catch (IllegalStateException e) {
2124 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2125 e.getMessage());
2126 }
2127 }
2128
2129 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2130 throws Exception {
2131 setupProfileOwner();
2132 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2133
2134 try {
2135 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2136 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2137 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2138 fail("Expected IllegalStateException");
2139 } catch (IllegalStateException e) {
2140 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2141 e.getMessage());
2142 }
2143 }
2144
2145 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2146 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2147 for (int state : states) {
2148 dpm.setUserProvisioningState(state, userId);
2149 assertEquals(state, dpm.getUserProvisioningState());
2150 }
2151 }
2152
2153 private void setupProfileOwner() throws Exception {
2154 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2155
2156 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2157 dpm.setActiveAdmin(admin1, false);
2158 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2159
2160 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2161 }
2162
2163 private void setupDeviceOwner() throws Exception {
2164 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2165
2166 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2167 dpm.setActiveAdmin(admin1, false);
2168 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2169
2170 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2171 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002172
2173 public void testSetMaximumTimeToLock() {
2174 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2175
2176 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2177 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2178
2179 reset(mMockContext.powerManagerInternal);
2180 reset(mMockContext.settings);
2181
2182 dpm.setMaximumTimeToLock(admin1, 0);
2183 verifyScreenTimeoutCall(null, false);
2184 reset(mMockContext.powerManagerInternal);
2185 reset(mMockContext.settings);
2186
2187 dpm.setMaximumTimeToLock(admin1, 1);
2188 verifyScreenTimeoutCall(1, true);
2189 reset(mMockContext.powerManagerInternal);
2190 reset(mMockContext.settings);
2191
2192 dpm.setMaximumTimeToLock(admin2, 10);
2193 verifyScreenTimeoutCall(null, false);
2194 reset(mMockContext.powerManagerInternal);
2195 reset(mMockContext.settings);
2196
2197 dpm.setMaximumTimeToLock(admin1, 5);
2198 verifyScreenTimeoutCall(5, true);
2199 reset(mMockContext.powerManagerInternal);
2200 reset(mMockContext.settings);
2201
2202 dpm.setMaximumTimeToLock(admin2, 4);
2203 verifyScreenTimeoutCall(4, true);
2204 reset(mMockContext.powerManagerInternal);
2205 reset(mMockContext.settings);
2206
2207 dpm.setMaximumTimeToLock(admin1, 0);
2208 reset(mMockContext.powerManagerInternal);
2209 reset(mMockContext.settings);
2210
2211 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2212 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2213 reset(mMockContext.powerManagerInternal);
2214 reset(mMockContext.settings);
2215
2216 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2217 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2218 reset(mMockContext.powerManagerInternal);
2219 reset(mMockContext.settings);
2220
2221 dpm.setMaximumTimeToLock(admin2, 10);
2222 verifyScreenTimeoutCall(10, true);
2223 reset(mMockContext.powerManagerInternal);
2224 reset(mMockContext.settings);
2225
2226 // There's no restriction; shold be set to MAX.
2227 dpm.setMaximumTimeToLock(admin2, 0);
2228 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2229 }
2230
Michal Karpinski943aabd2016-10-06 11:09:25 +01002231 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2232 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2233 setupDeviceOwner();
2234 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2235
Michal Karpinskid084ca52017-01-18 15:54:18 +00002236 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2237 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2238 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2239 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2240 - ONE_MINUTE;
2241
2242 // verify that the minimum timeout cannot be modified on user builds (system property is
2243 // not being read)
2244 mContext.buildMock.isDebuggable = false;
2245
2246 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2247 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2248 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2249
2250 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2251
2252 // restore to the debuggable build state
2253 mContext.buildMock.isDebuggable = true;
2254
2255 // Always return the default (second arg) when getting system property for long type
2256 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2257 new Answer<Long>() {
2258 @Override
2259 public Long answer(InvocationOnMock invocation) throws Throwable {
2260 return (Long) invocation.getArguments()[1];
2261 }
2262 }
2263 );
2264
2265 // reset to default (0 means the admin is not participating, so default should be returned)
2266 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002267
2268 // aggregation should be the default if unset by any admin
2269 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2270 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2271
2272 // admin not participating by default
2273 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2274
2275 //clamping from the top
2276 dpm.setRequiredStrongAuthTimeout(admin1,
2277 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2278 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2279 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2280 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2281 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2282
Michal Karpinskid084ca52017-01-18 15:54:18 +00002283 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002284 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2285 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2286 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2287 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2288
2289 // clamping from the bottom
2290 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2291 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2292 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2293
Michal Karpinskid084ca52017-01-18 15:54:18 +00002294 // values within range
2295 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2296 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2297 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2298
2299 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2300 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2301 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002302
2303 // reset to default
2304 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2305 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2306 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2307 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2308
2309 // negative value
2310 try {
2311 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2312 fail("Didn't throw IllegalArgumentException");
2313 } catch (IllegalArgumentException iae) {
2314 }
2315 }
2316
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002317 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2318 boolean shouldStayOnWhilePluggedInBeCleared) {
2319 if (expectedTimeout == null) {
2320 verify(mMockContext.powerManagerInternal, times(0))
2321 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2322 } else {
2323 verify(mMockContext.powerManagerInternal, times(1))
2324 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2325 }
2326 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2327 // UnfinishedVerificationException.
2328 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002329
Esteban Talavera01576862016-12-15 11:16:44 +00002330 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002331 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2332 .thenReturn(false);
2333 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2334 .thenReturn(false);
2335 initializeDpms();
2336 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2337 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2338 .thenReturn(true);
2339 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2340
2341 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002342 }
Victor Chang3e794af2016-03-04 13:48:17 +00002343
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002344 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2345 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002346 mContext.packageName = admin1.getPackageName();
2347 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002348 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2349 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2350 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2351 false);
2352 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2353 }
2354
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002355 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2356 setup_DeviceAdminFeatureOff();
2357 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2358 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2359 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2360 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2361 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2362 assertCheckProvisioningPreCondition(
2363 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2364 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2365 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2366 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2367 }
2368
Esteban Talavera01576862016-12-15 11:16:44 +00002369 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002370 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2371 .thenReturn(false);
2372 initializeDpms();
2373 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2374 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2375 .thenReturn(true);
2376 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2377
2378 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002379 }
Victor Chang3e794af2016-03-04 13:48:17 +00002380
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002381 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2382 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002383 mContext.packageName = admin1.getPackageName();
2384 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002385 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2386 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2387 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2388 false);
2389 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2390
2391 // Test again when split user is on
2392 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2393 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2394 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2395 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2396 true);
2397 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2398 }
2399
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002400 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2401 setup_ManagedProfileFeatureOff();
2402 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2403 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2404 DevicePolicyManager.CODE_OK);
2405 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2406 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2407 assertCheckProvisioningPreCondition(
2408 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2409 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2410 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2411 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2412
2413 // Test again when split user is on
2414 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2415 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2416 DevicePolicyManager.CODE_OK);
2417 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2418 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2419 assertCheckProvisioningPreCondition(
2420 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2421 DevicePolicyManager.CODE_OK);
2422 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2423 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2424 }
2425
Esteban Talavera01576862016-12-15 11:16:44 +00002426 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002427 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2428 .thenReturn(true);
2429 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2430 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2431 .thenReturn(true);
2432 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2433
2434 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002435 }
Victor Chang3e794af2016-03-04 13:48:17 +00002436
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002437 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2438 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002439 mContext.packageName = admin1.getPackageName();
2440 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002441 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2442 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2443 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2444 false /* because of non-split user */);
2445 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2446 false /* because of non-split user */);
2447 }
2448
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002449 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002450 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002451 setup_nonSplitUser_firstBoot_primaryUser();
2452 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2453 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2454 DevicePolicyManager.CODE_OK);
2455 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2456 DevicePolicyManager.CODE_OK);
2457 assertCheckProvisioningPreCondition(
2458 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2459 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2460 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2461 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2462 }
2463
Esteban Talavera01576862016-12-15 11:16:44 +00002464 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002465 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2466 .thenReturn(true);
2467 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2468 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2469 .thenReturn(true);
2470 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2471
2472 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002473 }
Victor Chang3e794af2016-03-04 13:48:17 +00002474
Nicolas Prevot45d29072017-01-18 16:11:19 +00002475 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2476 setDeviceOwner();
2477 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2478 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2479 }
2480
2481 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2482 setup_nonSplitUser_withDo_primaryUser();
2483 final int MANAGED_PROFILE_USER_ID = 18;
2484 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2485 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2486 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2487 false /* we can't remove a managed profile */)).thenReturn(false);
2488 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2489 true)).thenReturn(true);
2490 }
2491
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002492 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2493 throws Exception {
2494 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002495 mContext.packageName = admin1.getPackageName();
2496 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002497 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2498 false/* because of completed device setup */);
2499 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2500 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2501 false/* because of non-split user */);
2502 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2503 false/* because of non-split user */);
2504 }
2505
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002506 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2507 throws Exception {
2508 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2509 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2510 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2511 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2512 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2513 DevicePolicyManager.CODE_OK);
2514 assertCheckProvisioningPreCondition(
2515 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2516 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2517 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2518 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2519 }
2520
Nicolas Prevot45d29072017-01-18 16:11:19 +00002521 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2522 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002523 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002524 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2525
2526 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2527 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002528 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002529
2530 // COMP mode is allowed.
2531 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2532 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002533 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002534
Nicolas Prevot45d29072017-01-18 16:11:19 +00002535 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002536 assertCheckProvisioningPreCondition(
2537 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002538 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002539 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002540 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2541 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2542 }
Esteban Talavera01576862016-12-15 11:16:44 +00002543
Nicolas Prevot45d29072017-01-18 16:11:19 +00002544 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2545 setup_nonSplitUser_withDo_primaryUser();
2546 mContext.packageName = admin1.getPackageName();
2547 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2548 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2549 // other packages should be forbidden.
Esteban Talavera01576862016-12-15 11:16:44 +00002550 when(mContext.userManager.hasUserRestriction(
2551 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2552 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2553 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002554 when(mContext.userManager.getUserRestrictionSource(
2555 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2556 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2557 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2558 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2559 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002560 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002561 assertCheckProvisioningPreCondition(
2562 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002563 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002564 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002565 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2566 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2567 }
Esteban Talavera01576862016-12-15 11:16:44 +00002568
Nicolas Prevot45d29072017-01-18 16:11:19 +00002569 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2570 throws Exception {
2571 setup_nonSplitUser_withDo_primaryUser();
2572 mContext.packageName = admin1.getPackageName();
2573 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002574 // The DO should not be allowed to initiate provisioning if the restriction is set by
2575 // another entity.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002576 when(mContext.userManager.hasUserRestriction(
2577 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2578 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2579 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002580 when(mContext.userManager.getUserRestrictionSource(
2581 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2582 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2583 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2584 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2585 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002586 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2587
2588 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002589 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002590 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002591 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002592 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2593 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2594 }
2595
2596 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2597 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2598 mContext.packageName = admin1.getPackageName();
2599 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2600
2601 // We can delete the managed profile to create a new one, so provisioning is allowed.
2602 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2603 DevicePolicyManager.CODE_OK);
2604 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2605 assertCheckProvisioningPreCondition(
2606 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2607 DpmMockContext.ANOTHER_PACKAGE_NAME,
2608 DevicePolicyManager.CODE_OK);
2609 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2610 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2611 }
2612
2613 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2614 throws Exception {
2615 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2616 mContext.packageName = admin1.getPackageName();
2617 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2618 when(mContext.userManager.hasUserRestriction(
2619 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2620 eq(UserHandle.SYSTEM)))
2621 .thenReturn(true);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002622 when(mContext.userManager.getUserRestrictionSource(
2623 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2624 eq(UserHandle.SYSTEM)))
2625 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002626
2627 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002628 assertCheckProvisioningPreCondition(
2629 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2630 DpmMockContext.ANOTHER_PACKAGE_NAME,
2631 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2632 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2633 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002634
2635 // But the device owner can still do it because it has set the restriction itself.
2636 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2637 DevicePolicyManager.CODE_OK);
2638 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002639 }
2640
2641 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002642 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2643 .thenReturn(true);
2644 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2645 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2646 .thenReturn(false);
2647 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2648
2649 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002650 }
Victor Chang3e794af2016-03-04 13:48:17 +00002651
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002652 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2653 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002654 mContext.packageName = admin1.getPackageName();
2655 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002656 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2657 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2658 false /* because canAddMoreManagedProfiles returns false */);
2659 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2660 true);
2661 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2662 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002663 }
2664
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002665 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2666 throws Exception {
2667 setup_splitUser_firstBoot_systemUser();
2668 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2669 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2670 DevicePolicyManager.CODE_OK);
2671 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002672 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002673 assertCheckProvisioningPreCondition(
2674 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2675 DevicePolicyManager.CODE_OK);
2676 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2677 DevicePolicyManager.CODE_SYSTEM_USER);
2678 }
2679
Esteban Talavera01576862016-12-15 11:16:44 +00002680 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002681 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2682 .thenReturn(true);
2683 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2684 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2685 .thenReturn(false);
2686 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2687
2688 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002689 }
Victor Chang3e794af2016-03-04 13:48:17 +00002690
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002691 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2692 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002693 mContext.packageName = admin1.getPackageName();
2694 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002695 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2696 true/* it's undefined behavior. Can be changed into false in the future */);
2697 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2698 false /* because canAddMoreManagedProfiles returns false */);
2699 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2700 true/* it's undefined behavior. Can be changed into false in the future */);
2701 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2702 false/* because calling uid is system user */);
2703 }
2704
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002705 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2706 throws Exception {
2707 setup_splitUser_afterDeviceSetup_systemUser();
2708 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2709 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2710 DevicePolicyManager.CODE_OK);
2711 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002712 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002713 assertCheckProvisioningPreCondition(
2714 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2715 DevicePolicyManager.CODE_OK);
2716 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2717 DevicePolicyManager.CODE_SYSTEM_USER);
2718 }
2719
Esteban Talavera01576862016-12-15 11:16:44 +00002720 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002721 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2722 .thenReturn(true);
2723 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2724 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2725 true)).thenReturn(true);
2726 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2727
2728 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002729 }
Victor Chang3e794af2016-03-04 13:48:17 +00002730
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002731 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2732 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002733 mContext.packageName = admin1.getPackageName();
2734 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002735 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2736 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2737 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2738 true);
2739 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002740 }
2741
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002742 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002743 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002744 setup_splitUser_firstBoot_primaryUser();
2745 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2746 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2747 DevicePolicyManager.CODE_OK);
2748 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2749 DevicePolicyManager.CODE_OK);
2750 assertCheckProvisioningPreCondition(
2751 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2752 DevicePolicyManager.CODE_OK);
2753 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2754 DevicePolicyManager.CODE_OK);
2755 }
2756
Esteban Talavera01576862016-12-15 11:16:44 +00002757 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002758 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2759 .thenReturn(true);
2760 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2761 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2762 true)).thenReturn(true);
2763 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2764
2765 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002766 }
Victor Chang3e794af2016-03-04 13:48:17 +00002767
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002768 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2769 throws Exception {
2770 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002771 mContext.packageName = admin1.getPackageName();
2772 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002773 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2774 true/* it's undefined behavior. Can be changed into false in the future */);
2775 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2776 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2777 true/* it's undefined behavior. Can be changed into false in the future */);
2778 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2779 false/* because user setup completed */);
2780 }
2781
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002782 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002783 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002784 setup_splitUser_afterDeviceSetup_primaryUser();
2785 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2786 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2787 DevicePolicyManager.CODE_OK);
2788 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2789 DevicePolicyManager.CODE_OK);
2790 assertCheckProvisioningPreCondition(
2791 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2792 DevicePolicyManager.CODE_OK);
2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2794 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2795 }
2796
Esteban Talavera01576862016-12-15 11:16:44 +00002797 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002798 setDeviceOwner();
2799
2800 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2801 .thenReturn(true);
2802 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2803 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2804 .thenReturn(false);
2805 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2806
2807 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002808 }
Victor Chang3e794af2016-03-04 13:48:17 +00002809
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002810 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2811 throws Exception {
2812 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002813 mContext.packageName = admin1.getPackageName();
2814 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002815 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2816 false /* can't provision managed profile on system user */);
2817 }
2818
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002819 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002820 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002821 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2822 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2823 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2824 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2825 }
2826
2827 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002828 setDeviceOwner();
2829
2830 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2831 .thenReturn(true);
2832 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2833 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2834 true)).thenReturn(true);
2835 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2836
2837 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002838 }
Victor Chang3e794af2016-03-04 13:48:17 +00002839
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002840 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2841 throws Exception {
2842 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002843 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2844 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002845 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2846 }
2847
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002848 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002849 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002850 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2851 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002852
2853 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002854 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2855 DevicePolicyManager.CODE_OK);
2856 }
2857
2858 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002859 setDeviceOwner();
2860
2861 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2862 .thenReturn(true);
2863 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002864 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002865 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2866 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002867 .thenReturn(true);
2868 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002869 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002870 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2871 true)).thenReturn(true);
2872 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2873
2874 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002875 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002876
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002877 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2878 throws Exception {
2879 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002880 mContext.packageName = admin1.getPackageName();
2881 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002882 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2883 }
2884
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002885 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2886 throws Exception {
2887 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2888 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2889 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2890 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2891 }
2892
2893 public void testCheckProvisioningPreCondition_permission() {
2894 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2895 try {
Esteban Talavera01576862016-12-15 11:16:44 +00002896 dpm.checkProvisioningPreCondition(
2897 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002898 fail("Didn't throw SecurityException");
2899 } catch (SecurityException expected) {
2900 }
2901 }
2902
Victor Chang3577ed22016-08-25 18:49:26 +01002903 public void testForceUpdateUserSetupComplete_permission() {
2904 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2905 try {
2906 dpm.forceUpdateUserSetupComplete();
2907 fail("Didn't throw SecurityException");
2908 } catch (SecurityException expected) {
2909 }
2910 }
2911
2912 public void testForceUpdateUserSetupComplete_systemUser() {
2913 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2914 // GIVEN calling from user 20
2915 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2916 try {
2917 dpm.forceUpdateUserSetupComplete();
2918 fail("Didn't throw SecurityException");
2919 } catch (SecurityException expected) {
2920 }
2921 }
2922
2923 public void testForceUpdateUserSetupComplete_userbuild() {
2924 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2925 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2926
2927 final int userId = UserHandle.USER_SYSTEM;
2928 // GIVEN userComplete is false in SettingsProvider
2929 setUserSetupCompleteForUser(false, userId);
2930
2931 // GIVEN userComplete is true in DPM
2932 DevicePolicyManagerService.DevicePolicyData userData =
2933 new DevicePolicyManagerService.DevicePolicyData(userId);
2934 userData.mUserSetupComplete = true;
2935 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2936
2937 // GIVEN it's user build
2938 mContext.buildMock.isDebuggable = false;
2939
2940 assertTrue(dpms.hasUserSetupCompleted());
2941
2942 dpm.forceUpdateUserSetupComplete();
2943
2944 // THEN the state in dpms is not changed
2945 assertTrue(dpms.hasUserSetupCompleted());
2946 }
2947
2948 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2949 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2950 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2951
2952 final int userId = UserHandle.USER_SYSTEM;
2953 // GIVEN userComplete is false in SettingsProvider
2954 setUserSetupCompleteForUser(false, userId);
2955
2956 // GIVEN userComplete is true in DPM
2957 DevicePolicyManagerService.DevicePolicyData userData =
2958 new DevicePolicyManagerService.DevicePolicyData(userId);
2959 userData.mUserSetupComplete = true;
2960 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2961
2962 // GIVEN it's userdebug build
2963 mContext.buildMock.isDebuggable = true;
2964
2965 assertTrue(dpms.hasUserSetupCompleted());
2966
2967 dpm.forceUpdateUserSetupComplete();
2968
2969 // THEN the state in dpms is not changed
2970 assertFalse(dpms.hasUserSetupCompleted());
2971 }
2972
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002973 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002974 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002975 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2976 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2977 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2978 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002979 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002980 }
2981
2982 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2983 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2984 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002985
2986 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2987 // feature is disabled because there are non-affiliated secondary users.
2988 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002989 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2990 .thenReturn(true);
2991
2992 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002993 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002994
2995 // Enabling logging should not change the timestamp.
2996 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00002997 verify(mContext.settings)
2998 .securityLogSetLoggingEnabledProperty(true);
2999 when(mContext.settings.securityLogGetLoggingEnabledProperty())
3000 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003001 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003002
3003 // Retrieving the logs should update the timestamp.
3004 final long beforeRetrieval = System.currentTimeMillis();
3005 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003006 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003007 final long afterRetrieval = System.currentTimeMillis();
3008 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3009 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3010
3011 // Retrieving the pre-boot logs should update the timestamp.
3012 Thread.sleep(2);
3013 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003014 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003015 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3016
3017 // Checking the timestamp again should not change it.
3018 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003019 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003020
3021 // Retrieving the logs again should update the timestamp.
3022 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003023 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003024 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3025
3026 // Disabling logging should not change the timestamp.
3027 Thread.sleep(2);
3028 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003029 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003030
3031 // Restarting the DPMS should not lose the timestamp.
3032 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003033 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003034
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003035 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3036 mContext.binder.callingUid = 1234567;
3037 mContext.callerPermissions.add(permission.MANAGE_USERS);
3038 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3039 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3040
3041 // System can retrieve the timestamp.
3042 mContext.binder.clearCallingIdentity();
3043 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3044
3045 // Removing the device owner should clear the timestamp.
3046 clearDeviceOwner();
3047 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003048 }
3049
3050 public void testGetLastBugReportRequestTime() throws Exception {
3051 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3052 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003053
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003054 mContext.packageName = admin1.getPackageName();
3055 mContext.applicationInfo = new ApplicationInfo();
3056 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3057 .thenReturn(Color.WHITE);
3058 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3059 anyObject())).thenReturn(Color.WHITE);
3060
Esteban Talaverad36dd152016-12-15 08:51:45 +00003061 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3062 // feature is disabled because there are non-affiliated secondary users.
3063 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3064
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003065 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003066 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003067
3068 // Requesting a bug report should update the timestamp.
3069 final long beforeRequest = System.currentTimeMillis();
3070 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003071 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003072 final long afterRequest = System.currentTimeMillis();
3073 assertTrue(bugReportRequestTime >= beforeRequest);
3074 assertTrue(bugReportRequestTime <= afterRequest);
3075
3076 // Checking the timestamp again should not change it.
3077 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003078 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003079
3080 // Restarting the DPMS should not lose the timestamp.
3081 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003082 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003083
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003084 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3085 mContext.binder.callingUid = 1234567;
3086 mContext.callerPermissions.add(permission.MANAGE_USERS);
3087 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3088 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3089
3090 // System can retrieve the timestamp.
3091 mContext.binder.clearCallingIdentity();
3092 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3093
3094 // Removing the device owner should clear the timestamp.
3095 clearDeviceOwner();
3096 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003097 }
3098
3099 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3100 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3101 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003102 mContext.packageName = admin1.getPackageName();
3103 mContext.applicationInfo = new ApplicationInfo();
3104 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3105 .thenReturn(Color.WHITE);
3106 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3107 anyObject())).thenReturn(Color.WHITE);
3108
3109 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3110 // feature is disabled because there are non-affiliated secondary users.
3111 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003112 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3113 .thenReturn(true);
3114
3115 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003116 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003117
3118 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3119 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003120 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003121
3122 // Enabling logging should not change the timestamp.
3123 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003124 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003125
3126 // Retrieving the logs should update the timestamp.
3127 final long beforeRetrieval = System.currentTimeMillis();
3128 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003129 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003130 final long afterRetrieval = System.currentTimeMillis();
3131 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3132 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3133
3134 // Checking the timestamp again should not change it.
3135 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003136 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003137
3138 // Retrieving the logs again should update the timestamp.
3139 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003140 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003141 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3142
3143 // Disabling logging should not change the timestamp.
3144 Thread.sleep(2);
3145 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003146 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003147
3148 // Restarting the DPMS should not lose the timestamp.
3149 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003150 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3151
3152 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3153 mContext.binder.callingUid = 1234567;
3154 mContext.callerPermissions.add(permission.MANAGE_USERS);
3155 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3156 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3157
3158 // System can retrieve the timestamp.
3159 mContext.binder.clearCallingIdentity();
3160 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3161
3162 // Removing the device owner should clear the timestamp.
3163 clearDeviceOwner();
3164 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003165 }
3166
Tony Mak2f26b792016-11-28 17:54:51 +00003167 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3168 // Setup device owner.
3169 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3170 setupDeviceOwner();
3171
3172 // Only device owner is setup, the result list should be empty.
3173 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3174 MoreAsserts.assertEmpty(targetUsers);
3175
3176 // Setup a managed profile managed by the same admin.
3177 final int MANAGED_PROFILE_USER_ID = 15;
3178 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3179 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3180
3181 // Add a secondary user, it should never talk with.
3182 final int ANOTHER_USER_ID = 36;
3183 mContext.addUser(ANOTHER_USER_ID, 0);
3184
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003185 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3186 // other.
3187 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3188 MoreAsserts.assertEmpty(targetUsers);
3189
3190 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3191 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3192 MoreAsserts.assertEmpty(targetUsers);
3193
3194 // Setting affiliation ids
3195 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3196 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3197 dpm.setAffiliationIds(admin1, userAffiliationIds);
3198
3199 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3200 dpm.setAffiliationIds(admin1, userAffiliationIds);
3201
Tony Mak2f26b792016-11-28 17:54:51 +00003202 // Calling from device owner admin, the result list should just contain the managed
3203 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003204 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003205 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3206 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3207
3208 // Calling from managed profile admin, the result list should just contain the system
3209 // user id.
3210 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3211 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3212 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003213
3214 // Changing affiliation ids in one
3215 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3216
3217 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3218 // to each other.
3219 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3220 MoreAsserts.assertEmpty(targetUsers);
3221
3222 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3223 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3224 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003225 }
3226
3227 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3228 // Setup a device owner.
3229 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3230 setupDeviceOwner();
3231
3232 // Set up a managed profile managed by different package.
3233 final int MANAGED_PROFILE_USER_ID = 15;
3234 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3235 final ComponentName adminDifferentPackage =
3236 new ComponentName("another.package", "whatever.class");
3237 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3238
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003239 // Setting affiliation ids
3240 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3241 dpm.setAffiliationIds(admin1, userAffiliationIds);
3242
3243 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3244 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3245
Tony Mak2f26b792016-11-28 17:54:51 +00003246 // Calling from device owner admin, we should get zero bind device admin target users as
3247 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003248 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003249 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3250 MoreAsserts.assertEmpty(targetUsers);
3251
3252 // Calling from managed profile admin, we should still get zero target users for the same
3253 // reason.
3254 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3255 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3256 MoreAsserts.assertEmpty(targetUsers);
3257 }
3258
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003259 public void testIsDeviceManaged() throws Exception {
3260 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3261 setupDeviceOwner();
3262
3263 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3264 // find out that the device has a device owner.
3265 assertTrue(dpm.isDeviceManaged());
3266 mContext.binder.callingUid = 1234567;
3267 mContext.callerPermissions.add(permission.MANAGE_USERS);
3268 assertTrue(dpm.isDeviceManaged());
3269 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3270 mContext.binder.clearCallingIdentity();
3271 assertTrue(dpm.isDeviceManaged());
3272
3273 clearDeviceOwner();
3274
3275 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3276 // not have a device owner.
3277 mContext.binder.callingUid = 1234567;
3278 mContext.callerPermissions.add(permission.MANAGE_USERS);
3279 assertFalse(dpm.isDeviceManaged());
3280 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3281 mContext.binder.clearCallingIdentity();
3282 assertFalse(dpm.isDeviceManaged());
3283 }
3284
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003285 public void testDeviceOwnerOrganizationName() throws Exception {
3286 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3287 setupDeviceOwner();
3288
3289 dpm.setOrganizationName(admin1, "organization");
3290
3291 // Device owner can retrieve organization managing the device.
3292 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3293
3294 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3295 mContext.binder.callingUid = 1234567;
3296 mContext.callerPermissions.add(permission.MANAGE_USERS);
3297 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3298 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3299
3300 // System can retrieve organization managing the device.
3301 mContext.binder.clearCallingIdentity();
3302 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3303
3304 // Removing the device owner clears the organization managing the device.
3305 clearDeviceOwner();
3306 assertNull(dpm.getDeviceOwnerOrganizationName());
3307 }
3308
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003309 public void testWipeDataManagedProfile() throws Exception {
3310 final int MANAGED_PROFILE_USER_ID = 15;
3311 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3312 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3313 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3314
3315 // Even if the caller is the managed profile, the current user is the user 0
3316 when(mContext.iactivityManager.getCurrentUser())
3317 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3318
3319 dpm.wipeData(0);
3320 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3321 MANAGED_PROFILE_USER_ID);
3322 }
3323
3324 public void testWipeDataManagedProfileDisallowed() throws Exception {
3325 final int MANAGED_PROFILE_USER_ID = 15;
3326 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3327 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3328
3329 // Even if the caller is the managed profile, the current user is the user 0
3330 when(mContext.iactivityManager.getCurrentUser())
3331 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3332
3333 when(mContext.userManager.getUserRestrictionSource(
3334 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3335 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3336 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3337 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3338 try {
3339 // The PO is not allowed to remove the profile if the user restriction was set on the
3340 // profile by the system
3341 dpm.wipeData(0);
3342 fail("SecurityException not thrown");
3343 } catch (SecurityException expected) {
3344 }
3345 }
3346
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003347 public void testGetPermissionGrantState() throws Exception {
3348 final String permission = "some.permission";
3349 final String app1 = "com.example.app1";
3350 final String app2 = "com.example.app2";
3351
3352 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3353 .thenReturn(PackageManager.PERMISSION_GRANTED);
3354 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3355 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3356 when(mContext.packageManager.getPermissionFlags(permission, app1,
3357 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3358 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3359 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3360 .thenReturn(PackageManager.PERMISSION_DENIED);
3361 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3362 UserHandle.SYSTEM);
3363 when(mContext.packageManager.getPermissionFlags(permission, app2,
3364 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3365
3366 // System can retrieve permission grant state.
3367 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3368 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3369 dpm.getPermissionGrantState(null, app1, permission));
3370 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3371 dpm.getPermissionGrantState(null, app2, permission));
3372
3373 // A regular app cannot retrieve permission grant state.
3374 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
3375 try {
3376 dpm.getPermissionGrantState(null, app1, permission);
3377 fail("Didn't throw IllegalStateException");
3378 } catch (IllegalStateException expected) {
3379 }
3380
3381 // Profile owner can retrieve permission grant state.
3382 setAsProfileOwner(admin1);
3383 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3384 dpm.getPermissionGrantState(admin1, app1, permission));
3385 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3386 dpm.getPermissionGrantState(admin1, app2, permission));
3387 }
3388
Victor Chang3e794af2016-03-04 13:48:17 +00003389 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
3390 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
3391 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
3392 dpms.notifyChangeToContentObserver(
3393 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
3394 }
3395
3396 private void assertProvisioningAllowed(String action, boolean expected) {
3397 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
3398 dpm.isProvisioningAllowed(action));
3399 }
Tony Mak2f26b792016-11-28 17:54:51 +00003400
Nicolas Prevot45d29072017-01-18 16:11:19 +00003401 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
3402 int uid) {
3403 String previousPackageName = mContext.packageName;
3404 int previousUid = mMockContext.binder.callingUid;
3405
3406 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
3407 mContext.packageName = packageName;
3408 mMockContext.binder.callingUid = uid;
3409 assertProvisioningAllowed(action, expected);
3410
3411 // Set the previous package name / calling uid to go back to the initial state.
3412 mContext.packageName = previousPackageName;
3413 mMockContext.binder.callingUid = previousUid;
3414 }
3415
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003416 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00003417 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
3418 }
3419
3420 private void assertCheckProvisioningPreCondition(
3421 String action, String packageName, int provisioningCondition) {
3422 assertEquals("checkProvisioningPreCondition("
3423 + action + ", " + packageName + ") returning unexpected result",
3424 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003425 }
3426
Tony Mak2f26b792016-11-28 17:54:51 +00003427 /**
3428 * Setup a managed profile with the specified admin and its uid.
3429 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
3430 * @param adminUid uid of the admin package.
3431 * @param copyFromAdmin package information for {@code admin} will be built based on this
3432 * component's information.
3433 */
3434 private void addManagedProfile(
3435 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
3436 final int userId = UserHandle.getUserId(adminUid);
3437 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
3438 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3439 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
3440 dpm.setActiveAdmin(admin, false, userId);
3441 assertTrue(dpm.setProfileOwner(admin, null, userId));
3442 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3443 }
Victor Chang3e794af2016-03-04 13:48:17 +00003444}