blob: 5d4c3cfa3197e00771024bd63608670bf582aced [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;
Esteban Talaverab88f42b2017-01-24 16:47:16 +000088import static org.mockito.Mockito.verifyZeroInteractions;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070089import static org.mockito.Mockito.when;
90
91/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070092 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +000093 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070094 m FrameworksServicesTests &&
95 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000096 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070097 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080098 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070099
100 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000101 *
102 * , or:
103 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700104 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000105@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000107 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
108 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
109 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
110
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111 private DpmMockContext mContext;
112 public DevicePolicyManager dpm;
113 public DevicePolicyManagerServiceTestable dpms;
114
115 @Override
116 protected void setUp() throws Exception {
117 super.setUp();
118
119 mContext = getContext();
120
121 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
122 .thenReturn(true);
123
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800124 // By default, pretend all users are running and unlocked.
125 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
126
Makoto Onukia52562c2015-10-01 16:12:31 -0700127 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700128
Makoto Onukid932f762015-09-29 16:53:38 -0700129 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
130 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
131 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800132 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700133
Makoto Onukib643fb02015-09-22 15:03:44 -0700134 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700135 }
136
Makoto Onukia52562c2015-10-01 16:12:31 -0700137 private void initializeDpms() {
138 // Need clearCallingIdentity() to pass permission checks.
139 final long ident = mContext.binder.clearCallingIdentity();
140 try {
141 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
142
143 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
144
145 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
146 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
147
148 dpm = new DevicePolicyManagerTestable(mContext, dpms);
149 } finally {
150 mContext.binder.restoreCallingIdentity(ident);
151 }
152 }
153
Makoto Onukib643fb02015-09-22 15:03:44 -0700154 private void setUpUserManager() {
155 // Emulate UserManager.set/getApplicationRestriction().
156 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
157
158 // UM.setApplicationRestrictions() will save to appRestrictions.
159 doAnswer(new Answer<Void>() {
160 @Override
161 public Void answer(InvocationOnMock invocation) throws Throwable {
162 String pkg = (String) invocation.getArguments()[0];
163 Bundle bundle = (Bundle) invocation.getArguments()[1];
164 UserHandle user = (UserHandle) invocation.getArguments()[2];
165
166 appRestrictions.put(Pair.create(pkg, user), bundle);
167
168 return null;
169 }
170 }).when(mContext.userManager).setApplicationRestrictions(
171 anyString(), any(Bundle.class), any(UserHandle.class));
172
173 // UM.getApplicationRestrictions() will read from appRestrictions.
174 doAnswer(new Answer<Bundle>() {
175 @Override
176 public Bundle answer(InvocationOnMock invocation) throws Throwable {
177 String pkg = (String) invocation.getArguments()[0];
178 UserHandle user = (UserHandle) invocation.getArguments()[1];
179
180 return appRestrictions.get(Pair.create(pkg, user));
181 }
182 }).when(mContext.userManager).getApplicationRestrictions(
183 anyString(), any(UserHandle.class));
184
Makoto Onukid932f762015-09-29 16:53:38 -0700185 // Add the first secondary user.
186 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700187 }
188
189 private void setAsProfileOwner(ComponentName admin) {
190 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
191 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
192
Makoto Onukia4f11972015-10-01 13:19:58 -0700193 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700194 dpm.setActiveAdmin(admin, /* replace =*/ false);
195
196 // Fire!
197 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
198
199 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700200 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700201 }
202
203 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700204 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
205 .thenReturn(false);
206
207 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
208 new DevicePolicyManagerServiceTestable(mContext, dataDir);
209
210 // If the device has no DPMS feature, it shouldn't register the local service.
211 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
212 }
213
214 /**
215 * Caller doesn't have proper permissions.
216 */
217 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700218 // 1. Failure cases.
219
220 // Caller doesn't have MANAGE_DEVICE_ADMINS.
221 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700222 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700223 fail("Didn't throw SecurityException");
224 } catch (SecurityException expected) {
225 }
226
227 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
228 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
229 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700230 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700231 fail("Didn't throw SecurityException");
232 } catch (SecurityException expected) {
233 }
234 }
235
Makoto Onukif76b06a2015-09-22 15:03:44 -0700236 /**
237 * Test for:
238 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800239 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700240 * {@link DevicePolicyManager#isAdminActive}
241 * {@link DevicePolicyManager#isAdminActiveAsUser}
242 * {@link DevicePolicyManager#getActiveAdmins}
243 * {@link DevicePolicyManager#getActiveAdminsAsUser}
244 */
245 public void testSetActiveAdmin() throws Exception {
246 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700247 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
248
Makoto Onukif76b06a2015-09-22 15:03:44 -0700249 // 2. Call the API.
250 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700251
252 // 3. Verify internal calls.
253
254 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700255 verify(mContext.spiedContext).sendBroadcastAsUser(
256 MockUtils.checkIntentAction(
257 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
258 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
259 verify(mContext.spiedContext).sendBroadcastAsUser(
260 MockUtils.checkIntentAction(
261 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700262 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
263
Makoto Onukif76b06a2015-09-22 15:03:44 -0700264 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
265 eq(admin1.getPackageName()),
266 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
267 eq(PackageManager.DONT_KILL_APP),
268 eq(DpmMockContext.CALLER_USER_HANDLE),
269 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700270
271 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700272
273 // Make sure it's active admin1.
274 assertTrue(dpm.isAdminActive(admin1));
275 assertFalse(dpm.isAdminActive(admin2));
276 assertFalse(dpm.isAdminActive(admin3));
277
278 // But not admin1 for a different user.
279
280 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
281 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
282 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
283
284 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
285 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
286
287 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
288
289 // Next, add one more admin.
290 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700291 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
292 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700293
294 dpm.setActiveAdmin(admin2, /* replace =*/ false);
295
296 // Now we have two admins.
297 assertTrue(dpm.isAdminActive(admin1));
298 assertTrue(dpm.isAdminActive(admin2));
299 assertFalse(dpm.isAdminActive(admin3));
300
301 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
302 // again. (times(1) because it was previously called for admin1)
303 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
304 eq(admin1.getPackageName()),
305 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
306 eq(PackageManager.DONT_KILL_APP),
307 eq(DpmMockContext.CALLER_USER_HANDLE),
308 anyString());
309
310 // 4. Add the same admin1 again without replace, which should throw.
311 try {
312 dpm.setActiveAdmin(admin1, /* replace =*/ false);
313 fail("Didn't throw");
314 } catch (IllegalArgumentException expected) {
315 }
316
317 // 5. Add the same admin1 again with replace, which should succeed.
318 dpm.setActiveAdmin(admin1, /* replace =*/ true);
319
320 // TODO make sure it's replaced.
321
322 // 6. Test getActiveAdmins()
323 List<ComponentName> admins = dpm.getActiveAdmins();
324 assertEquals(2, admins.size());
325 assertEquals(admin1, admins.get(0));
326 assertEquals(admin2, admins.get(1));
327
328 // Another user has no admins.
329 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
330
331 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
332 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
333
334 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
335 }
336
Makoto Onukid932f762015-09-29 16:53:38 -0700337 public void testSetActiveAdmin_multiUsers() throws Exception {
338
339 final int ANOTHER_USER_ID = 100;
340 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
341
342 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
343
344 // Set up pacakge manager for the other user.
345 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700346
347 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
348
349 dpm.setActiveAdmin(admin1, /* replace =*/ false);
350
351 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
352 dpm.setActiveAdmin(admin2, /* replace =*/ false);
353
354
355 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
356 assertTrue(dpm.isAdminActive(admin1));
357 assertFalse(dpm.isAdminActive(admin2));
358
359 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
360 assertFalse(dpm.isAdminActive(admin1));
361 assertTrue(dpm.isAdminActive(admin2));
362 }
363
Makoto Onukif76b06a2015-09-22 15:03:44 -0700364 /**
365 * Test for:
366 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800367 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700368 */
369 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
370 // 1. Make sure the caller has proper permissions.
371 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
372
373 dpm.setActiveAdmin(admin1, /* replace =*/ false);
374 assertTrue(dpm.isAdminActive(admin1));
375
376 // Add the same admin1 again without replace, which should throw.
377 try {
378 dpm.setActiveAdmin(admin1, /* replace =*/ false);
379 fail("Didn't throw");
380 } catch (IllegalArgumentException expected) {
381 }
382 }
383
384 /**
385 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800386 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
387 * BIND_DEVICE_ADMIN.
388 */
389 public void testSetActiveAdmin_permissionCheck() throws Exception {
390 // 1. Make sure the caller has proper permissions.
391 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
392
393 try {
394 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
395 fail();
396 } catch (IllegalArgumentException expected) {
397 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
398 }
399 assertFalse(dpm.isAdminActive(adminNoPerm));
400
401 // Change the target API level to MNC. Now it can be set as DA.
402 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
403 VERSION_CODES.M);
404 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
405 assertTrue(dpm.isAdminActive(adminNoPerm));
406
407 // TODO Test the "load from the file" case where DA will still be loaded even without
408 // BIND_DEVICE_ADMIN and target API is N.
409 }
410
411 /**
412 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700413 * {@link DevicePolicyManager#removeActiveAdmin}
414 */
415 public void testRemoveActiveAdmin_SecurityException() {
416 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
417
418 // Add admin.
419
420 dpm.setActiveAdmin(admin1, /* replace =*/ false);
421
422 assertTrue(dpm.isAdminActive(admin1));
423
424 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
425
426 // Directly call the DPMS method with a different userid, which should fail.
427 try {
428 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
429 fail("Didn't throw SecurityException");
430 } catch (SecurityException expected) {
431 }
432
433 // Try to remove active admin with a different caller userid should fail too, without
434 // having MANAGE_DEVICE_ADMINS.
435 mContext.callerPermissions.clear();
436
Makoto Onukid932f762015-09-29 16:53:38 -0700437 // Change the caller, and call into DPMS directly with a different user-id.
438
Makoto Onukif76b06a2015-09-22 15:03:44 -0700439 mContext.binder.callingUid = 1234567;
440 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700441 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700442 fail("Didn't throw SecurityException");
443 } catch (SecurityException expected) {
444 }
445 }
446
447 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800448 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
449 * (because we can't send the remove broadcast).
450 */
451 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
452 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
453
454 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
455
456 // Add admin.
457
458 dpm.setActiveAdmin(admin1, /* replace =*/ false);
459
460 assertTrue(dpm.isAdminActive(admin1));
461
462 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
463
464 // 1. User not unlocked.
465 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
466 .thenReturn(false);
467 try {
468 dpm.removeActiveAdmin(admin1);
469 fail("Didn't throw IllegalStateException");
470 } catch (IllegalStateException expected) {
471 MoreAsserts.assertContainsRegex(
472 "User must be running and unlocked", expected.getMessage());
473 }
474
475 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
476
477 // 2. User unlocked.
478 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
479 .thenReturn(true);
480
481 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700482 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800483 }
484
485 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700486 * Test for:
487 * {@link DevicePolicyManager#removeActiveAdmin}
488 */
Makoto Onukid932f762015-09-29 16:53:38 -0700489 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700490 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
491
492 // Add admin1.
493
494 dpm.setActiveAdmin(admin1, /* replace =*/ false);
495
496 assertTrue(dpm.isAdminActive(admin1));
497 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
498
499 // Different user, but should work, because caller has proper permissions.
500 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700501
502 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700503 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700504
505 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700506 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700507
508 // TODO DO Still can't be removed in this case.
509 }
510
511 /**
512 * Test for:
513 * {@link DevicePolicyManager#removeActiveAdmin}
514 */
515 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
516 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
517 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
518
519 // Add admin1.
520
521 dpm.setActiveAdmin(admin1, /* replace =*/ false);
522
523 assertTrue(dpm.isAdminActive(admin1));
524 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
525
526 // Broadcast from saveSettingsLocked().
527 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
528 MockUtils.checkIntentAction(
529 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
530 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
531
532 // Remove. No permissions, but same user, so it'll work.
533 mContext.callerPermissions.clear();
534 dpm.removeActiveAdmin(admin1);
535
Makoto Onukif76b06a2015-09-22 15:03:44 -0700536 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
537 MockUtils.checkIntentAction(
538 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
539 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
540 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700541 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700542 eq(dpms.mHandler),
543 eq(Activity.RESULT_OK),
544 isNull(String.class),
545 isNull(Bundle.class));
546
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700547 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700548
549 // Again broadcast from saveSettingsLocked().
550 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
551 MockUtils.checkIntentAction(
552 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
553 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
554
555 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700556 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700557
558 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000559 * Test for: @{link DevicePolicyManager#setActivePasswordState}
560 *
561 * Validates that when the password for a user changes, the notification broadcast intent
562 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
563 * addition to ones in the original user.
564 */
565 public void testSetActivePasswordState_sendToProfiles() throws Exception {
566 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
567
568 final int MANAGED_PROFILE_USER_ID = 78;
569 final int MANAGED_PROFILE_ADMIN_UID =
570 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
571
572 // Setup device owner.
573 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
574 mContext.packageName = admin1.getPackageName();
575 setupDeviceOwner();
576
577 // Add a managed profile belonging to the system user.
578 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
579
580 // Change the parent user's password.
581 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
582
583 // Both the device owner and the managed profile owner should receive this broadcast.
584 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
585 intent.setComponent(admin1);
586 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
587
588 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
589 MockUtils.checkIntent(intent),
590 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
591 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
592 MockUtils.checkIntent(intent),
593 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
594 }
595
596 /**
597 * Test for: @{link DevicePolicyManager#setActivePasswordState}
598 *
599 * Validates that when the password for a managed profile changes, the notification broadcast
600 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
601 * its parent.
602 */
603 public void testSetActivePasswordState_notSentToParent() throws Exception {
604 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
605
606 final int MANAGED_PROFILE_USER_ID = 78;
607 final int MANAGED_PROFILE_ADMIN_UID =
608 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
609
610 // Setup device owner.
611 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
612 mContext.packageName = admin1.getPackageName();
613 doReturn(true).when(mContext.lockPatternUtils)
614 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
615 setupDeviceOwner();
616
617 // Add a managed profile belonging to the system user.
618 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
619
620 // Change the profile's password.
621 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
622
623 // Both the device owner and the managed profile owner should receive this broadcast.
624 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
625 intent.setComponent(admin1);
626 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
627
628 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
629 MockUtils.checkIntent(intent),
630 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
631 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
632 MockUtils.checkIntent(intent),
633 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
634 }
635 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000636 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700637 */
638 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000639 setDeviceOwner();
640
641 // Try to set a profile owner on the same user, which should fail.
642 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
643 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
644 try {
645 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
646 fail("IllegalStateException not thrown");
647 } catch (IllegalStateException expected) {
648 assertTrue("Message was: " + expected.getMessage(),
649 expected.getMessage().contains("already has a device owner"));
650 }
651
652 // DO admin can't be deactivated.
653 dpm.removeActiveAdmin(admin1);
654 assertTrue(dpm.isAdminActive(admin1));
655
656 // TODO Test getDeviceOwnerName() too. To do so, we need to change
657 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
658 }
659
660 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700661 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800662 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700663 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
664 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
665
Makoto Onukid932f762015-09-29 16:53:38 -0700666 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700667 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
668
Makoto Onukid932f762015-09-29 16:53:38 -0700669 // Make sure admin1 is installed on system user.
670 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700671
Makoto Onukic8a5a552015-11-19 14:29:12 -0800672 // Check various get APIs.
673 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
674
Makoto Onukib643fb02015-09-22 15:03:44 -0700675 // DO needs to be an DA.
676 dpm.setActiveAdmin(admin1, /* replace =*/ false);
677
678 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700679 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700680
Makoto Onukic8a5a552015-11-19 14:29:12 -0800681 // getDeviceOwnerComponent should return the admin1 component.
682 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
683 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
684
685 // Check various get APIs.
686 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
687
688 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
689 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
690 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
691 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
692
693 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
694
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000695 // Verify internal calls.
696 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
697 eq(admin1.getPackageName()));
698
Makoto Onukib643fb02015-09-22 15:03:44 -0700699 // TODO We should check if the caller has called clearCallerIdentity().
700 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
701 eq(UserHandle.USER_SYSTEM), eq(false));
702
703 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
704 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
705 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
706
Makoto Onukic8a5a552015-11-19 14:29:12 -0800707 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700708 }
709
Makoto Onukic8a5a552015-11-19 14:29:12 -0800710 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
711 final int origCallingUser = mContext.binder.callingUid;
712 final List origPermissions = new ArrayList(mContext.callerPermissions);
713 mContext.callerPermissions.clear();
714
715 mContext.callerPermissions.add(permission.MANAGE_USERS);
716
717 mContext.binder.callingUid = Process.SYSTEM_UID;
718
719 // TODO Test getDeviceOwnerName() too. To do so, we need to change
720 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
721 if (hasDeviceOwner) {
722 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
723 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
724 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
725
726 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
727 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
728 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
729 } else {
730 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
731 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
732 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
733
734 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
735 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
736 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
737 }
738
739 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
740 if (hasDeviceOwner) {
741 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
742 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
743 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
744
745 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
746 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
747 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
748 } else {
749 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
750 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
751 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
752
753 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
754 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
755 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
756 }
757
758 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
759 // Still with MANAGE_USERS.
760 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
761 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
762 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
763
764 if (hasDeviceOwner) {
765 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
766 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
767 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
768 } else {
769 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
770 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
771 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
772 }
773
774 mContext.binder.callingUid = Process.SYSTEM_UID;
775 mContext.callerPermissions.remove(permission.MANAGE_USERS);
776 // System can still call "OnAnyUser" without MANAGE_USERS.
777 if (hasDeviceOwner) {
778 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
779 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
780 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
781
782 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
783 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
784 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
785 } else {
786 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
787 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
788 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
789
790 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
791 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
792 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
793 }
794
795 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
796 // Still no MANAGE_USERS.
797 if (hasDeviceOwner) {
798 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
799 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
800 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
801 } else {
802 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
803 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
804 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
805 }
806
807 try {
808 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
809 fail();
810 } catch (SecurityException expected) {
811 }
812 try {
813 dpm.getDeviceOwnerComponentOnAnyUser();
814 fail();
815 } catch (SecurityException expected) {
816 }
817 try {
818 dpm.getDeviceOwnerUserId();
819 fail();
820 } catch (SecurityException expected) {
821 }
822 try {
823 dpm.getDeviceOwnerNameOnAnyUser();
824 fail();
825 } catch (SecurityException expected) {
826 }
827
828 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
829 // Still no MANAGE_USERS.
830 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
831 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
832 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
833
834 try {
835 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
836 fail();
837 } catch (SecurityException expected) {
838 }
839 try {
840 dpm.getDeviceOwnerComponentOnAnyUser();
841 fail();
842 } catch (SecurityException expected) {
843 }
844 try {
845 dpm.getDeviceOwnerUserId();
846 fail();
847 } catch (SecurityException expected) {
848 }
849 try {
850 dpm.getDeviceOwnerNameOnAnyUser();
851 fail();
852 } catch (SecurityException expected) {
853 }
854
855 // Restore.
856 mContext.binder.callingUid = origCallingUser;
857 mContext.callerPermissions.addAll(origPermissions);
858 }
859
860
Makoto Onukib643fb02015-09-22 15:03:44 -0700861 /**
862 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
863 */
864 public void testSetDeviceOwner_noSuchPackage() {
865 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800866 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700867 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
868 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
869
870 // Call from a process on the system user.
871 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
872
Makoto Onukib643fb02015-09-22 15:03:44 -0700873 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700874 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700875 fail("Didn't throw IllegalArgumentException");
876 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700877 assertTrue("Message was: " + expected.getMessage(),
878 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700879 }
880 }
881
882 public void testSetDeviceOwner_failures() throws Exception {
883 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
884 }
885
Makoto Onukia52562c2015-10-01 16:12:31 -0700886 public void testClearDeviceOwner() throws Exception {
887 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800888 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700889 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
890 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
891
892 // Set admin1 as a DA to the secondary user.
893 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
894
895 dpm.setActiveAdmin(admin1, /* replace =*/ false);
896
897 // Set admin 1 as the DO to the system user.
898
899 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
900 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
901 dpm.setActiveAdmin(admin1, /* replace =*/ false);
902 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
903
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000904 // Verify internal calls.
905 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
906 eq(admin1.getPackageName()));
907
Makoto Onukic8a5a552015-11-19 14:29:12 -0800908 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700909
Makoto Onuki90b89652016-01-28 14:44:18 -0800910 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
911
912 assertTrue(dpm.isAdminActive(admin1));
913 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
914
Makoto Onukia52562c2015-10-01 16:12:31 -0700915 // Set up other mocks.
916 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
917
918 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700919 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700920 eq(admin1.getPackageName()),
921 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800922
923 // But first pretend the user is locked. Then it should fail.
924 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
925 try {
926 dpm.clearDeviceOwnerApp(admin1.getPackageName());
927 fail("Didn't throw IllegalStateException");
928 } catch (IllegalStateException expected) {
929 MoreAsserts.assertContainsRegex(
930 "User must be running and unlocked", expected.getMessage());
931 }
932
933 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800934 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700935 dpm.clearDeviceOwnerApp(admin1.getPackageName());
936
937 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800938 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700939
Makoto Onuki90b89652016-01-28 14:44:18 -0800940 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
941 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100942 eq(null),
943 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800944
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700945 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100946
947 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
948 // and once for clearing it.
949 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
950 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
951 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700952 // TODO Check other calls.
953 }
954
955 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
956 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800957 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700958 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
959 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
960
961 // Set admin1 as a DA to the secondary user.
962 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
963
964 dpm.setActiveAdmin(admin1, /* replace =*/ false);
965
966 // Set admin 1 as the DO to the system user.
967
968 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
969 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
970 dpm.setActiveAdmin(admin1, /* replace =*/ false);
971 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
972
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000973 // Verify internal calls.
974 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
975 eq(admin1.getPackageName()));
976
Makoto Onukic8a5a552015-11-19 14:29:12 -0800977 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700978
979 // Now call clear from the secondary user, which should throw.
980 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
981
982 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700983 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700984 eq(admin1.getPackageName()),
985 anyInt());
986 try {
987 dpm.clearDeviceOwnerApp(admin1.getPackageName());
988 fail("Didn't throw");
989 } catch (SecurityException e) {
990 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
991 }
992
Makoto Onukic8a5a552015-11-19 14:29:12 -0800993 // DO shouldn't be removed.
994 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700995 }
996
Makoto Onukib643fb02015-09-22 15:03:44 -0700997 public void testSetProfileOwner() throws Exception {
998 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700999
Makoto Onuki90b89652016-01-28 14:44:18 -08001000 // PO admin can't be deactivated.
1001 dpm.removeActiveAdmin(admin1);
1002 assertTrue(dpm.isAdminActive(admin1));
1003
Makoto Onuki803d6752015-10-30 12:58:39 -07001004 // Try setting DO on the same user, which should fail.
1005 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1006 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1007 try {
1008 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1009 fail("IllegalStateException not thrown");
1010 } catch (IllegalStateException expected) {
1011 assertTrue("Message was: " + expected.getMessage(),
1012 expected.getMessage().contains("already has a profile owner"));
1013 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001014 }
1015
Makoto Onuki90b89652016-01-28 14:44:18 -08001016 public void testClearProfileOwner() throws Exception {
1017 setAsProfileOwner(admin1);
1018
1019 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1020
1021 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1022 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1023
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001024 // First try when the user is locked, which should fail.
1025 when(mContext.userManager.isUserUnlocked(anyInt()))
1026 .thenReturn(false);
1027 try {
1028 dpm.clearProfileOwner(admin1);
1029 fail("Didn't throw IllegalStateException");
1030 } catch (IllegalStateException expected) {
1031 MoreAsserts.assertContainsRegex(
1032 "User must be running and unlocked", expected.getMessage());
1033 }
1034 // Clear, really.
1035 when(mContext.userManager.isUserUnlocked(anyInt()))
1036 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001037 dpm.clearProfileOwner(admin1);
1038
1039 // Check
1040 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001041 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001042 }
1043
Makoto Onukib643fb02015-09-22 15:03:44 -07001044 public void testSetProfileOwner_failures() throws Exception {
1045 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1046 }
1047
Makoto Onukia52562c2015-10-01 16:12:31 -07001048 public void testGetDeviceOwnerAdminLocked() throws Exception {
1049 checkDeviceOwnerWithMultipleDeviceAdmins();
1050 }
1051
1052 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1053 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1054 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1055 // make sure it gets the right component from the right user.
1056
1057 final int ANOTHER_USER_ID = 100;
1058 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1059
1060 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1061
1062 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001063 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001064 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1065 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1066
1067 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1068
Victor Change29cd472016-03-02 20:57:42 +00001069 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1070
Makoto Onukia52562c2015-10-01 16:12:31 -07001071 // Make sure the admin packge is installed to each user.
1072 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1073 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1074
1075 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1076 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1077
1078 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1079
1080
1081 // Set active admins to the users.
1082 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1083 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1084
1085 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1086 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1087
1088 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1089
1090 // Set DO on the first non-system user.
1091 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1092 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1093
Makoto Onukic8a5a552015-11-19 14:29:12 -08001094 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001095
1096 // Then check getDeviceOwnerAdminLocked().
1097 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1098 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1099 }
1100
1101 /**
1102 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001103 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1104 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001105 *
1106 * We didn't use to persist the DO component class name, but now we do, and the above method
1107 * finds the right component from a package name upon migration.
1108 */
1109 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001110 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001111 checkDeviceOwnerWithMultipleDeviceAdmins();
1112
1113 // Overwrite the device owner setting and clears the clas name.
1114 dpms.mOwners.setDeviceOwner(
1115 new ComponentName(admin2.getPackageName(), ""),
1116 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1117 dpms.mOwners.writeDeviceOwner();
1118
1119 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001120 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001121
1122 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001123 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1124 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001125 initializeDpms();
1126
1127 // Now the DO component name is a full name.
1128 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1129 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001130 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001131 }
1132
Makoto Onukib643fb02015-09-22 15:03:44 -07001133 public void testSetGetApplicationRestriction() {
1134 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001135 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001136
1137 {
1138 Bundle rest = new Bundle();
1139 rest.putString("KEY_STRING", "Foo1");
1140 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1141 }
1142
1143 {
1144 Bundle rest = new Bundle();
1145 rest.putString("KEY_STRING", "Foo2");
1146 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1147 }
1148
1149 {
1150 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1151 assertNotNull(returned);
1152 assertEquals(returned.size(), 1);
1153 assertEquals(returned.get("KEY_STRING"), "Foo1");
1154 }
1155
1156 {
1157 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1158 assertNotNull(returned);
1159 assertEquals(returned.size(), 1);
1160 assertEquals(returned.get("KEY_STRING"), "Foo2");
1161 }
1162
1163 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1164 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1165 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001166
Edman Anjosf9946772016-11-28 16:35:15 +01001167 /**
1168 * Setup a package in the package manager mock. Useful for faking installed applications.
1169 *
1170 * @param packageName the name of the package to be setup
1171 * @param appId the application ID to be given to the package
1172 * @return the UID of the package as known by the mock package manager
1173 */
1174 private int setupPackageInPackageManager(final String packageName, final int appId)
1175 throws Exception {
1176 // Make the PackageManager return the package instead of throwing a NameNotFoundException
1177 final PackageInfo pi = new PackageInfo();
1178 pi.applicationInfo = new ApplicationInfo();
1179 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1180 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1181 eq(packageName),
1182 anyInt(),
1183 eq(DpmMockContext.CALLER_USER_HANDLE));
1184 // Setup application UID with the PackageManager
1185 final int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, appId);
1186 doReturn(uid).when(mContext.packageManager).getPackageUidAsUser(
1187 eq(packageName),
1188 eq(DpmMockContext.CALLER_USER_HANDLE));
1189 // Associate packageName to uid
1190 doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid));
1191 doReturn(new String[]{packageName})
1192 .when(mContext.ipackageManager).getPackagesForUid(eq(uid));
1193 return uid;
1194 }
1195
1196 /**
1197 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1198 * privileges can acually be exercised by a delegate are not covered here.
1199 */
1200 public void testDelegation() throws Exception {
1201 setAsProfileOwner(admin1);
1202
1203 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1204
1205 // Given two packages
1206 final String CERT_DELEGATE = "com.delegate.certs";
1207 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1208 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1209 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1210 20989);
1211
1212 // On delegation
1213 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1214 mContext.packageName = admin1.getPackageName();
1215 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1216 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1217
1218 // DPMS correctly stores and retrieves the delegates
1219 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1220 assertEquals(2, policy.mDelegationMap.size());
1221 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1222 DELEGATION_CERT_INSTALL);
1223 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1224 DELEGATION_CERT_INSTALL);
1225 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1226 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1227 DELEGATION_APP_RESTRICTIONS);
1228 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1229 DELEGATION_APP_RESTRICTIONS);
1230 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1231
1232 // On calling install certificate APIs from an unauthorized process
1233 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1234 mContext.packageName = RESTRICTIONS_DELEGATE;
1235
1236 // DPMS throws a SecurityException
1237 try {
1238 dpm.installCaCert(null, null);
1239 fail("Didn't throw SecurityException on unauthorized access");
1240 } catch (SecurityException expected) {
1241 }
1242
1243 // On calling install certificate APIs from an authorized process
1244 mContext.binder.callingUid = CERT_DELEGATE_UID;
1245 mContext.packageName = CERT_DELEGATE;
1246
1247 // DPMS executes without a SecurityException
1248 try {
1249 dpm.installCaCert(null, null);
1250 } catch (SecurityException unexpected) {
1251 fail("Threw SecurityException on authorized access");
1252 } catch (NullPointerException expected) {
1253 }
1254
1255 // On removing a delegate
1256 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1257 mContext.packageName = admin1.getPackageName();
1258 dpm.setCertInstallerPackage(admin1, null);
1259
1260 // DPMS does not allow access to ex-delegate
1261 mContext.binder.callingUid = CERT_DELEGATE_UID;
1262 mContext.packageName = CERT_DELEGATE;
1263 try {
1264 dpm.installCaCert(null, null);
1265 fail("Didn't throw SecurityException on unauthorized access");
1266 } catch (SecurityException expected) {
1267 }
1268
1269 // But still allows access to other existing delegates
1270 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1271 mContext.packageName = RESTRICTIONS_DELEGATE;
1272 try {
1273 dpm.getApplicationRestrictions(null, "pkg");
1274 } catch (SecurityException expected) {
1275 fail("Threw SecurityException on authorized access");
1276 }
1277 }
1278
Esteban Talaverabf60f722015-12-10 16:26:44 +00001279 public void testApplicationRestrictionsManagingApp() throws Exception {
1280 setAsProfileOwner(admin1);
1281
Rubin Xued1928a2016-02-11 17:23:06 +00001282 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001283 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1284 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001285 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1286 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001287
Esteban Talaverabf60f722015-12-10 16:26:44 +00001288 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1289 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001290 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1291 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001292 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1293 Bundle rest = new Bundle();
1294 rest.putString("KEY_STRING", "Foo1");
1295 try {
1296 dpm.setApplicationRestrictions(null, "pkg1", rest);
1297 fail("Didn't throw expected SecurityException");
1298 } catch (SecurityException expected) {
1299 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001300 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1301 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001302 }
1303 try {
1304 dpm.getApplicationRestrictions(null, "pkg1");
1305 fail("Didn't throw expected SecurityException");
1306 } catch (SecurityException expected) {
1307 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001308 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1309 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001310 }
1311
1312 // Check via the profile owner that no restrictions were set.
1313 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001314 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001315 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1316
Rubin Xued1928a2016-02-11 17:23:06 +00001317 // Check the API does not allow setting a non-existent package
1318 try {
1319 dpm.setApplicationRestrictionsManagingPackage(admin1,
1320 nonExistAppRestrictionsManagerPackage);
1321 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001322 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001323 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001324 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001325 }
1326
Esteban Talaverabf60f722015-12-10 16:26:44 +00001327 // Let appRestrictionsManagerPackage manage app restrictions
1328 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1329 assertEquals(appRestrictionsManagerPackage,
1330 dpm.getApplicationRestrictionsManagingPackage(admin1));
1331
1332 // Now that package should be able to set and retrieve app restrictions.
1333 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001334 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001335 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1336 dpm.setApplicationRestrictions(null, "pkg1", rest);
1337 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1338 assertEquals(1, returned.size(), 1);
1339 assertEquals("Foo1", returned.get("KEY_STRING"));
1340
1341 // The same app running on a separate user shouldn't be able to manage app restrictions.
1342 mContext.binder.callingUid = UserHandle.getUid(
1343 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1344 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1345 try {
1346 dpm.setApplicationRestrictions(null, "pkg1", rest);
1347 fail("Didn't throw expected SecurityException");
1348 } catch (SecurityException expected) {
1349 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001350 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1351 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001352 }
1353
1354 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1355 // too.
1356 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001357 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001358 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1359 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1360 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1361
1362 // Removing the ability for the package to manage app restrictions.
1363 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1364 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1365 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001366 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001367 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1368 try {
1369 dpm.setApplicationRestrictions(null, "pkg1", null);
1370 fail("Didn't throw expected SecurityException");
1371 } catch (SecurityException expected) {
1372 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001373 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1374 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001375 }
1376 }
1377
Makoto Onukia4f11972015-10-01 13:19:58 -07001378 public void testSetUserRestriction_asDo() throws Exception {
1379 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001380 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001381 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1382 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1383
1384 // First, set DO.
1385
1386 // Call from a process on the system user.
1387 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1388
1389 // Make sure admin1 is installed on system user.
1390 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001391
1392 // Call.
1393 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001394 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001395 UserHandle.USER_SYSTEM));
1396
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001397 // Check that the user restrictions that are enabled by default are set. Then unset them.
1398 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001399 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001400 DpmTestUtils.assertRestrictions(
1401 DpmTestUtils.newRestrictions(defaultRestrictions),
1402 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1403 );
1404 DpmTestUtils.assertRestrictions(
1405 DpmTestUtils.newRestrictions(defaultRestrictions),
1406 dpm.getUserRestrictions(admin1)
1407 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001408 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1409 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001410 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001411 eq(true) /* isDeviceOwner */,
1412 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001413 );
1414 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001415
1416 for (String restriction : defaultRestrictions) {
1417 dpm.clearUserRestriction(admin1, restriction);
1418 }
1419
Esteban Talavera548a04b2016-12-20 15:22:30 +00001420 assertNoDeviceOwnerRestrictions();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001421 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001422
1423 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1424 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1425 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001426 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1427 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001428 reset(mContext.userManagerInternal);
1429
Makoto Onukia4f11972015-10-01 13:19:58 -07001430 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001431 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1432 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001433 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1434 UserManager.DISALLOW_ADD_USER),
1435 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001436 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001437
Makoto Onuki068c54a2015-10-13 14:34:03 -07001438 DpmTestUtils.assertRestrictions(
1439 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001440 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001441 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1442 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001443 DpmTestUtils.assertRestrictions(
1444 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001445 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001446 dpm.getUserRestrictions(admin1)
1447 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001448
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1450 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1451 eq(UserHandle.USER_SYSTEM),
1452 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001453 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001454 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001455
Makoto Onuki068c54a2015-10-13 14:34:03 -07001456 DpmTestUtils.assertRestrictions(
1457 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1458 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1459 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001460 DpmTestUtils.assertRestrictions(
1461 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1462 dpm.getUserRestrictions(admin1)
1463 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001464
1465 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001466 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1467 eq(UserHandle.USER_SYSTEM),
1468 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001469 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001470 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001471
Esteban Talavera548a04b2016-12-20 15:22:30 +00001472 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001473
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001474 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1475 // DO sets them, the scope is global.
1476 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1477 reset(mContext.userManagerInternal);
1478 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1479 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1480 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001481 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001482 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1483 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001484 reset(mContext.userManagerInternal);
1485
1486 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1487 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov6a40f092016-10-25 15:46:51 +01001488 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001489
1490 // More tests.
1491 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1492 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1493 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001494 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1495 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001496 reset(mContext.userManagerInternal);
1497
1498 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1499 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1500 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001501 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001502 UserManager.DISALLOW_ADD_USER),
1503 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001504 reset(mContext.userManagerInternal);
1505
1506 dpm.setCameraDisabled(admin1, true);
1507 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1508 eq(UserHandle.USER_SYSTEM),
1509 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001510 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001511 UserManager.DISALLOW_ADD_USER),
1512 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001513 reset(mContext.userManagerInternal);
1514
1515 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1516 // locally.
1517 dpm.setCameraDisabled(admin1, false);
1518 reset(mContext.userManagerInternal);
1519
1520 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1521 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1522 dpm.setCameraDisabled(admin2, true);
1523
1524 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1525 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001526 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001527 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001528 UserManager.DISALLOW_ADD_USER),
1529 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001530 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001531 // TODO Make sure restrictions are written to the file.
1532 }
1533
1534 public void testSetUserRestriction_asPo() {
1535 setAsProfileOwner(admin1);
1536
Makoto Onuki068c54a2015-10-13 14:34:03 -07001537 DpmTestUtils.assertRestrictions(
1538 DpmTestUtils.newRestrictions(),
1539 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1540 .ensureUserRestrictions()
1541 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001542
1543 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001544 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1545 eq(DpmMockContext.CALLER_USER_HANDLE),
1546 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001547 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001548 reset(mContext.userManagerInternal);
1549
Makoto Onukia4f11972015-10-01 13:19:58 -07001550 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001551 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1552 eq(DpmMockContext.CALLER_USER_HANDLE),
1553 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1554 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001555 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001556 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001557
Makoto Onuki068c54a2015-10-13 14:34:03 -07001558 DpmTestUtils.assertRestrictions(
1559 DpmTestUtils.newRestrictions(
1560 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1561 UserManager.DISALLOW_OUTGOING_CALLS
1562 ),
1563 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1564 .ensureUserRestrictions()
1565 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001566 DpmTestUtils.assertRestrictions(
1567 DpmTestUtils.newRestrictions(
1568 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1569 UserManager.DISALLOW_OUTGOING_CALLS
1570 ),
1571 dpm.getUserRestrictions(admin1)
1572 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001573
1574 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001575 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1576 eq(DpmMockContext.CALLER_USER_HANDLE),
1577 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001578 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001579 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001580
1581 DpmTestUtils.assertRestrictions(
1582 DpmTestUtils.newRestrictions(
1583 UserManager.DISALLOW_OUTGOING_CALLS
1584 ),
1585 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1586 .ensureUserRestrictions()
1587 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001588 DpmTestUtils.assertRestrictions(
1589 DpmTestUtils.newRestrictions(
1590 UserManager.DISALLOW_OUTGOING_CALLS
1591 ),
1592 dpm.getUserRestrictions(admin1)
1593 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001594
1595 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001596 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1597 eq(DpmMockContext.CALLER_USER_HANDLE),
1598 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001599 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001600 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001601
Makoto Onuki068c54a2015-10-13 14:34:03 -07001602 DpmTestUtils.assertRestrictions(
1603 DpmTestUtils.newRestrictions(),
1604 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1605 .ensureUserRestrictions()
1606 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001607 DpmTestUtils.assertRestrictions(
1608 DpmTestUtils.newRestrictions(),
1609 dpm.getUserRestrictions(admin1)
1610 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001611
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001612 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1613 // though when DO sets them they'll be applied globally.
1614 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1615 reset(mContext.userManagerInternal);
1616 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1617 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1618 eq(DpmMockContext.CALLER_USER_HANDLE),
1619 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1620 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001621 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001622 reset(mContext.userManagerInternal);
1623
1624 dpm.setCameraDisabled(admin1, true);
1625 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1626 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001627 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001628 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001629 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001630 reset(mContext.userManagerInternal);
1631
Makoto Onukia4f11972015-10-01 13:19:58 -07001632 // TODO Make sure restrictions are written to the file.
1633 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001634
Esteban Talavera548a04b2016-12-20 15:22:30 +00001635
1636 public void testDefaultEnabledUserRestrictions() throws Exception {
1637 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1638 mContext.callerPermissions.add(permission.MANAGE_USERS);
1639 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1640 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1641
1642 // First, set DO.
1643
1644 // Call from a process on the system user.
1645 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1646
1647 // Make sure admin1 is installed on system user.
1648 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1649
1650 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1651 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1652 UserHandle.USER_SYSTEM));
1653
1654 // Check that the user restrictions that are enabled by default are set. Then unset them.
1655 String[] defaultRestrictions = UserRestrictionsUtils
1656 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1657 assertTrue(defaultRestrictions.length > 0);
1658 DpmTestUtils.assertRestrictions(
1659 DpmTestUtils.newRestrictions(defaultRestrictions),
1660 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1661 );
1662 DpmTestUtils.assertRestrictions(
1663 DpmTestUtils.newRestrictions(defaultRestrictions),
1664 dpm.getUserRestrictions(admin1)
1665 );
1666 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1667 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001668 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001669 eq(true) /* isDeviceOwner */,
1670 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001671 );
1672 reset(mContext.userManagerInternal);
1673
1674 for (String restriction : defaultRestrictions) {
1675 dpm.clearUserRestriction(admin1, restriction);
1676 }
1677
1678 assertNoDeviceOwnerRestrictions();
1679
1680 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1681 reset(mContext.userManagerInternal);
1682 initializeDpms();
1683 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1684 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1685
1686 assertNoDeviceOwnerRestrictions();
1687
1688 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1689 // is set as it wasn't enabled during setDeviceOwner.
1690 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1691 assertFalse(UserRestrictionsUtils
1692 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1693 UserRestrictionsUtils
1694 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1695 try {
1696 reset(mContext.userManagerInternal);
1697 initializeDpms();
1698 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1699 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1700
1701 DpmTestUtils.assertRestrictions(
1702 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1703 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1704 );
1705 DpmTestUtils.assertRestrictions(
1706 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1707 dpm.getUserRestrictions(admin1)
1708 );
1709 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1710 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001711 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001712 eq(true) /* isDeviceOwner */,
1713 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001714 );
1715 reset(mContext.userManagerInternal);
1716
1717 // Remove the restriction.
1718 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1719
1720 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1721 initializeDpms();
1722 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1723 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1724 assertNoDeviceOwnerRestrictions();
1725 } finally {
1726 UserRestrictionsUtils
1727 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1728 }
1729 }
1730
1731 private void assertNoDeviceOwnerRestrictions() {
1732 DpmTestUtils.assertRestrictions(
1733 DpmTestUtils.newRestrictions(),
1734 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1735 );
1736 DpmTestUtils.assertRestrictions(
1737 DpmTestUtils.newRestrictions(),
1738 dpm.getUserRestrictions(admin1)
1739 );
1740 }
1741
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001742 public void testGetMacAddress() throws Exception {
1743 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1744 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1745 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1746
1747 // In this test, change the caller user to "system".
1748 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1749
1750 // Make sure admin1 is installed on system user.
1751 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1752
1753 // Test 1. Caller doesn't have DO or DA.
1754 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001755 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001756 fail();
1757 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001758 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001759 }
1760
1761 // DO needs to be an DA.
1762 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1763 assertTrue(dpm.isAdminActive(admin1));
1764
1765 // Test 2. Caller has DA, but not DO.
1766 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001767 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001768 fail();
1769 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001770 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001771 }
1772
1773 // Test 3. Caller has PO, but not DO.
1774 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1775 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001776 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001777 fail();
1778 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001779 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001780 }
1781
1782 // Remove PO.
1783 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001784 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001785 // Test 4, Caller is DO now.
1786 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1787
1788 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001789 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001790
1791 // 4-2. Returns WifiInfo, but with the default MAC.
1792 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001793 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001794
1795 // 4-3. With a real MAC address.
1796 final WifiInfo wi = new WifiInfo();
1797 wi.setMacAddress("11:22:33:44:55:66");
1798 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001799 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001800 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001801
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001802 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001803 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1804 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1805
1806 // In this test, change the caller user to "system".
1807 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1808
1809 // Make sure admin1 is installed on system user.
1810 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1811
1812 // Set admin1 as DA.
1813 dpm.setActiveAdmin(admin1, false);
1814 assertTrue(dpm.isAdminActive(admin1));
1815 try {
1816 dpm.reboot(admin1);
1817 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1818 } catch (SecurityException expected) {
1819 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1820 }
1821
1822 // Set admin1 as PO.
1823 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1824 try {
1825 dpm.reboot(admin1);
1826 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1827 } catch (SecurityException expected) {
1828 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1829 }
1830
1831 // Remove PO and add DO.
1832 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001833 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001834 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1835
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001836 // admin1 is DO.
1837 // Set current call state of device to ringing.
1838 when(mContext.telephonyManager.getCallState())
1839 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1840 try {
1841 dpm.reboot(admin1);
1842 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1843 } catch (IllegalStateException expected) {
1844 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1845 }
1846
1847 // Set current call state of device to dialing/active.
1848 when(mContext.telephonyManager.getCallState())
1849 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1850 try {
1851 dpm.reboot(admin1);
1852 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1853 } catch (IllegalStateException expected) {
1854 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1855 }
1856
1857 // Set current call state of device to idle.
1858 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001859 dpm.reboot(admin1);
1860 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001861
1862 public void testSetGetSupportText() {
1863 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1864 dpm.setActiveAdmin(admin1, true);
1865 dpm.setActiveAdmin(admin2, true);
1866 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1867
1868 // Null default support messages.
1869 {
1870 assertNull(dpm.getLongSupportMessage(admin1));
1871 assertNull(dpm.getShortSupportMessage(admin1));
1872 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1873 assertNull(dpm.getShortSupportMessageForUser(admin1,
1874 DpmMockContext.CALLER_USER_HANDLE));
1875 assertNull(dpm.getLongSupportMessageForUser(admin1,
1876 DpmMockContext.CALLER_USER_HANDLE));
1877 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1878 }
1879
1880 // Only system can call the per user versions.
1881 {
1882 try {
1883 dpm.getShortSupportMessageForUser(admin1,
1884 DpmMockContext.CALLER_USER_HANDLE);
1885 fail("Only system should be able to call getXXXForUser versions");
1886 } catch (SecurityException expected) {
1887 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1888 }
1889 try {
1890 dpm.getLongSupportMessageForUser(admin1,
1891 DpmMockContext.CALLER_USER_HANDLE);
1892 fail("Only system should be able to call getXXXForUser versions");
1893 } catch (SecurityException expected) {
1894 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1895 }
1896 }
1897
1898 // Can't set message for admin in another uid.
1899 {
1900 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1901 try {
1902 dpm.setShortSupportMessage(admin1, "Some text");
1903 fail("Admins should only be able to change their own support text.");
1904 } catch (SecurityException expected) {
1905 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1906 }
1907 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1908 }
1909
1910 // Set/Get short returns what it sets and other admins text isn't changed.
1911 {
1912 final String supportText = "Some text to test with.";
1913 dpm.setShortSupportMessage(admin1, supportText);
1914 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1915 assertNull(dpm.getLongSupportMessage(admin1));
1916 assertNull(dpm.getShortSupportMessage(admin2));
1917
1918 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1919 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1920 DpmMockContext.CALLER_USER_HANDLE));
1921 assertNull(dpm.getShortSupportMessageForUser(admin2,
1922 DpmMockContext.CALLER_USER_HANDLE));
1923 assertNull(dpm.getLongSupportMessageForUser(admin1,
1924 DpmMockContext.CALLER_USER_HANDLE));
1925 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1926
1927 dpm.setShortSupportMessage(admin1, null);
1928 assertNull(dpm.getShortSupportMessage(admin1));
1929 }
1930
1931 // Set/Get long returns what it sets and other admins text isn't changed.
1932 {
1933 final String supportText = "Some text to test with.\nWith more text.";
1934 dpm.setLongSupportMessage(admin1, supportText);
1935 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1936 assertNull(dpm.getShortSupportMessage(admin1));
1937 assertNull(dpm.getLongSupportMessage(admin2));
1938
1939 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1940 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1941 DpmMockContext.CALLER_USER_HANDLE));
1942 assertNull(dpm.getLongSupportMessageForUser(admin2,
1943 DpmMockContext.CALLER_USER_HANDLE));
1944 assertNull(dpm.getShortSupportMessageForUser(admin1,
1945 DpmMockContext.CALLER_USER_HANDLE));
1946 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1947
1948 dpm.setLongSupportMessage(admin1, null);
1949 assertNull(dpm.getLongSupportMessage(admin1));
1950 }
1951 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001952
1953 /**
1954 * Test for:
1955 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001956 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001957 * {@link DevicePolicyManager#isAffiliatedUser}
1958 */
1959 public void testUserAffiliation() throws Exception {
1960 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1961 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1962 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1963
1964 // Check that the system user is unaffiliated.
1965 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1966 assertFalse(dpm.isAffiliatedUser());
1967
1968 // Set a device owner on the system user. Check that the system user becomes affiliated.
1969 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1970 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1971 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1972 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001973 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001974
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001975 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001976 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1977 setAsProfileOwner(admin2);
1978 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001979 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001980
1981 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1982 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001983 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001984 userAffiliationIds.add("red");
1985 userAffiliationIds.add("green");
1986 userAffiliationIds.add("blue");
1987 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001988 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001989 assertFalse(dpm.isAffiliatedUser());
1990
1991 // Have the device owner specify a set of affiliation ids that do not intersect with those
1992 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001993 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001994 deviceAffiliationIds.add("cyan");
1995 deviceAffiliationIds.add("yellow");
1996 deviceAffiliationIds.add("magenta");
1997 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1998 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001999 MoreAsserts.assertContentsInAnyOrder(
2000 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002001 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2002 assertFalse(dpm.isAffiliatedUser());
2003
2004 // Have the profile owner specify a set of affiliation ids that intersect with those
2005 // specified by the device owner. Check that the test user becomes affiliated.
2006 userAffiliationIds.add("yellow");
2007 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002008 MoreAsserts.assertContentsInAnyOrder(
2009 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002010 assertTrue(dpm.isAffiliatedUser());
2011
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002012 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
2013 dpm.setAffiliationIds(admin2, Collections.emptyList());
2014 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002015 assertFalse(dpm.isAffiliatedUser());
2016
2017 // Check that the system user remains affiliated.
2018 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2019 assertTrue(dpm.isAffiliatedUser());
2020 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002021
2022 public void testGetUserProvisioningState_defaultResult() {
2023 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2024 }
2025
2026 public void testSetUserProvisioningState_permission() throws Exception {
2027 setupProfileOwner();
2028 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2029
2030 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2031 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2032 }
2033
2034 public void testSetUserProvisioningState_unprivileged() throws Exception {
2035 setupProfileOwner();
2036 try {
2037 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2038 DpmMockContext.CALLER_USER_HANDLE);
2039 fail("Expected SecurityException");
2040 } catch (SecurityException expected) {
2041 }
2042 }
2043
2044 public void testSetUserProvisioningState_noManagement() {
2045 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2046 try {
2047 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2048 DpmMockContext.CALLER_USER_HANDLE);
2049 fail("IllegalStateException expected");
2050 } catch (IllegalStateException e) {
2051 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
2052 e.getMessage());
2053 }
2054 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2055 }
2056
2057 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2058 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2059 setupDeviceOwner();
2060 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2061
2062 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2063 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2064 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2065 }
2066
2067 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2068 throws Exception {
2069 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2070 setupDeviceOwner();
2071 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2072
2073 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2074 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2075 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2076 }
2077
2078 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2079 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2080 setupDeviceOwner();
2081 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2082
2083 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2084 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2085 }
2086
2087 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2088 throws Exception {
2089 setupProfileOwner();
2090 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2091
2092 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2093 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2094 DevicePolicyManager.STATE_USER_UNMANAGED);
2095 }
2096
2097 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2098 throws Exception {
2099 setupProfileOwner();
2100 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2101
2102 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2103 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2104 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2105 }
2106
2107 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2108 setupProfileOwner();
2109 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2110
2111 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2112 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2113 }
2114
2115 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2116 setupProfileOwner();
2117 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2118
2119 try {
2120 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2121 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2122 DevicePolicyManager.STATE_USER_UNMANAGED);
2123 fail("Expected IllegalStateException");
2124 } catch (IllegalStateException e) {
2125 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2126 e.getMessage());
2127 }
2128 }
2129
2130 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2131 throws Exception {
2132 setupProfileOwner();
2133 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2134
2135 try {
2136 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2137 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2138 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2139 fail("Expected IllegalStateException");
2140 } catch (IllegalStateException e) {
2141 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2142 e.getMessage());
2143 }
2144 }
2145
2146 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2147 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2148 for (int state : states) {
2149 dpm.setUserProvisioningState(state, userId);
2150 assertEquals(state, dpm.getUserProvisioningState());
2151 }
2152 }
2153
2154 private void setupProfileOwner() throws Exception {
2155 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2156
2157 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2158 dpm.setActiveAdmin(admin1, false);
2159 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2160
2161 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2162 }
2163
2164 private void setupDeviceOwner() throws Exception {
2165 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2166
2167 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2168 dpm.setActiveAdmin(admin1, false);
2169 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2170
2171 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2172 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002173
2174 public void testSetMaximumTimeToLock() {
2175 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2176
2177 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2178 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2179
2180 reset(mMockContext.powerManagerInternal);
2181 reset(mMockContext.settings);
2182
2183 dpm.setMaximumTimeToLock(admin1, 0);
2184 verifyScreenTimeoutCall(null, false);
2185 reset(mMockContext.powerManagerInternal);
2186 reset(mMockContext.settings);
2187
2188 dpm.setMaximumTimeToLock(admin1, 1);
2189 verifyScreenTimeoutCall(1, true);
2190 reset(mMockContext.powerManagerInternal);
2191 reset(mMockContext.settings);
2192
2193 dpm.setMaximumTimeToLock(admin2, 10);
2194 verifyScreenTimeoutCall(null, false);
2195 reset(mMockContext.powerManagerInternal);
2196 reset(mMockContext.settings);
2197
2198 dpm.setMaximumTimeToLock(admin1, 5);
2199 verifyScreenTimeoutCall(5, true);
2200 reset(mMockContext.powerManagerInternal);
2201 reset(mMockContext.settings);
2202
2203 dpm.setMaximumTimeToLock(admin2, 4);
2204 verifyScreenTimeoutCall(4, true);
2205 reset(mMockContext.powerManagerInternal);
2206 reset(mMockContext.settings);
2207
2208 dpm.setMaximumTimeToLock(admin1, 0);
2209 reset(mMockContext.powerManagerInternal);
2210 reset(mMockContext.settings);
2211
2212 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2213 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2214 reset(mMockContext.powerManagerInternal);
2215 reset(mMockContext.settings);
2216
2217 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2218 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2219 reset(mMockContext.powerManagerInternal);
2220 reset(mMockContext.settings);
2221
2222 dpm.setMaximumTimeToLock(admin2, 10);
2223 verifyScreenTimeoutCall(10, true);
2224 reset(mMockContext.powerManagerInternal);
2225 reset(mMockContext.settings);
2226
2227 // There's no restriction; shold be set to MAX.
2228 dpm.setMaximumTimeToLock(admin2, 0);
2229 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2230 }
2231
Michal Karpinski943aabd2016-10-06 11:09:25 +01002232 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2233 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2234 setupDeviceOwner();
2235 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2236
Michal Karpinskid084ca52017-01-18 15:54:18 +00002237 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2238 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2239 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2240 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2241 - ONE_MINUTE;
2242
2243 // verify that the minimum timeout cannot be modified on user builds (system property is
2244 // not being read)
2245 mContext.buildMock.isDebuggable = false;
2246
2247 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2248 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2249 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2250
2251 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2252
2253 // restore to the debuggable build state
2254 mContext.buildMock.isDebuggable = true;
2255
2256 // Always return the default (second arg) when getting system property for long type
2257 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2258 new Answer<Long>() {
2259 @Override
2260 public Long answer(InvocationOnMock invocation) throws Throwable {
2261 return (Long) invocation.getArguments()[1];
2262 }
2263 }
2264 );
2265
2266 // reset to default (0 means the admin is not participating, so default should be returned)
2267 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002268
2269 // aggregation should be the default if unset by any admin
2270 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2271 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2272
2273 // admin not participating by default
2274 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2275
2276 //clamping from the top
2277 dpm.setRequiredStrongAuthTimeout(admin1,
2278 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2279 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2280 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2281 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2282 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2283
Michal Karpinskid084ca52017-01-18 15:54:18 +00002284 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002285 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2286 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2287 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2288 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2289
2290 // clamping from the bottom
2291 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2292 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2293 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2294
Michal Karpinskid084ca52017-01-18 15:54:18 +00002295 // values within range
2296 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2297 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2298 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2299
2300 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2301 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2302 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002303
2304 // reset to default
2305 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2306 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2307 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2308 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2309
2310 // negative value
2311 try {
2312 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2313 fail("Didn't throw IllegalArgumentException");
2314 } catch (IllegalArgumentException iae) {
2315 }
2316 }
2317
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002318 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2319 boolean shouldStayOnWhilePluggedInBeCleared) {
2320 if (expectedTimeout == null) {
2321 verify(mMockContext.powerManagerInternal, times(0))
2322 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2323 } else {
2324 verify(mMockContext.powerManagerInternal, times(1))
2325 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2326 }
2327 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2328 // UnfinishedVerificationException.
2329 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002330
Esteban Talavera01576862016-12-15 11:16:44 +00002331 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002332 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2333 .thenReturn(false);
2334 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2335 .thenReturn(false);
2336 initializeDpms();
2337 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2338 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2339 .thenReturn(true);
2340 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2341
2342 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002343 }
Victor Chang3e794af2016-03-04 13:48:17 +00002344
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002345 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2346 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002347 mContext.packageName = admin1.getPackageName();
2348 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002349 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2350 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2351 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2352 false);
2353 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2354 }
2355
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002356 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2357 setup_DeviceAdminFeatureOff();
2358 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2359 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2360 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2361 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2362 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2363 assertCheckProvisioningPreCondition(
2364 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2365 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2366 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2367 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2368 }
2369
Esteban Talavera01576862016-12-15 11:16:44 +00002370 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002371 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2372 .thenReturn(false);
2373 initializeDpms();
2374 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2375 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2376 .thenReturn(true);
2377 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2378
2379 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002380 }
Victor Chang3e794af2016-03-04 13:48:17 +00002381
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002382 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2383 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002384 mContext.packageName = admin1.getPackageName();
2385 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002386 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2387 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2388 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2389 false);
2390 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2391
2392 // Test again when split user is on
2393 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2394 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2395 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2396 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2397 true);
2398 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2399 }
2400
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002401 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2402 setup_ManagedProfileFeatureOff();
2403 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2404 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2405 DevicePolicyManager.CODE_OK);
2406 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2407 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2408 assertCheckProvisioningPreCondition(
2409 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2410 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2411 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2412 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2413
2414 // Test again when split user is on
2415 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2416 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2417 DevicePolicyManager.CODE_OK);
2418 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2419 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2420 assertCheckProvisioningPreCondition(
2421 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2422 DevicePolicyManager.CODE_OK);
2423 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2424 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2425 }
2426
Esteban Talavera01576862016-12-15 11:16:44 +00002427 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002428 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2429 .thenReturn(true);
2430 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2431 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2432 .thenReturn(true);
2433 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2434
2435 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002436 }
Victor Chang3e794af2016-03-04 13:48:17 +00002437
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002438 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2439 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002440 mContext.packageName = admin1.getPackageName();
2441 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002442 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2443 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2444 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2445 false /* because of non-split user */);
2446 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2447 false /* because of non-split user */);
2448 }
2449
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002450 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002451 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002452 setup_nonSplitUser_firstBoot_primaryUser();
2453 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2454 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2455 DevicePolicyManager.CODE_OK);
2456 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2457 DevicePolicyManager.CODE_OK);
2458 assertCheckProvisioningPreCondition(
2459 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2460 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2461 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2462 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2463 }
2464
Esteban Talavera01576862016-12-15 11:16:44 +00002465 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002466 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2467 .thenReturn(true);
2468 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2469 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2470 .thenReturn(true);
2471 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2472
2473 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002474 }
Victor Chang3e794af2016-03-04 13:48:17 +00002475
Nicolas Prevot45d29072017-01-18 16:11:19 +00002476 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2477 setDeviceOwner();
2478 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2479 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2480 }
2481
2482 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2483 setup_nonSplitUser_withDo_primaryUser();
2484 final int MANAGED_PROFILE_USER_ID = 18;
2485 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2486 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2487 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2488 false /* we can't remove a managed profile */)).thenReturn(false);
2489 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2490 true)).thenReturn(true);
2491 }
2492
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002493 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2494 throws Exception {
2495 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002496 mContext.packageName = admin1.getPackageName();
2497 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002498 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2499 false/* because of completed device setup */);
2500 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2501 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2502 false/* because of non-split user */);
2503 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2504 false/* because of non-split user */);
2505 }
2506
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002507 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2508 throws Exception {
2509 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2510 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2511 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2512 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2513 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2514 DevicePolicyManager.CODE_OK);
2515 assertCheckProvisioningPreCondition(
2516 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2517 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2518 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2519 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2520 }
2521
Nicolas Prevot45d29072017-01-18 16:11:19 +00002522 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2523 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002524 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002525 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2526
2527 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2528 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002529 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002530
2531 // COMP mode is allowed.
2532 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2533 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002534 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002535
Nicolas Prevot45d29072017-01-18 16:11:19 +00002536 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002537 assertCheckProvisioningPreCondition(
2538 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002539 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002540 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002541 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2542 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2543 }
Esteban Talavera01576862016-12-15 11:16:44 +00002544
Nicolas Prevot45d29072017-01-18 16:11:19 +00002545 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2546 setup_nonSplitUser_withDo_primaryUser();
2547 mContext.packageName = admin1.getPackageName();
2548 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2549 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2550 // other packages should be forbidden.
Esteban Talavera01576862016-12-15 11:16:44 +00002551 when(mContext.userManager.hasUserRestriction(
2552 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2553 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2554 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002555 when(mContext.userManager.getUserRestrictionSource(
2556 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2557 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2558 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2559 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2560 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002561 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002562 assertCheckProvisioningPreCondition(
2563 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002564 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002565 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002566 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2567 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2568 }
Esteban Talavera01576862016-12-15 11:16:44 +00002569
Nicolas Prevot45d29072017-01-18 16:11:19 +00002570 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2571 throws Exception {
2572 setup_nonSplitUser_withDo_primaryUser();
2573 mContext.packageName = admin1.getPackageName();
2574 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002575 // The DO should not be allowed to initiate provisioning if the restriction is set by
2576 // another entity.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002577 when(mContext.userManager.hasUserRestriction(
2578 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2579 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2580 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002581 when(mContext.userManager.getUserRestrictionSource(
2582 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2583 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2584 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2585 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2586 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002587 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2588
2589 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002590 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002591 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002592 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002593 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2594 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2595 }
2596
2597 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2598 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2599 mContext.packageName = admin1.getPackageName();
2600 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2601
2602 // We can delete the managed profile to create a new one, so provisioning is allowed.
2603 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2604 DevicePolicyManager.CODE_OK);
2605 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2606 assertCheckProvisioningPreCondition(
2607 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2608 DpmMockContext.ANOTHER_PACKAGE_NAME,
2609 DevicePolicyManager.CODE_OK);
2610 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2611 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2612 }
2613
2614 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2615 throws Exception {
2616 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2617 mContext.packageName = admin1.getPackageName();
2618 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2619 when(mContext.userManager.hasUserRestriction(
2620 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2621 eq(UserHandle.SYSTEM)))
2622 .thenReturn(true);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002623 when(mContext.userManager.getUserRestrictionSource(
2624 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2625 eq(UserHandle.SYSTEM)))
2626 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002627
2628 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002629 assertCheckProvisioningPreCondition(
2630 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2631 DpmMockContext.ANOTHER_PACKAGE_NAME,
2632 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2633 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2634 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002635
2636 // But the device owner can still do it because it has set the restriction itself.
2637 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2638 DevicePolicyManager.CODE_OK);
2639 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002640 }
2641
2642 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002643 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2644 .thenReturn(true);
2645 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2646 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2647 .thenReturn(false);
2648 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2649
2650 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002651 }
Victor Chang3e794af2016-03-04 13:48:17 +00002652
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002653 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2654 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002655 mContext.packageName = admin1.getPackageName();
2656 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002657 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2658 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2659 false /* because canAddMoreManagedProfiles returns false */);
2660 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2661 true);
2662 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2663 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002664 }
2665
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002666 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2667 throws Exception {
2668 setup_splitUser_firstBoot_systemUser();
2669 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2670 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2671 DevicePolicyManager.CODE_OK);
2672 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002673 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002674 assertCheckProvisioningPreCondition(
2675 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2676 DevicePolicyManager.CODE_OK);
2677 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2678 DevicePolicyManager.CODE_SYSTEM_USER);
2679 }
2680
Esteban Talavera01576862016-12-15 11:16:44 +00002681 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002682 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2683 .thenReturn(true);
2684 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2685 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2686 .thenReturn(false);
2687 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2688
2689 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002690 }
Victor Chang3e794af2016-03-04 13:48:17 +00002691
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002692 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2693 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002694 mContext.packageName = admin1.getPackageName();
2695 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002696 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2697 true/* it's undefined behavior. Can be changed into false in the future */);
2698 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2699 false /* because canAddMoreManagedProfiles returns false */);
2700 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2701 true/* it's undefined behavior. Can be changed into false in the future */);
2702 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2703 false/* because calling uid is system user */);
2704 }
2705
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002706 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2707 throws Exception {
2708 setup_splitUser_afterDeviceSetup_systemUser();
2709 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2710 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2711 DevicePolicyManager.CODE_OK);
2712 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002713 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002714 assertCheckProvisioningPreCondition(
2715 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2716 DevicePolicyManager.CODE_OK);
2717 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2718 DevicePolicyManager.CODE_SYSTEM_USER);
2719 }
2720
Esteban Talavera01576862016-12-15 11:16:44 +00002721 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002722 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2723 .thenReturn(true);
2724 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2725 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2726 true)).thenReturn(true);
2727 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2728
2729 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002730 }
Victor Chang3e794af2016-03-04 13:48:17 +00002731
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002732 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2733 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002734 mContext.packageName = admin1.getPackageName();
2735 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002736 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2737 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2738 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2739 true);
2740 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002741 }
2742
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002743 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002744 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002745 setup_splitUser_firstBoot_primaryUser();
2746 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2747 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2748 DevicePolicyManager.CODE_OK);
2749 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2750 DevicePolicyManager.CODE_OK);
2751 assertCheckProvisioningPreCondition(
2752 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2753 DevicePolicyManager.CODE_OK);
2754 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2755 DevicePolicyManager.CODE_OK);
2756 }
2757
Esteban Talavera01576862016-12-15 11:16:44 +00002758 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002759 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2760 .thenReturn(true);
2761 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2762 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2763 true)).thenReturn(true);
2764 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2765
2766 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002767 }
Victor Chang3e794af2016-03-04 13:48:17 +00002768
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002769 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2770 throws Exception {
2771 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002772 mContext.packageName = admin1.getPackageName();
2773 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002774 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2775 true/* it's undefined behavior. Can be changed into false in the future */);
2776 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2777 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2778 true/* it's undefined behavior. Can be changed into false in the future */);
2779 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2780 false/* because user setup completed */);
2781 }
2782
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002783 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002784 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002785 setup_splitUser_afterDeviceSetup_primaryUser();
2786 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2787 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2788 DevicePolicyManager.CODE_OK);
2789 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2790 DevicePolicyManager.CODE_OK);
2791 assertCheckProvisioningPreCondition(
2792 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2793 DevicePolicyManager.CODE_OK);
2794 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2795 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2796 }
2797
Esteban Talavera01576862016-12-15 11:16:44 +00002798 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002799 setDeviceOwner();
2800
2801 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2802 .thenReturn(true);
2803 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2804 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2805 .thenReturn(false);
2806 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2807
2808 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002809 }
Victor Chang3e794af2016-03-04 13:48:17 +00002810
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002811 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2812 throws Exception {
2813 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002814 mContext.packageName = admin1.getPackageName();
2815 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002816 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2817 false /* can't provision managed profile on system user */);
2818 }
2819
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002820 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002821 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002822 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2823 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2824 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2825 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2826 }
2827
2828 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002829 setDeviceOwner();
2830
2831 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2832 .thenReturn(true);
2833 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2834 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2835 true)).thenReturn(true);
2836 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2837
2838 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002839 }
Victor Chang3e794af2016-03-04 13:48:17 +00002840
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002841 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2842 throws Exception {
2843 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002844 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2845 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002846 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2847 }
2848
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002849 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002850 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002851 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2852 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002853
2854 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002855 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2856 DevicePolicyManager.CODE_OK);
2857 }
2858
2859 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002860 setDeviceOwner();
2861
2862 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2863 .thenReturn(true);
2864 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002865 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002866 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2867 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002868 .thenReturn(true);
2869 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002870 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002871 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2872 true)).thenReturn(true);
2873 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2874
2875 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002876 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002877
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002878 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2879 throws Exception {
2880 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002881 mContext.packageName = admin1.getPackageName();
2882 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002883 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2884 }
2885
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002886 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2887 throws Exception {
2888 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2889 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2890 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2891 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2892 }
2893
2894 public void testCheckProvisioningPreCondition_permission() {
2895 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2896 try {
Esteban Talavera01576862016-12-15 11:16:44 +00002897 dpm.checkProvisioningPreCondition(
2898 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002899 fail("Didn't throw SecurityException");
2900 } catch (SecurityException expected) {
2901 }
2902 }
2903
Victor Chang3577ed22016-08-25 18:49:26 +01002904 public void testForceUpdateUserSetupComplete_permission() {
2905 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2906 try {
2907 dpm.forceUpdateUserSetupComplete();
2908 fail("Didn't throw SecurityException");
2909 } catch (SecurityException expected) {
2910 }
2911 }
2912
2913 public void testForceUpdateUserSetupComplete_systemUser() {
2914 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2915 // GIVEN calling from user 20
2916 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2917 try {
2918 dpm.forceUpdateUserSetupComplete();
2919 fail("Didn't throw SecurityException");
2920 } catch (SecurityException expected) {
2921 }
2922 }
2923
2924 public void testForceUpdateUserSetupComplete_userbuild() {
2925 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2926 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2927
2928 final int userId = UserHandle.USER_SYSTEM;
2929 // GIVEN userComplete is false in SettingsProvider
2930 setUserSetupCompleteForUser(false, userId);
2931
2932 // GIVEN userComplete is true in DPM
2933 DevicePolicyManagerService.DevicePolicyData userData =
2934 new DevicePolicyManagerService.DevicePolicyData(userId);
2935 userData.mUserSetupComplete = true;
2936 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2937
2938 // GIVEN it's user build
2939 mContext.buildMock.isDebuggable = false;
2940
2941 assertTrue(dpms.hasUserSetupCompleted());
2942
2943 dpm.forceUpdateUserSetupComplete();
2944
2945 // THEN the state in dpms is not changed
2946 assertTrue(dpms.hasUserSetupCompleted());
2947 }
2948
2949 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2950 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2951 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2952
2953 final int userId = UserHandle.USER_SYSTEM;
2954 // GIVEN userComplete is false in SettingsProvider
2955 setUserSetupCompleteForUser(false, userId);
2956
2957 // GIVEN userComplete is true in DPM
2958 DevicePolicyManagerService.DevicePolicyData userData =
2959 new DevicePolicyManagerService.DevicePolicyData(userId);
2960 userData.mUserSetupComplete = true;
2961 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2962
2963 // GIVEN it's userdebug build
2964 mContext.buildMock.isDebuggable = true;
2965
2966 assertTrue(dpms.hasUserSetupCompleted());
2967
2968 dpm.forceUpdateUserSetupComplete();
2969
2970 // THEN the state in dpms is not changed
2971 assertFalse(dpms.hasUserSetupCompleted());
2972 }
2973
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002974 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002975 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002976 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2977 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2978 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2979 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002980 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002981 }
2982
2983 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2984 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2985 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002986
2987 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2988 // feature is disabled because there are non-affiliated secondary users.
2989 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002990 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2991 .thenReturn(true);
2992
2993 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002994 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002995
2996 // Enabling logging should not change the timestamp.
2997 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00002998 verify(mContext.settings)
2999 .securityLogSetLoggingEnabledProperty(true);
3000 when(mContext.settings.securityLogGetLoggingEnabledProperty())
3001 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003002 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003003
3004 // Retrieving the logs should update the timestamp.
3005 final long beforeRetrieval = System.currentTimeMillis();
3006 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003007 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003008 final long afterRetrieval = System.currentTimeMillis();
3009 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3010 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3011
3012 // Retrieving the pre-boot logs should update the timestamp.
3013 Thread.sleep(2);
3014 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003015 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003016 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3017
3018 // Checking the timestamp again should not change it.
3019 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003020 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003021
3022 // Retrieving the logs again should update the timestamp.
3023 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003024 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003025 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3026
3027 // Disabling logging should not change the timestamp.
3028 Thread.sleep(2);
3029 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003030 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003031
3032 // Restarting the DPMS should not lose the timestamp.
3033 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003034 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003035
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003036 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3037 mContext.binder.callingUid = 1234567;
3038 mContext.callerPermissions.add(permission.MANAGE_USERS);
3039 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3040 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3041
3042 // System can retrieve the timestamp.
3043 mContext.binder.clearCallingIdentity();
3044 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3045
3046 // Removing the device owner should clear the timestamp.
3047 clearDeviceOwner();
3048 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003049 }
3050
3051 public void testGetLastBugReportRequestTime() throws Exception {
3052 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3053 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003054
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003055 mContext.packageName = admin1.getPackageName();
3056 mContext.applicationInfo = new ApplicationInfo();
3057 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3058 .thenReturn(Color.WHITE);
3059 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3060 anyObject())).thenReturn(Color.WHITE);
3061
Esteban Talaverad36dd152016-12-15 08:51:45 +00003062 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3063 // feature is disabled because there are non-affiliated secondary users.
3064 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3065
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003066 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003067 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003068
3069 // Requesting a bug report should update the timestamp.
3070 final long beforeRequest = System.currentTimeMillis();
3071 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003072 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003073 final long afterRequest = System.currentTimeMillis();
3074 assertTrue(bugReportRequestTime >= beforeRequest);
3075 assertTrue(bugReportRequestTime <= afterRequest);
3076
3077 // Checking the timestamp again should not change it.
3078 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003079 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003080
3081 // Restarting the DPMS should not lose the timestamp.
3082 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003083 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003084
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003085 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3086 mContext.binder.callingUid = 1234567;
3087 mContext.callerPermissions.add(permission.MANAGE_USERS);
3088 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3089 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3090
3091 // System can retrieve the timestamp.
3092 mContext.binder.clearCallingIdentity();
3093 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3094
3095 // Removing the device owner should clear the timestamp.
3096 clearDeviceOwner();
3097 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003098 }
3099
3100 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3101 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3102 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003103 mContext.packageName = admin1.getPackageName();
3104 mContext.applicationInfo = new ApplicationInfo();
3105 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3106 .thenReturn(Color.WHITE);
3107 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3108 anyObject())).thenReturn(Color.WHITE);
3109
3110 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3111 // feature is disabled because there are non-affiliated secondary users.
3112 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003113 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3114 .thenReturn(true);
3115
3116 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003117 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003118
3119 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3120 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003121 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003122
3123 // Enabling logging should not change the timestamp.
3124 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003125 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003126
3127 // Retrieving the logs should update the timestamp.
3128 final long beforeRetrieval = System.currentTimeMillis();
3129 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003130 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003131 final long afterRetrieval = System.currentTimeMillis();
3132 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3133 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3134
3135 // Checking the timestamp again should not change it.
3136 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003137 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003138
3139 // Retrieving the logs again should update the timestamp.
3140 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003141 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003142 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3143
3144 // Disabling logging should not change the timestamp.
3145 Thread.sleep(2);
3146 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003147 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003148
3149 // Restarting the DPMS should not lose the timestamp.
3150 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003151 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3152
3153 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3154 mContext.binder.callingUid = 1234567;
3155 mContext.callerPermissions.add(permission.MANAGE_USERS);
3156 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3157 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3158
3159 // System can retrieve the timestamp.
3160 mContext.binder.clearCallingIdentity();
3161 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3162
3163 // Removing the device owner should clear the timestamp.
3164 clearDeviceOwner();
3165 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003166 }
3167
Tony Mak2f26b792016-11-28 17:54:51 +00003168 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3169 // Setup device owner.
3170 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3171 setupDeviceOwner();
3172
3173 // Only device owner is setup, the result list should be empty.
3174 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3175 MoreAsserts.assertEmpty(targetUsers);
3176
3177 // Setup a managed profile managed by the same admin.
3178 final int MANAGED_PROFILE_USER_ID = 15;
3179 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3180 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3181
3182 // Add a secondary user, it should never talk with.
3183 final int ANOTHER_USER_ID = 36;
3184 mContext.addUser(ANOTHER_USER_ID, 0);
3185
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003186 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3187 // other.
3188 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3189 MoreAsserts.assertEmpty(targetUsers);
3190
3191 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3192 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3193 MoreAsserts.assertEmpty(targetUsers);
3194
3195 // Setting affiliation ids
3196 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3197 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3198 dpm.setAffiliationIds(admin1, userAffiliationIds);
3199
3200 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3201 dpm.setAffiliationIds(admin1, userAffiliationIds);
3202
Tony Mak2f26b792016-11-28 17:54:51 +00003203 // Calling from device owner admin, the result list should just contain the managed
3204 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003205 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003206 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3207 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3208
3209 // Calling from managed profile admin, the result list should just contain the system
3210 // user id.
3211 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3212 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3213 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003214
3215 // Changing affiliation ids in one
3216 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3217
3218 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3219 // to each other.
3220 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3221 MoreAsserts.assertEmpty(targetUsers);
3222
3223 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3224 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3225 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003226 }
3227
3228 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3229 // Setup a device owner.
3230 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3231 setupDeviceOwner();
3232
3233 // Set up a managed profile managed by different package.
3234 final int MANAGED_PROFILE_USER_ID = 15;
3235 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3236 final ComponentName adminDifferentPackage =
3237 new ComponentName("another.package", "whatever.class");
3238 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3239
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003240 // Setting affiliation ids
3241 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3242 dpm.setAffiliationIds(admin1, userAffiliationIds);
3243
3244 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3245 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3246
Tony Mak2f26b792016-11-28 17:54:51 +00003247 // Calling from device owner admin, we should get zero bind device admin target users as
3248 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003249 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003250 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3251 MoreAsserts.assertEmpty(targetUsers);
3252
3253 // Calling from managed profile admin, we should still get zero target users for the same
3254 // reason.
3255 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3256 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3257 MoreAsserts.assertEmpty(targetUsers);
3258 }
3259
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003260 public void testIsDeviceManaged() throws Exception {
3261 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3262 setupDeviceOwner();
3263
3264 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3265 // find out that the device has a device owner.
3266 assertTrue(dpm.isDeviceManaged());
3267 mContext.binder.callingUid = 1234567;
3268 mContext.callerPermissions.add(permission.MANAGE_USERS);
3269 assertTrue(dpm.isDeviceManaged());
3270 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3271 mContext.binder.clearCallingIdentity();
3272 assertTrue(dpm.isDeviceManaged());
3273
3274 clearDeviceOwner();
3275
3276 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3277 // not have a device owner.
3278 mContext.binder.callingUid = 1234567;
3279 mContext.callerPermissions.add(permission.MANAGE_USERS);
3280 assertFalse(dpm.isDeviceManaged());
3281 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3282 mContext.binder.clearCallingIdentity();
3283 assertFalse(dpm.isDeviceManaged());
3284 }
3285
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003286 public void testDeviceOwnerOrganizationName() throws Exception {
3287 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3288 setupDeviceOwner();
3289
3290 dpm.setOrganizationName(admin1, "organization");
3291
3292 // Device owner can retrieve organization managing the device.
3293 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3294
3295 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3296 mContext.binder.callingUid = 1234567;
3297 mContext.callerPermissions.add(permission.MANAGE_USERS);
3298 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3299 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3300
3301 // System can retrieve organization managing the device.
3302 mContext.binder.clearCallingIdentity();
3303 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3304
3305 // Removing the device owner clears the organization managing the device.
3306 clearDeviceOwner();
3307 assertNull(dpm.getDeviceOwnerOrganizationName());
3308 }
3309
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003310 public void testWipeDataManagedProfile() throws Exception {
3311 final int MANAGED_PROFILE_USER_ID = 15;
3312 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3313 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3314 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3315
3316 // Even if the caller is the managed profile, the current user is the user 0
3317 when(mContext.iactivityManager.getCurrentUser())
3318 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3319
3320 dpm.wipeData(0);
3321 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3322 MANAGED_PROFILE_USER_ID);
3323 }
3324
3325 public void testWipeDataManagedProfileDisallowed() throws Exception {
3326 final int MANAGED_PROFILE_USER_ID = 15;
3327 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3328 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3329
3330 // Even if the caller is the managed profile, the current user is the user 0
3331 when(mContext.iactivityManager.getCurrentUser())
3332 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3333
3334 when(mContext.userManager.getUserRestrictionSource(
3335 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3336 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3337 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3338 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3339 try {
3340 // The PO is not allowed to remove the profile if the user restriction was set on the
3341 // profile by the system
3342 dpm.wipeData(0);
3343 fail("SecurityException not thrown");
3344 } catch (SecurityException expected) {
3345 }
3346 }
3347
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003348 public void testWipeDataDeviceOwner() throws Exception {
3349 setDeviceOwner();
3350 when(mContext.userManager.getUserRestrictionSource(
3351 UserManager.DISALLOW_FACTORY_RESET,
3352 UserHandle.SYSTEM))
3353 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3354
3355 dpm.wipeData(0);
3356 verify(mContext.recoverySystem).rebootWipeUserData(
3357 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3358 }
3359
3360 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3361 setDeviceOwner();
3362 when(mContext.userManager.getUserRestrictionSource(
3363 UserManager.DISALLOW_FACTORY_RESET,
3364 UserHandle.SYSTEM))
3365 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3366 try {
3367 // The DO is not allowed to wipe the device if the user restriction was set
3368 // by the system
3369 dpm.wipeData(0);
3370 fail("SecurityException not thrown");
3371 } catch (SecurityException expected) {
3372 }
3373 }
3374
3375 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3376 final int MANAGED_PROFILE_USER_ID = 15;
3377 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3378 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3379
3380 // Even if the caller is the managed profile, the current user is the user 0
3381 when(mContext.iactivityManager.getCurrentUser())
3382 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3383
3384 when(mContext.userManager.getUserRestrictionSource(
3385 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3386 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3387 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3388
3389 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3390 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3391
3392 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3393 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3394 // Failed password attempts on the parent user are taken into account, as there isn't a
3395 // separate work challenge.
3396 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3397 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3398 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3399
3400 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3401 // both the user restriction and the policy were set by the PO.
3402 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3403 MANAGED_PROFILE_USER_ID);
3404 verifyZeroInteractions(mContext.recoverySystem);
3405 }
3406
3407 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3408 throws Exception {
3409 final int MANAGED_PROFILE_USER_ID = 15;
3410 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3411 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3412
3413 // Even if the caller is the managed profile, the current user is the user 0
3414 when(mContext.iactivityManager.getCurrentUser())
3415 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3416
3417 when(mContext.userManager.getUserRestrictionSource(
3418 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3419 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3420 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3421
3422 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3423 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3424
3425 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3426 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3427 // Failed password attempts on the parent user are taken into account, as there isn't a
3428 // separate work challenge.
3429 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3430 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3431 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3432
3433 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3434 // not wiped.
3435 verify(mContext.userManagerInternal, never())
3436 .removeUserEvenWhenDisallowed(anyInt());
3437 verifyZeroInteractions(mContext.recoverySystem);
3438 }
3439
3440 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3441 setDeviceOwner();
3442 when(mContext.userManager.getUserRestrictionSource(
3443 UserManager.DISALLOW_FACTORY_RESET,
3444 UserHandle.SYSTEM))
3445 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3446
3447 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3448
3449 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3450 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3451 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3452 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3453 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3454
3455 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3456 // user restriction and the policy were set by the DO.
3457 verify(mContext.recoverySystem).rebootWipeUserData(
3458 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3459 }
3460
3461 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3462 setDeviceOwner();
3463 when(mContext.userManager.getUserRestrictionSource(
3464 UserManager.DISALLOW_FACTORY_RESET,
3465 UserHandle.SYSTEM))
3466 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3467
3468 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3469
3470 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3471 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3472 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3473 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3474 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3475
3476 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
3477 verifyZeroInteractions(mContext.recoverySystem);
3478 verify(mContext.userManagerInternal, never())
3479 .removeUserEvenWhenDisallowed(anyInt());
3480 }
3481
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003482 public void testGetPermissionGrantState() throws Exception {
3483 final String permission = "some.permission";
3484 final String app1 = "com.example.app1";
3485 final String app2 = "com.example.app2";
3486
3487 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3488 .thenReturn(PackageManager.PERMISSION_GRANTED);
3489 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3490 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3491 when(mContext.packageManager.getPermissionFlags(permission, app1,
3492 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3493 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3494 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3495 .thenReturn(PackageManager.PERMISSION_DENIED);
3496 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3497 UserHandle.SYSTEM);
3498 when(mContext.packageManager.getPermissionFlags(permission, app2,
3499 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3500
3501 // System can retrieve permission grant state.
3502 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3503 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3504 dpm.getPermissionGrantState(null, app1, permission));
3505 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3506 dpm.getPermissionGrantState(null, app2, permission));
3507
3508 // A regular app cannot retrieve permission grant state.
3509 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
3510 try {
3511 dpm.getPermissionGrantState(null, app1, permission);
3512 fail("Didn't throw IllegalStateException");
3513 } catch (IllegalStateException expected) {
3514 }
3515
3516 // Profile owner can retrieve permission grant state.
3517 setAsProfileOwner(admin1);
3518 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3519 dpm.getPermissionGrantState(admin1, app1, permission));
3520 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3521 dpm.getPermissionGrantState(admin1, app2, permission));
3522 }
3523
Victor Chang3e794af2016-03-04 13:48:17 +00003524 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
3525 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
3526 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
3527 dpms.notifyChangeToContentObserver(
3528 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
3529 }
3530
3531 private void assertProvisioningAllowed(String action, boolean expected) {
3532 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
3533 dpm.isProvisioningAllowed(action));
3534 }
Tony Mak2f26b792016-11-28 17:54:51 +00003535
Nicolas Prevot45d29072017-01-18 16:11:19 +00003536 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
3537 int uid) {
3538 String previousPackageName = mContext.packageName;
3539 int previousUid = mMockContext.binder.callingUid;
3540
3541 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
3542 mContext.packageName = packageName;
3543 mMockContext.binder.callingUid = uid;
3544 assertProvisioningAllowed(action, expected);
3545
3546 // Set the previous package name / calling uid to go back to the initial state.
3547 mContext.packageName = previousPackageName;
3548 mMockContext.binder.callingUid = previousUid;
3549 }
3550
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003551 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00003552 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
3553 }
3554
3555 private void assertCheckProvisioningPreCondition(
3556 String action, String packageName, int provisioningCondition) {
3557 assertEquals("checkProvisioningPreCondition("
3558 + action + ", " + packageName + ") returning unexpected result",
3559 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003560 }
3561
Tony Mak2f26b792016-11-28 17:54:51 +00003562 /**
3563 * Setup a managed profile with the specified admin and its uid.
3564 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
3565 * @param adminUid uid of the admin package.
3566 * @param copyFromAdmin package information for {@code admin} will be built based on this
3567 * component's information.
3568 */
3569 private void addManagedProfile(
3570 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
3571 final int userId = UserHandle.getUserId(adminUid);
3572 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
3573 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3574 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
3575 dpm.setActiveAdmin(admin, false, userId);
3576 assertTrue(dpm.setProfileOwner(admin, null, userId));
3577 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3578 }
Victor Chang3e794af2016-03-04 13:48:17 +00003579}