blob: c35d11420fbcfc454a65d87887df3fac049b5c9a [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Makoto Onukif76b06a2015-09-22 15:03:44 -070018import android.Manifest.permission;
19import android.app.Activity;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070020import android.app.admin.DeviceAdminReceiver;
21import android.app.admin.DevicePolicyManager;
22import android.app.admin.DevicePolicyManagerInternal;
Makoto Onukif76b06a2015-09-22 15:03:44 -070023import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070024import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000025import android.content.Context;
26import android.content.Intent;
27import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000028import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070030import android.content.pm.PackageManager;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010031import android.content.res.Resources;
32import android.graphics.Color;
33import android.net.IIpConnectivityMetrics;
Tony Mak2f26b792016-11-28 17:54:51 +000034import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080035import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080036import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070037import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000038import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080039import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070040import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070041import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080042import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000043import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080044import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000045import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010046import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070047import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070048
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010049import com.android.internal.R;
Alan Treadwayafad8782016-01-19 15:15:08 +000050import com.android.server.LocalServices;
51import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000052import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000053
Makoto Onukib643fb02015-09-22 15:03:44 -070054import org.mockito.invocation.InvocationOnMock;
55import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070056
Makoto Onukic8a5a552015-11-19 14:29:12 -080057import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000058import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000059import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070060import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070062import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010063import java.util.Set;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070064
65import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070066import static org.mockito.Matchers.anyInt;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010067import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070068import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070069import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070070import static org.mockito.Matchers.isNull;
Makoto Onukib643fb02015-09-22 15:03:44 -070071import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070072import static org.mockito.Mockito.doReturn;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080073import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070074import static org.mockito.Mockito.times;
75import static org.mockito.Mockito.verify;
76import static org.mockito.Mockito.when;
77
78/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070079 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +000080 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070081 m FrameworksServicesTests &&
82 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000083 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070084 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080085 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070086
87 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +000088 *
89 * , or:
90 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070091 */
Benjamin Franz6d009032016-01-25 18:56:38 +000092@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070093public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000094 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
95 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
96 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
97
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098 private DpmMockContext mContext;
99 public DevicePolicyManager dpm;
100 public DevicePolicyManagerServiceTestable dpms;
101
102 @Override
103 protected void setUp() throws Exception {
104 super.setUp();
105
106 mContext = getContext();
107
108 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
109 .thenReturn(true);
110
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800111 // By default, pretend all users are running and unlocked.
112 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
113
Makoto Onukia52562c2015-10-01 16:12:31 -0700114 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700115
Makoto Onukid932f762015-09-29 16:53:38 -0700116 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
117 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
118 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800119 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700120
Makoto Onukib643fb02015-09-22 15:03:44 -0700121 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700122 }
123
Makoto Onukia52562c2015-10-01 16:12:31 -0700124 private void initializeDpms() {
125 // Need clearCallingIdentity() to pass permission checks.
126 final long ident = mContext.binder.clearCallingIdentity();
127 try {
128 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
129
130 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
131
132 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
133 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
134
135 dpm = new DevicePolicyManagerTestable(mContext, dpms);
136 } finally {
137 mContext.binder.restoreCallingIdentity(ident);
138 }
139 }
140
Makoto Onukib643fb02015-09-22 15:03:44 -0700141 private void setUpUserManager() {
142 // Emulate UserManager.set/getApplicationRestriction().
143 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
144
145 // UM.setApplicationRestrictions() will save to appRestrictions.
146 doAnswer(new Answer<Void>() {
147 @Override
148 public Void answer(InvocationOnMock invocation) throws Throwable {
149 String pkg = (String) invocation.getArguments()[0];
150 Bundle bundle = (Bundle) invocation.getArguments()[1];
151 UserHandle user = (UserHandle) invocation.getArguments()[2];
152
153 appRestrictions.put(Pair.create(pkg, user), bundle);
154
155 return null;
156 }
157 }).when(mContext.userManager).setApplicationRestrictions(
158 anyString(), any(Bundle.class), any(UserHandle.class));
159
160 // UM.getApplicationRestrictions() will read from appRestrictions.
161 doAnswer(new Answer<Bundle>() {
162 @Override
163 public Bundle answer(InvocationOnMock invocation) throws Throwable {
164 String pkg = (String) invocation.getArguments()[0];
165 UserHandle user = (UserHandle) invocation.getArguments()[1];
166
167 return appRestrictions.get(Pair.create(pkg, user));
168 }
169 }).when(mContext.userManager).getApplicationRestrictions(
170 anyString(), any(UserHandle.class));
171
Makoto Onukid932f762015-09-29 16:53:38 -0700172 // Add the first secondary user.
173 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700174 }
175
176 private void setAsProfileOwner(ComponentName admin) {
177 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
178 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
179
Makoto Onukia4f11972015-10-01 13:19:58 -0700180 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700181 dpm.setActiveAdmin(admin, /* replace =*/ false);
182
183 // Fire!
184 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
185
186 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700187 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700188 }
189
190 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700191 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
192 .thenReturn(false);
193
194 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
195 new DevicePolicyManagerServiceTestable(mContext, dataDir);
196
197 // If the device has no DPMS feature, it shouldn't register the local service.
198 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
199 }
200
201 /**
202 * Caller doesn't have proper permissions.
203 */
204 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700205 // 1. Failure cases.
206
207 // Caller doesn't have MANAGE_DEVICE_ADMINS.
208 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700209 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700210 fail("Didn't throw SecurityException");
211 } catch (SecurityException expected) {
212 }
213
214 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
215 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
216 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700217 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700218 fail("Didn't throw SecurityException");
219 } catch (SecurityException expected) {
220 }
221 }
222
Makoto Onukif76b06a2015-09-22 15:03:44 -0700223 /**
224 * Test for:
225 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800226 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700227 * {@link DevicePolicyManager#isAdminActive}
228 * {@link DevicePolicyManager#isAdminActiveAsUser}
229 * {@link DevicePolicyManager#getActiveAdmins}
230 * {@link DevicePolicyManager#getActiveAdminsAsUser}
231 */
232 public void testSetActiveAdmin() throws Exception {
233 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700234 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
235
Makoto Onukif76b06a2015-09-22 15:03:44 -0700236 // 2. Call the API.
237 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700238
239 // 3. Verify internal calls.
240
241 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700242 verify(mContext.spiedContext).sendBroadcastAsUser(
243 MockUtils.checkIntentAction(
244 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
245 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
246 verify(mContext.spiedContext).sendBroadcastAsUser(
247 MockUtils.checkIntentAction(
248 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700249 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
250
Makoto Onukif76b06a2015-09-22 15:03:44 -0700251 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
252 eq(admin1.getPackageName()),
253 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
254 eq(PackageManager.DONT_KILL_APP),
255 eq(DpmMockContext.CALLER_USER_HANDLE),
256 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700257
258 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700259
260 // Make sure it's active admin1.
261 assertTrue(dpm.isAdminActive(admin1));
262 assertFalse(dpm.isAdminActive(admin2));
263 assertFalse(dpm.isAdminActive(admin3));
264
265 // But not admin1 for a different user.
266
267 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
268 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
269 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
270
271 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
272 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
273
274 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
275
276 // Next, add one more admin.
277 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700278 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
279 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700280
281 dpm.setActiveAdmin(admin2, /* replace =*/ false);
282
283 // Now we have two admins.
284 assertTrue(dpm.isAdminActive(admin1));
285 assertTrue(dpm.isAdminActive(admin2));
286 assertFalse(dpm.isAdminActive(admin3));
287
288 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
289 // again. (times(1) because it was previously called for admin1)
290 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
291 eq(admin1.getPackageName()),
292 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
293 eq(PackageManager.DONT_KILL_APP),
294 eq(DpmMockContext.CALLER_USER_HANDLE),
295 anyString());
296
297 // 4. Add the same admin1 again without replace, which should throw.
298 try {
299 dpm.setActiveAdmin(admin1, /* replace =*/ false);
300 fail("Didn't throw");
301 } catch (IllegalArgumentException expected) {
302 }
303
304 // 5. Add the same admin1 again with replace, which should succeed.
305 dpm.setActiveAdmin(admin1, /* replace =*/ true);
306
307 // TODO make sure it's replaced.
308
309 // 6. Test getActiveAdmins()
310 List<ComponentName> admins = dpm.getActiveAdmins();
311 assertEquals(2, admins.size());
312 assertEquals(admin1, admins.get(0));
313 assertEquals(admin2, admins.get(1));
314
315 // Another user has no admins.
316 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
317
318 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
319 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
320
321 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
322 }
323
Makoto Onukid932f762015-09-29 16:53:38 -0700324 public void testSetActiveAdmin_multiUsers() throws Exception {
325
326 final int ANOTHER_USER_ID = 100;
327 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
328
329 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
330
331 // Set up pacakge manager for the other user.
332 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700333
334 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
335
336 dpm.setActiveAdmin(admin1, /* replace =*/ false);
337
338 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
339 dpm.setActiveAdmin(admin2, /* replace =*/ false);
340
341
342 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
343 assertTrue(dpm.isAdminActive(admin1));
344 assertFalse(dpm.isAdminActive(admin2));
345
346 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
347 assertFalse(dpm.isAdminActive(admin1));
348 assertTrue(dpm.isAdminActive(admin2));
349 }
350
Makoto Onukif76b06a2015-09-22 15:03:44 -0700351 /**
352 * Test for:
353 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800354 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700355 */
356 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
357 // 1. Make sure the caller has proper permissions.
358 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
359
360 dpm.setActiveAdmin(admin1, /* replace =*/ false);
361 assertTrue(dpm.isAdminActive(admin1));
362
363 // Add the same admin1 again without replace, which should throw.
364 try {
365 dpm.setActiveAdmin(admin1, /* replace =*/ false);
366 fail("Didn't throw");
367 } catch (IllegalArgumentException expected) {
368 }
369 }
370
371 /**
372 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800373 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
374 * BIND_DEVICE_ADMIN.
375 */
376 public void testSetActiveAdmin_permissionCheck() throws Exception {
377 // 1. Make sure the caller has proper permissions.
378 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
379
380 try {
381 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
382 fail();
383 } catch (IllegalArgumentException expected) {
384 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
385 }
386 assertFalse(dpm.isAdminActive(adminNoPerm));
387
388 // Change the target API level to MNC. Now it can be set as DA.
389 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
390 VERSION_CODES.M);
391 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
392 assertTrue(dpm.isAdminActive(adminNoPerm));
393
394 // TODO Test the "load from the file" case where DA will still be loaded even without
395 // BIND_DEVICE_ADMIN and target API is N.
396 }
397
398 /**
399 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700400 * {@link DevicePolicyManager#removeActiveAdmin}
401 */
402 public void testRemoveActiveAdmin_SecurityException() {
403 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
404
405 // Add admin.
406
407 dpm.setActiveAdmin(admin1, /* replace =*/ false);
408
409 assertTrue(dpm.isAdminActive(admin1));
410
411 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
412
413 // Directly call the DPMS method with a different userid, which should fail.
414 try {
415 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
416 fail("Didn't throw SecurityException");
417 } catch (SecurityException expected) {
418 }
419
420 // Try to remove active admin with a different caller userid should fail too, without
421 // having MANAGE_DEVICE_ADMINS.
422 mContext.callerPermissions.clear();
423
Makoto Onukid932f762015-09-29 16:53:38 -0700424 // Change the caller, and call into DPMS directly with a different user-id.
425
Makoto Onukif76b06a2015-09-22 15:03:44 -0700426 mContext.binder.callingUid = 1234567;
427 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700428 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700429 fail("Didn't throw SecurityException");
430 } catch (SecurityException expected) {
431 }
432 }
433
434 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800435 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
436 * (because we can't send the remove broadcast).
437 */
438 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
439 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
440
441 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
442
443 // Add admin.
444
445 dpm.setActiveAdmin(admin1, /* replace =*/ false);
446
447 assertTrue(dpm.isAdminActive(admin1));
448
449 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
450
451 // 1. User not unlocked.
452 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
453 .thenReturn(false);
454 try {
455 dpm.removeActiveAdmin(admin1);
456 fail("Didn't throw IllegalStateException");
457 } catch (IllegalStateException expected) {
458 MoreAsserts.assertContainsRegex(
459 "User must be running and unlocked", expected.getMessage());
460 }
461
462 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
463
464 // 2. User unlocked.
465 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
466 .thenReturn(true);
467
468 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700469 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800470 }
471
472 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700473 * Test for:
474 * {@link DevicePolicyManager#removeActiveAdmin}
475 */
Makoto Onukid932f762015-09-29 16:53:38 -0700476 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700477 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
478
479 // Add admin1.
480
481 dpm.setActiveAdmin(admin1, /* replace =*/ false);
482
483 assertTrue(dpm.isAdminActive(admin1));
484 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
485
486 // Different user, but should work, because caller has proper permissions.
487 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700488
489 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700490 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700491
492 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700493 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700494
495 // TODO DO Still can't be removed in this case.
496 }
497
498 /**
499 * Test for:
500 * {@link DevicePolicyManager#removeActiveAdmin}
501 */
502 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
503 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
504 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
505
506 // Add admin1.
507
508 dpm.setActiveAdmin(admin1, /* replace =*/ false);
509
510 assertTrue(dpm.isAdminActive(admin1));
511 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
512
513 // Broadcast from saveSettingsLocked().
514 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
515 MockUtils.checkIntentAction(
516 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
517 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
518
519 // Remove. No permissions, but same user, so it'll work.
520 mContext.callerPermissions.clear();
521 dpm.removeActiveAdmin(admin1);
522
Makoto Onukif76b06a2015-09-22 15:03:44 -0700523 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
524 MockUtils.checkIntentAction(
525 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
526 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
527 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700528 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700529 eq(dpms.mHandler),
530 eq(Activity.RESULT_OK),
531 isNull(String.class),
532 isNull(Bundle.class));
533
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700534 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700535
536 // Again broadcast from saveSettingsLocked().
537 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
538 MockUtils.checkIntentAction(
539 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
540 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
541
542 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700543 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700544
545 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000546 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700547 */
548 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000549 setDeviceOwner();
550
551 // Try to set a profile owner on the same user, which should fail.
552 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
553 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
554 try {
555 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
556 fail("IllegalStateException not thrown");
557 } catch (IllegalStateException expected) {
558 assertTrue("Message was: " + expected.getMessage(),
559 expected.getMessage().contains("already has a device owner"));
560 }
561
562 // DO admin can't be deactivated.
563 dpm.removeActiveAdmin(admin1);
564 assertTrue(dpm.isAdminActive(admin1));
565
566 // TODO Test getDeviceOwnerName() too. To do so, we need to change
567 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
568 }
569
570 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700571 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800572 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700573 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
574 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
575
Makoto Onukid932f762015-09-29 16:53:38 -0700576 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700577 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
578
Makoto Onukid932f762015-09-29 16:53:38 -0700579 // Make sure admin1 is installed on system user.
580 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700581
Makoto Onukic8a5a552015-11-19 14:29:12 -0800582 // Check various get APIs.
583 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
584
Makoto Onukib643fb02015-09-22 15:03:44 -0700585 // DO needs to be an DA.
586 dpm.setActiveAdmin(admin1, /* replace =*/ false);
587
588 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700589 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700590
Makoto Onukic8a5a552015-11-19 14:29:12 -0800591 // getDeviceOwnerComponent should return the admin1 component.
592 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
593 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
594
595 // Check various get APIs.
596 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
597
598 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
599 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
600 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
601 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
602
603 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
604
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000605 // Verify internal calls.
606 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
607 eq(admin1.getPackageName()));
608
Makoto Onukib643fb02015-09-22 15:03:44 -0700609 // TODO We should check if the caller has called clearCallerIdentity().
610 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
611 eq(UserHandle.USER_SYSTEM), eq(false));
612
613 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
614 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
615 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
616
Makoto Onukic8a5a552015-11-19 14:29:12 -0800617 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700618 }
619
Makoto Onukic8a5a552015-11-19 14:29:12 -0800620 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
621 final int origCallingUser = mContext.binder.callingUid;
622 final List origPermissions = new ArrayList(mContext.callerPermissions);
623 mContext.callerPermissions.clear();
624
625 mContext.callerPermissions.add(permission.MANAGE_USERS);
626
627 mContext.binder.callingUid = Process.SYSTEM_UID;
628
629 // TODO Test getDeviceOwnerName() too. To do so, we need to change
630 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
631 if (hasDeviceOwner) {
632 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
633 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
634 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
635
636 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
637 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
638 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
639 } else {
640 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
641 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
642 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
643
644 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
645 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
646 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
647 }
648
649 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
650 if (hasDeviceOwner) {
651 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
652 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
653 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
654
655 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
656 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
657 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
658 } else {
659 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
660 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
661 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
662
663 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
664 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
665 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
666 }
667
668 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
669 // Still with MANAGE_USERS.
670 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
671 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
672 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
673
674 if (hasDeviceOwner) {
675 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
676 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
677 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
678 } else {
679 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
680 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
681 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
682 }
683
684 mContext.binder.callingUid = Process.SYSTEM_UID;
685 mContext.callerPermissions.remove(permission.MANAGE_USERS);
686 // System can still call "OnAnyUser" without MANAGE_USERS.
687 if (hasDeviceOwner) {
688 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
689 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
690 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
691
692 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
693 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
694 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
695 } else {
696 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
697 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
698 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
699
700 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
701 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
702 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
703 }
704
705 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
706 // Still no MANAGE_USERS.
707 if (hasDeviceOwner) {
708 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
709 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
710 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
711 } else {
712 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
713 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
714 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
715 }
716
717 try {
718 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
719 fail();
720 } catch (SecurityException expected) {
721 }
722 try {
723 dpm.getDeviceOwnerComponentOnAnyUser();
724 fail();
725 } catch (SecurityException expected) {
726 }
727 try {
728 dpm.getDeviceOwnerUserId();
729 fail();
730 } catch (SecurityException expected) {
731 }
732 try {
733 dpm.getDeviceOwnerNameOnAnyUser();
734 fail();
735 } catch (SecurityException expected) {
736 }
737
738 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
739 // Still no MANAGE_USERS.
740 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
741 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
742 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
743
744 try {
745 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
746 fail();
747 } catch (SecurityException expected) {
748 }
749 try {
750 dpm.getDeviceOwnerComponentOnAnyUser();
751 fail();
752 } catch (SecurityException expected) {
753 }
754 try {
755 dpm.getDeviceOwnerUserId();
756 fail();
757 } catch (SecurityException expected) {
758 }
759 try {
760 dpm.getDeviceOwnerNameOnAnyUser();
761 fail();
762 } catch (SecurityException expected) {
763 }
764
765 // Restore.
766 mContext.binder.callingUid = origCallingUser;
767 mContext.callerPermissions.addAll(origPermissions);
768 }
769
770
Makoto Onukib643fb02015-09-22 15:03:44 -0700771 /**
772 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
773 */
774 public void testSetDeviceOwner_noSuchPackage() {
775 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800776 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700777 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
778 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
779
780 // Call from a process on the system user.
781 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
782
Makoto Onukib643fb02015-09-22 15:03:44 -0700783 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700784 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700785 fail("Didn't throw IllegalArgumentException");
786 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700787 assertTrue("Message was: " + expected.getMessage(),
788 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700789 }
790 }
791
792 public void testSetDeviceOwner_failures() throws Exception {
793 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
794 }
795
Makoto Onukia52562c2015-10-01 16:12:31 -0700796 public void testClearDeviceOwner() throws Exception {
797 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800798 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700799 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
800 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
801
802 // Set admin1 as a DA to the secondary user.
803 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
804
805 dpm.setActiveAdmin(admin1, /* replace =*/ false);
806
807 // Set admin 1 as the DO to the system user.
808
809 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
810 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
811 dpm.setActiveAdmin(admin1, /* replace =*/ false);
812 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
813
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000814 // Verify internal calls.
815 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
816 eq(admin1.getPackageName()));
817
Makoto Onukic8a5a552015-11-19 14:29:12 -0800818 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700819
Makoto Onuki90b89652016-01-28 14:44:18 -0800820 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
821
822 assertTrue(dpm.isAdminActive(admin1));
823 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
824
Makoto Onukia52562c2015-10-01 16:12:31 -0700825 // Set up other mocks.
826 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
827
828 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700829 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700830 eq(admin1.getPackageName()),
831 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800832
833 // But first pretend the user is locked. Then it should fail.
834 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
835 try {
836 dpm.clearDeviceOwnerApp(admin1.getPackageName());
837 fail("Didn't throw IllegalStateException");
838 } catch (IllegalStateException expected) {
839 MoreAsserts.assertContainsRegex(
840 "User must be running and unlocked", expected.getMessage());
841 }
842
843 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800844 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700845 dpm.clearDeviceOwnerApp(admin1.getPackageName());
846
847 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800848 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700849
Makoto Onuki90b89652016-01-28 14:44:18 -0800850 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
851 eq(UserHandle.USER_SYSTEM),
852 MockUtils.checkUserRestrictions(),
853 MockUtils.checkUserRestrictions()
854 );
855
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700856 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100857
858 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
859 // and once for clearing it.
860 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
861 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
862 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700863 // TODO Check other calls.
864 }
865
866 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
867 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800868 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700869 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
870 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
871
872 // Set admin1 as a DA to the secondary user.
873 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
874
875 dpm.setActiveAdmin(admin1, /* replace =*/ false);
876
877 // Set admin 1 as the DO to the system user.
878
879 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
880 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
881 dpm.setActiveAdmin(admin1, /* replace =*/ false);
882 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
883
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000884 // Verify internal calls.
885 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
886 eq(admin1.getPackageName()));
887
Makoto Onukic8a5a552015-11-19 14:29:12 -0800888 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700889
890 // Now call clear from the secondary user, which should throw.
891 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
892
893 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700894 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700895 eq(admin1.getPackageName()),
896 anyInt());
897 try {
898 dpm.clearDeviceOwnerApp(admin1.getPackageName());
899 fail("Didn't throw");
900 } catch (SecurityException e) {
901 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
902 }
903
Makoto Onukic8a5a552015-11-19 14:29:12 -0800904 // DO shouldn't be removed.
905 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700906 }
907
Makoto Onukib643fb02015-09-22 15:03:44 -0700908 public void testSetProfileOwner() throws Exception {
909 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700910
Makoto Onuki90b89652016-01-28 14:44:18 -0800911 // PO admin can't be deactivated.
912 dpm.removeActiveAdmin(admin1);
913 assertTrue(dpm.isAdminActive(admin1));
914
Makoto Onuki803d6752015-10-30 12:58:39 -0700915 // Try setting DO on the same user, which should fail.
916 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
917 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
918 try {
919 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
920 fail("IllegalStateException not thrown");
921 } catch (IllegalStateException expected) {
922 assertTrue("Message was: " + expected.getMessage(),
923 expected.getMessage().contains("already has a profile owner"));
924 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700925 }
926
Makoto Onuki90b89652016-01-28 14:44:18 -0800927 public void testClearProfileOwner() throws Exception {
928 setAsProfileOwner(admin1);
929
930 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
931
932 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
933 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
934
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800935 // First try when the user is locked, which should fail.
936 when(mContext.userManager.isUserUnlocked(anyInt()))
937 .thenReturn(false);
938 try {
939 dpm.clearProfileOwner(admin1);
940 fail("Didn't throw IllegalStateException");
941 } catch (IllegalStateException expected) {
942 MoreAsserts.assertContainsRegex(
943 "User must be running and unlocked", expected.getMessage());
944 }
945 // Clear, really.
946 when(mContext.userManager.isUserUnlocked(anyInt()))
947 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800948 dpm.clearProfileOwner(admin1);
949
950 // Check
951 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700952 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -0800953 }
954
Makoto Onukib643fb02015-09-22 15:03:44 -0700955 public void testSetProfileOwner_failures() throws Exception {
956 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
957 }
958
Makoto Onukia52562c2015-10-01 16:12:31 -0700959 public void testGetDeviceOwnerAdminLocked() throws Exception {
960 checkDeviceOwnerWithMultipleDeviceAdmins();
961 }
962
963 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
964 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
965 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
966 // make sure it gets the right component from the right user.
967
968 final int ANOTHER_USER_ID = 100;
969 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
970
971 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
972
973 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800974 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700975 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
976 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
977
978 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
979
Victor Change29cd472016-03-02 20:57:42 +0000980 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
981
Makoto Onukia52562c2015-10-01 16:12:31 -0700982 // Make sure the admin packge is installed to each user.
983 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
984 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
985
986 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
987 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
988
989 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
990
991
992 // Set active admins to the users.
993 dpm.setActiveAdmin(admin1, /* replace =*/ false);
994 dpm.setActiveAdmin(admin3, /* replace =*/ false);
995
996 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
997 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
998
999 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1000
1001 // Set DO on the first non-system user.
1002 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1003 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1004
Makoto Onukic8a5a552015-11-19 14:29:12 -08001005 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001006
1007 // Then check getDeviceOwnerAdminLocked().
1008 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1009 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1010 }
1011
1012 /**
1013 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001014 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1015 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001016 *
1017 * We didn't use to persist the DO component class name, but now we do, and the above method
1018 * finds the right component from a package name upon migration.
1019 */
1020 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001021 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001022 checkDeviceOwnerWithMultipleDeviceAdmins();
1023
1024 // Overwrite the device owner setting and clears the clas name.
1025 dpms.mOwners.setDeviceOwner(
1026 new ComponentName(admin2.getPackageName(), ""),
1027 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1028 dpms.mOwners.writeDeviceOwner();
1029
1030 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001031 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001032
1033 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001034 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1035 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001036 initializeDpms();
1037
1038 // Now the DO component name is a full name.
1039 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1040 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001041 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001042 }
1043
Makoto Onukib643fb02015-09-22 15:03:44 -07001044 public void testSetGetApplicationRestriction() {
1045 setAsProfileOwner(admin1);
1046
1047 {
1048 Bundle rest = new Bundle();
1049 rest.putString("KEY_STRING", "Foo1");
1050 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1051 }
1052
1053 {
1054 Bundle rest = new Bundle();
1055 rest.putString("KEY_STRING", "Foo2");
1056 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1057 }
1058
1059 {
1060 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1061 assertNotNull(returned);
1062 assertEquals(returned.size(), 1);
1063 assertEquals(returned.get("KEY_STRING"), "Foo1");
1064 }
1065
1066 {
1067 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1068 assertNotNull(returned);
1069 assertEquals(returned.size(), 1);
1070 assertEquals(returned.get("KEY_STRING"), "Foo2");
1071 }
1072
1073 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1074 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1075 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001076
Esteban Talaverabf60f722015-12-10 16:26:44 +00001077 public void testApplicationRestrictionsManagingApp() throws Exception {
1078 setAsProfileOwner(admin1);
1079
Rubin Xued1928a2016-02-11 17:23:06 +00001080 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001081 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1082 final int appRestrictionsManagerAppId = 20987;
1083 final int appRestrictionsManagerUid = UserHandle.getUid(
1084 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001085 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001086 eq(appRestrictionsManagerPackage),
1087 eq(DpmMockContext.CALLER_USER_HANDLE));
1088 mContext.binder.callingUid = appRestrictionsManagerUid;
1089
Rubin Xued1928a2016-02-11 17:23:06 +00001090 final PackageInfo pi = new PackageInfo();
1091 pi.applicationInfo = new ApplicationInfo();
1092 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1093 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1094 eq(appRestrictionsManagerPackage),
1095 anyInt(),
1096 eq(DpmMockContext.CALLER_USER_HANDLE));
1097
Esteban Talaverabf60f722015-12-10 16:26:44 +00001098 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1099 // delegated that permission yet.
1100 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1101 Bundle rest = new Bundle();
1102 rest.putString("KEY_STRING", "Foo1");
1103 try {
1104 dpm.setApplicationRestrictions(null, "pkg1", rest);
1105 fail("Didn't throw expected SecurityException");
1106 } catch (SecurityException expected) {
1107 MoreAsserts.assertContainsRegex(
1108 "caller cannot manage application restrictions", expected.getMessage());
1109 }
1110 try {
1111 dpm.getApplicationRestrictions(null, "pkg1");
1112 fail("Didn't throw expected SecurityException");
1113 } catch (SecurityException expected) {
1114 MoreAsserts.assertContainsRegex(
1115 "caller cannot manage application restrictions", expected.getMessage());
1116 }
1117
1118 // Check via the profile owner that no restrictions were set.
1119 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1120 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1121
Rubin Xued1928a2016-02-11 17:23:06 +00001122 // Check the API does not allow setting a non-existent package
1123 try {
1124 dpm.setApplicationRestrictionsManagingPackage(admin1,
1125 nonExistAppRestrictionsManagerPackage);
1126 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001127 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001128 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001129 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001130 }
1131
Esteban Talaverabf60f722015-12-10 16:26:44 +00001132 // Let appRestrictionsManagerPackage manage app restrictions
1133 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1134 assertEquals(appRestrictionsManagerPackage,
1135 dpm.getApplicationRestrictionsManagingPackage(admin1));
1136
1137 // Now that package should be able to set and retrieve app restrictions.
1138 mContext.binder.callingUid = appRestrictionsManagerUid;
1139 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1140 dpm.setApplicationRestrictions(null, "pkg1", rest);
1141 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1142 assertEquals(1, returned.size(), 1);
1143 assertEquals("Foo1", returned.get("KEY_STRING"));
1144
1145 // The same app running on a separate user shouldn't be able to manage app restrictions.
1146 mContext.binder.callingUid = UserHandle.getUid(
1147 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1148 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1149 try {
1150 dpm.setApplicationRestrictions(null, "pkg1", rest);
1151 fail("Didn't throw expected SecurityException");
1152 } catch (SecurityException expected) {
1153 MoreAsserts.assertContainsRegex(
1154 "caller cannot manage application restrictions", expected.getMessage());
1155 }
1156
1157 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1158 // too.
1159 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1160 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1161 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1162 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1163
1164 // Removing the ability for the package to manage app restrictions.
1165 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1166 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1167 mContext.binder.callingUid = appRestrictionsManagerUid;
1168 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1169 try {
1170 dpm.setApplicationRestrictions(null, "pkg1", null);
1171 fail("Didn't throw expected SecurityException");
1172 } catch (SecurityException expected) {
1173 MoreAsserts.assertContainsRegex(
1174 "caller cannot manage application restrictions", expected.getMessage());
1175 }
1176 }
1177
Makoto Onukia4f11972015-10-01 13:19:58 -07001178 public void testSetUserRestriction_asDo() throws Exception {
1179 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001180 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001181 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1182 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1183
1184 // First, set DO.
1185
1186 // Call from a process on the system user.
1187 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1188
1189 // Make sure admin1 is installed on system user.
1190 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001191
1192 // Call.
1193 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001194 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001195 UserHandle.USER_SYSTEM));
1196
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001197 // Check that the user restrictions that are enabled by default are set. Then unset them.
1198 String[] defaultRestrictions = UserRestrictionsUtils
1199 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1200 DpmTestUtils.assertRestrictions(
1201 DpmTestUtils.newRestrictions(defaultRestrictions),
1202 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1203 );
1204 DpmTestUtils.assertRestrictions(
1205 DpmTestUtils.newRestrictions(defaultRestrictions),
1206 dpm.getUserRestrictions(admin1)
1207 );
1208
1209 for (String restriction : defaultRestrictions) {
1210 dpm.clearUserRestriction(admin1, restriction);
1211 }
1212
Makoto Onuki068c54a2015-10-13 14:34:03 -07001213 DpmTestUtils.assertRestrictions(
1214 DpmTestUtils.newRestrictions(),
1215 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1216 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001217 DpmTestUtils.assertRestrictions(
1218 DpmTestUtils.newRestrictions(),
1219 dpm.getUserRestrictions(admin1)
1220 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001221
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001222 reset(mContext.userManagerInternal);
1223
1224 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1225 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1226 eq(UserHandle.USER_SYSTEM),
1227 MockUtils.checkUserRestrictions(),
1228 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001229 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001230 reset(mContext.userManagerInternal);
1231
Makoto Onukia4f11972015-10-01 13:19:58 -07001232 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001233 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1234 eq(UserHandle.USER_SYSTEM),
1235 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1236 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1237 );
1238 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001239
Makoto Onuki068c54a2015-10-13 14:34:03 -07001240 DpmTestUtils.assertRestrictions(
1241 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001242 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001243 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1244 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001245 DpmTestUtils.assertRestrictions(
1246 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001247 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001248 dpm.getUserRestrictions(admin1)
1249 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001250
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001251 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1252 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1253 eq(UserHandle.USER_SYSTEM),
1254 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1255 MockUtils.checkUserRestrictions()
1256 );
1257 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001258
Makoto Onuki068c54a2015-10-13 14:34:03 -07001259 DpmTestUtils.assertRestrictions(
1260 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1261 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1262 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001263 DpmTestUtils.assertRestrictions(
1264 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1265 dpm.getUserRestrictions(admin1)
1266 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001267
1268 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001269 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1270 eq(UserHandle.USER_SYSTEM),
1271 MockUtils.checkUserRestrictions(),
1272 MockUtils.checkUserRestrictions()
1273 );
1274 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001275
Makoto Onuki068c54a2015-10-13 14:34:03 -07001276 DpmTestUtils.assertRestrictions(
1277 DpmTestUtils.newRestrictions(),
1278 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1279 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001280 DpmTestUtils.assertRestrictions(
1281 DpmTestUtils.newRestrictions(),
1282 dpm.getUserRestrictions(admin1)
1283 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001284
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001285 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1286 // DO sets them, the scope is global.
1287 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1288 reset(mContext.userManagerInternal);
1289 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1290 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1291 eq(UserHandle.USER_SYSTEM),
1292 MockUtils.checkUserRestrictions(),
1293 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1294 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1295 );
1296 reset(mContext.userManagerInternal);
1297
1298 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1299 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1300
1301
1302 // More tests.
1303 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1304 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1305 eq(UserHandle.USER_SYSTEM),
1306 MockUtils.checkUserRestrictions(),
1307 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1308 );
1309 reset(mContext.userManagerInternal);
1310
1311 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1312 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1313 eq(UserHandle.USER_SYSTEM),
1314 MockUtils.checkUserRestrictions(),
1315 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1316 UserManager.DISALLOW_ADD_USER)
1317 );
1318 reset(mContext.userManagerInternal);
1319
1320 dpm.setCameraDisabled(admin1, true);
1321 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1322 eq(UserHandle.USER_SYSTEM),
1323 // DISALLOW_CAMERA will be applied to both local and global.
1324 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1325 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1326 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1327 );
1328 reset(mContext.userManagerInternal);
1329
1330 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1331 // locally.
1332 dpm.setCameraDisabled(admin1, false);
1333 reset(mContext.userManagerInternal);
1334
1335 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1336 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1337 dpm.setCameraDisabled(admin2, true);
1338
1339 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1340 eq(UserHandle.USER_SYSTEM),
1341 // DISALLOW_CAMERA will be applied to both local and global.
1342 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1343 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1344 UserManager.DISALLOW_ADD_USER)
1345 );
1346 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001347 // TODO Make sure restrictions are written to the file.
1348 }
1349
1350 public void testSetUserRestriction_asPo() {
1351 setAsProfileOwner(admin1);
1352
Makoto Onuki068c54a2015-10-13 14:34:03 -07001353 DpmTestUtils.assertRestrictions(
1354 DpmTestUtils.newRestrictions(),
1355 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1356 .ensureUserRestrictions()
1357 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001358
1359 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001360 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1361 eq(DpmMockContext.CALLER_USER_HANDLE),
1362 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1363 isNull(Bundle.class)
1364 );
1365 reset(mContext.userManagerInternal);
1366
Makoto Onukia4f11972015-10-01 13:19:58 -07001367 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001368 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1369 eq(DpmMockContext.CALLER_USER_HANDLE),
1370 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1371 UserManager.DISALLOW_OUTGOING_CALLS),
1372 isNull(Bundle.class)
1373 );
1374 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001375
Makoto Onuki068c54a2015-10-13 14:34:03 -07001376 DpmTestUtils.assertRestrictions(
1377 DpmTestUtils.newRestrictions(
1378 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1379 UserManager.DISALLOW_OUTGOING_CALLS
1380 ),
1381 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1382 .ensureUserRestrictions()
1383 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001384 DpmTestUtils.assertRestrictions(
1385 DpmTestUtils.newRestrictions(
1386 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1387 UserManager.DISALLOW_OUTGOING_CALLS
1388 ),
1389 dpm.getUserRestrictions(admin1)
1390 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001391
1392 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001393 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1394 eq(DpmMockContext.CALLER_USER_HANDLE),
1395 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1396 isNull(Bundle.class)
1397 );
1398 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001399
1400 DpmTestUtils.assertRestrictions(
1401 DpmTestUtils.newRestrictions(
1402 UserManager.DISALLOW_OUTGOING_CALLS
1403 ),
1404 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1405 .ensureUserRestrictions()
1406 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001407 DpmTestUtils.assertRestrictions(
1408 DpmTestUtils.newRestrictions(
1409 UserManager.DISALLOW_OUTGOING_CALLS
1410 ),
1411 dpm.getUserRestrictions(admin1)
1412 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001413
1414 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001415 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1416 eq(DpmMockContext.CALLER_USER_HANDLE),
1417 MockUtils.checkUserRestrictions(),
1418 isNull(Bundle.class)
1419 );
1420 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001421
Makoto Onuki068c54a2015-10-13 14:34:03 -07001422 DpmTestUtils.assertRestrictions(
1423 DpmTestUtils.newRestrictions(),
1424 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1425 .ensureUserRestrictions()
1426 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001427 DpmTestUtils.assertRestrictions(
1428 DpmTestUtils.newRestrictions(),
1429 dpm.getUserRestrictions(admin1)
1430 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001431
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001432 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1433 // though when DO sets them they'll be applied globally.
1434 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1435 reset(mContext.userManagerInternal);
1436 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1437 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1438 eq(DpmMockContext.CALLER_USER_HANDLE),
1439 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1440 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1441 isNull(Bundle.class)
1442 );
1443 reset(mContext.userManagerInternal);
1444
1445 dpm.setCameraDisabled(admin1, true);
1446 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1447 eq(DpmMockContext.CALLER_USER_HANDLE),
1448 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1449 UserManager.DISALLOW_ADJUST_VOLUME,
1450 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1451 isNull(Bundle.class)
1452 );
1453 reset(mContext.userManagerInternal);
1454
Makoto Onukia4f11972015-10-01 13:19:58 -07001455 // TODO Make sure restrictions are written to the file.
1456 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001457
1458 public void testGetMacAddress() throws Exception {
1459 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1460 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1461 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1462
1463 // In this test, change the caller user to "system".
1464 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1465
1466 // Make sure admin1 is installed on system user.
1467 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1468
1469 // Test 1. Caller doesn't have DO or DA.
1470 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001471 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001472 fail();
1473 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001474 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001475 }
1476
1477 // DO needs to be an DA.
1478 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1479 assertTrue(dpm.isAdminActive(admin1));
1480
1481 // Test 2. Caller has DA, but not DO.
1482 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001483 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001484 fail();
1485 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001486 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001487 }
1488
1489 // Test 3. Caller has PO, but not DO.
1490 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1491 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001492 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001493 fail();
1494 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001495 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001496 }
1497
1498 // Remove PO.
1499 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001500 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001501 // Test 4, Caller is DO now.
1502 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1503
1504 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001505 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001506
1507 // 4-2. Returns WifiInfo, but with the default MAC.
1508 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001509 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001510
1511 // 4-3. With a real MAC address.
1512 final WifiInfo wi = new WifiInfo();
1513 wi.setMacAddress("11:22:33:44:55:66");
1514 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001515 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001516 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001517
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001518 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001519 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1520 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1521
1522 // In this test, change the caller user to "system".
1523 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1524
1525 // Make sure admin1 is installed on system user.
1526 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1527
1528 // Set admin1 as DA.
1529 dpm.setActiveAdmin(admin1, false);
1530 assertTrue(dpm.isAdminActive(admin1));
1531 try {
1532 dpm.reboot(admin1);
1533 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1534 } catch (SecurityException expected) {
1535 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1536 }
1537
1538 // Set admin1 as PO.
1539 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1540 try {
1541 dpm.reboot(admin1);
1542 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1543 } catch (SecurityException expected) {
1544 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1545 }
1546
1547 // Remove PO and add DO.
1548 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001549 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001550 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1551
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001552 // admin1 is DO.
1553 // Set current call state of device to ringing.
1554 when(mContext.telephonyManager.getCallState())
1555 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1556 try {
1557 dpm.reboot(admin1);
1558 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1559 } catch (IllegalStateException expected) {
1560 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1561 }
1562
1563 // Set current call state of device to dialing/active.
1564 when(mContext.telephonyManager.getCallState())
1565 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1566 try {
1567 dpm.reboot(admin1);
1568 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1569 } catch (IllegalStateException expected) {
1570 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1571 }
1572
1573 // Set current call state of device to idle.
1574 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001575 dpm.reboot(admin1);
1576 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001577
1578 public void testSetGetSupportText() {
1579 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1580 dpm.setActiveAdmin(admin1, true);
1581 dpm.setActiveAdmin(admin2, true);
1582 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1583
1584 // Null default support messages.
1585 {
1586 assertNull(dpm.getLongSupportMessage(admin1));
1587 assertNull(dpm.getShortSupportMessage(admin1));
1588 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1589 assertNull(dpm.getShortSupportMessageForUser(admin1,
1590 DpmMockContext.CALLER_USER_HANDLE));
1591 assertNull(dpm.getLongSupportMessageForUser(admin1,
1592 DpmMockContext.CALLER_USER_HANDLE));
1593 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1594 }
1595
1596 // Only system can call the per user versions.
1597 {
1598 try {
1599 dpm.getShortSupportMessageForUser(admin1,
1600 DpmMockContext.CALLER_USER_HANDLE);
1601 fail("Only system should be able to call getXXXForUser versions");
1602 } catch (SecurityException expected) {
1603 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1604 }
1605 try {
1606 dpm.getLongSupportMessageForUser(admin1,
1607 DpmMockContext.CALLER_USER_HANDLE);
1608 fail("Only system should be able to call getXXXForUser versions");
1609 } catch (SecurityException expected) {
1610 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1611 }
1612 }
1613
1614 // Can't set message for admin in another uid.
1615 {
1616 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1617 try {
1618 dpm.setShortSupportMessage(admin1, "Some text");
1619 fail("Admins should only be able to change their own support text.");
1620 } catch (SecurityException expected) {
1621 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1622 }
1623 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1624 }
1625
1626 // Set/Get short returns what it sets and other admins text isn't changed.
1627 {
1628 final String supportText = "Some text to test with.";
1629 dpm.setShortSupportMessage(admin1, supportText);
1630 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1631 assertNull(dpm.getLongSupportMessage(admin1));
1632 assertNull(dpm.getShortSupportMessage(admin2));
1633
1634 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1635 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1636 DpmMockContext.CALLER_USER_HANDLE));
1637 assertNull(dpm.getShortSupportMessageForUser(admin2,
1638 DpmMockContext.CALLER_USER_HANDLE));
1639 assertNull(dpm.getLongSupportMessageForUser(admin1,
1640 DpmMockContext.CALLER_USER_HANDLE));
1641 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1642
1643 dpm.setShortSupportMessage(admin1, null);
1644 assertNull(dpm.getShortSupportMessage(admin1));
1645 }
1646
1647 // Set/Get long returns what it sets and other admins text isn't changed.
1648 {
1649 final String supportText = "Some text to test with.\nWith more text.";
1650 dpm.setLongSupportMessage(admin1, supportText);
1651 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1652 assertNull(dpm.getShortSupportMessage(admin1));
1653 assertNull(dpm.getLongSupportMessage(admin2));
1654
1655 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1656 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1657 DpmMockContext.CALLER_USER_HANDLE));
1658 assertNull(dpm.getLongSupportMessageForUser(admin2,
1659 DpmMockContext.CALLER_USER_HANDLE));
1660 assertNull(dpm.getShortSupportMessageForUser(admin1,
1661 DpmMockContext.CALLER_USER_HANDLE));
1662 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1663
1664 dpm.setLongSupportMessage(admin1, null);
1665 assertNull(dpm.getLongSupportMessage(admin1));
1666 }
1667 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001668
1669 /**
1670 * Test for:
1671 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001672 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001673 * {@link DevicePolicyManager#isAffiliatedUser}
1674 */
1675 public void testUserAffiliation() throws Exception {
1676 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1677 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1678 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1679
1680 // Check that the system user is unaffiliated.
1681 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1682 assertFalse(dpm.isAffiliatedUser());
1683
1684 // Set a device owner on the system user. Check that the system user becomes affiliated.
1685 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1686 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1687 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1688 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001689 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001690
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001691 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001692 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1693 setAsProfileOwner(admin2);
1694 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001695 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001696
1697 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1698 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001699 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001700 userAffiliationIds.add("red");
1701 userAffiliationIds.add("green");
1702 userAffiliationIds.add("blue");
1703 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001704 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001705 assertFalse(dpm.isAffiliatedUser());
1706
1707 // Have the device owner specify a set of affiliation ids that do not intersect with those
1708 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001709 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001710 deviceAffiliationIds.add("cyan");
1711 deviceAffiliationIds.add("yellow");
1712 deviceAffiliationIds.add("magenta");
1713 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1714 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001715 MoreAsserts.assertContentsInAnyOrder(
1716 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001717 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1718 assertFalse(dpm.isAffiliatedUser());
1719
1720 // Have the profile owner specify a set of affiliation ids that intersect with those
1721 // specified by the device owner. Check that the test user becomes affiliated.
1722 userAffiliationIds.add("yellow");
1723 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001724 MoreAsserts.assertContentsInAnyOrder(
1725 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001726 assertTrue(dpm.isAffiliatedUser());
1727
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001728 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
1729 dpm.setAffiliationIds(admin2, Collections.emptyList());
1730 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001731 assertFalse(dpm.isAffiliatedUser());
1732
1733 // Check that the system user remains affiliated.
1734 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1735 assertTrue(dpm.isAffiliatedUser());
1736 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001737
1738 public void testGetUserProvisioningState_defaultResult() {
1739 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1740 }
1741
1742 public void testSetUserProvisioningState_permission() throws Exception {
1743 setupProfileOwner();
1744 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1745
1746 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1747 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1748 }
1749
1750 public void testSetUserProvisioningState_unprivileged() throws Exception {
1751 setupProfileOwner();
1752 try {
1753 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1754 DpmMockContext.CALLER_USER_HANDLE);
1755 fail("Expected SecurityException");
1756 } catch (SecurityException expected) {
1757 }
1758 }
1759
1760 public void testSetUserProvisioningState_noManagement() {
1761 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1762 try {
1763 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1764 DpmMockContext.CALLER_USER_HANDLE);
1765 fail("IllegalStateException expected");
1766 } catch (IllegalStateException e) {
1767 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1768 e.getMessage());
1769 }
1770 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1771 }
1772
1773 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1774 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1775 setupDeviceOwner();
1776 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1777
1778 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1779 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1780 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1781 }
1782
1783 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1784 throws Exception {
1785 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1786 setupDeviceOwner();
1787 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1788
1789 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1790 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1791 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1792 }
1793
1794 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1795 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1796 setupDeviceOwner();
1797 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1798
1799 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1800 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1801 }
1802
1803 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1804 throws Exception {
1805 setupProfileOwner();
1806 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1807
1808 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1809 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1810 DevicePolicyManager.STATE_USER_UNMANAGED);
1811 }
1812
1813 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1814 throws Exception {
1815 setupProfileOwner();
1816 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1817
1818 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1819 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1820 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1821 }
1822
1823 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1824 setupProfileOwner();
1825 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1826
1827 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1828 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1829 }
1830
1831 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
1832 setupProfileOwner();
1833 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1834
1835 try {
1836 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1837 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1838 DevicePolicyManager.STATE_USER_UNMANAGED);
1839 fail("Expected IllegalStateException");
1840 } catch (IllegalStateException e) {
1841 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1842 e.getMessage());
1843 }
1844 }
1845
1846 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
1847 throws Exception {
1848 setupProfileOwner();
1849 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1850
1851 try {
1852 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1853 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1854 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
1855 fail("Expected IllegalStateException");
1856 } catch (IllegalStateException e) {
1857 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1858 e.getMessage());
1859 }
1860 }
1861
1862 private void exerciseUserProvisioningTransitions(int userId, int... states) {
1863 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1864 for (int state : states) {
1865 dpm.setUserProvisioningState(state, userId);
1866 assertEquals(state, dpm.getUserProvisioningState());
1867 }
1868 }
1869
1870 private void setupProfileOwner() throws Exception {
1871 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1872
1873 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1874 dpm.setActiveAdmin(admin1, false);
1875 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
1876
1877 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1878 }
1879
1880 private void setupDeviceOwner() throws Exception {
1881 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1882
1883 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1884 dpm.setActiveAdmin(admin1, false);
1885 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1886
1887 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1888 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001889
1890 public void testSetMaximumTimeToLock() {
1891 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1892
1893 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1894 dpm.setActiveAdmin(admin2, /* replace =*/ false);
1895
1896 reset(mMockContext.powerManagerInternal);
1897 reset(mMockContext.settings);
1898
1899 dpm.setMaximumTimeToLock(admin1, 0);
1900 verifyScreenTimeoutCall(null, false);
1901 reset(mMockContext.powerManagerInternal);
1902 reset(mMockContext.settings);
1903
1904 dpm.setMaximumTimeToLock(admin1, 1);
1905 verifyScreenTimeoutCall(1, true);
1906 reset(mMockContext.powerManagerInternal);
1907 reset(mMockContext.settings);
1908
1909 dpm.setMaximumTimeToLock(admin2, 10);
1910 verifyScreenTimeoutCall(null, false);
1911 reset(mMockContext.powerManagerInternal);
1912 reset(mMockContext.settings);
1913
1914 dpm.setMaximumTimeToLock(admin1, 5);
1915 verifyScreenTimeoutCall(5, true);
1916 reset(mMockContext.powerManagerInternal);
1917 reset(mMockContext.settings);
1918
1919 dpm.setMaximumTimeToLock(admin2, 4);
1920 verifyScreenTimeoutCall(4, true);
1921 reset(mMockContext.powerManagerInternal);
1922 reset(mMockContext.settings);
1923
1924 dpm.setMaximumTimeToLock(admin1, 0);
1925 reset(mMockContext.powerManagerInternal);
1926 reset(mMockContext.settings);
1927
1928 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
1929 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1930 reset(mMockContext.powerManagerInternal);
1931 reset(mMockContext.settings);
1932
1933 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
1934 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1935 reset(mMockContext.powerManagerInternal);
1936 reset(mMockContext.settings);
1937
1938 dpm.setMaximumTimeToLock(admin2, 10);
1939 verifyScreenTimeoutCall(10, true);
1940 reset(mMockContext.powerManagerInternal);
1941 reset(mMockContext.settings);
1942
1943 // There's no restriction; shold be set to MAX.
1944 dpm.setMaximumTimeToLock(admin2, 0);
1945 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
1946 }
1947
Michal Karpinski943aabd2016-10-06 11:09:25 +01001948 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
1949 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1950 setupDeviceOwner();
1951 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1952
1953 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
1954 final long ONE_MINUTE = 60 * 1000;
1955
1956 // aggregation should be the default if unset by any admin
1957 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1958 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1959
1960 // admin not participating by default
1961 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1962
1963 //clamping from the top
1964 dpm.setRequiredStrongAuthTimeout(admin1,
1965 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1966 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
1967 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1968 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1969 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1970
1971 // 0 means default
1972 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1973 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1974 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1975 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1976
1977 // clamping from the bottom
1978 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
1979 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1980 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1981
1982 // value within range
1983 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1984 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1985 + ONE_MINUTE);
1986 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1987 + ONE_MINUTE);
1988
1989 // reset to default
1990 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1991 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1992 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1993 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1994
1995 // negative value
1996 try {
1997 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
1998 fail("Didn't throw IllegalArgumentException");
1999 } catch (IllegalArgumentException iae) {
2000 }
2001 }
2002
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002003 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2004 boolean shouldStayOnWhilePluggedInBeCleared) {
2005 if (expectedTimeout == null) {
2006 verify(mMockContext.powerManagerInternal, times(0))
2007 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2008 } else {
2009 verify(mMockContext.powerManagerInternal, times(1))
2010 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2011 }
2012 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2013 // UnfinishedVerificationException.
2014 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002015
Esteban Talavera01576862016-12-15 11:16:44 +00002016 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002017 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2018 .thenReturn(false);
2019 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2020 .thenReturn(false);
2021 initializeDpms();
2022 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2023 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2024 .thenReturn(true);
2025 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2026
2027 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002028 }
Victor Chang3e794af2016-03-04 13:48:17 +00002029
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002030 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2031 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002032 mContext.packageName = admin1.getPackageName();
2033 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002034 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2035 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2036 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2037 false);
2038 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2039 }
2040
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002041 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2042 setup_DeviceAdminFeatureOff();
2043 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2044 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2045 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2046 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2047 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2048 assertCheckProvisioningPreCondition(
2049 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2050 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2051 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2052 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2053 }
2054
Esteban Talavera01576862016-12-15 11:16:44 +00002055 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002056 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2057 .thenReturn(false);
2058 initializeDpms();
2059 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2060 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2061 .thenReturn(true);
2062 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2063
2064 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002065 }
Victor Chang3e794af2016-03-04 13:48:17 +00002066
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002067 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2068 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002069 mContext.packageName = admin1.getPackageName();
2070 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002071 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2072 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2073 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2074 false);
2075 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2076
2077 // Test again when split user is on
2078 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2079 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2080 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2081 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2082 true);
2083 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2084 }
2085
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002086 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2087 setup_ManagedProfileFeatureOff();
2088 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2089 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2090 DevicePolicyManager.CODE_OK);
2091 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2092 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2093 assertCheckProvisioningPreCondition(
2094 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2095 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2096 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2097 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2098
2099 // Test again when split user is on
2100 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2101 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2102 DevicePolicyManager.CODE_OK);
2103 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2104 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2105 assertCheckProvisioningPreCondition(
2106 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2107 DevicePolicyManager.CODE_OK);
2108 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2109 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2110 }
2111
Esteban Talavera01576862016-12-15 11:16:44 +00002112 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002113 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2114 .thenReturn(true);
2115 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2116 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2117 .thenReturn(true);
2118 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2119
2120 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002121 }
Victor Chang3e794af2016-03-04 13:48:17 +00002122
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002123 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2124 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002125 mContext.packageName = admin1.getPackageName();
2126 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002127 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2128 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2129 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2130 false /* because of non-split user */);
2131 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2132 false /* because of non-split user */);
2133 }
2134
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002135 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002136 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002137 setup_nonSplitUser_firstBoot_primaryUser();
2138 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2139 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2140 DevicePolicyManager.CODE_OK);
2141 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2142 DevicePolicyManager.CODE_OK);
2143 assertCheckProvisioningPreCondition(
2144 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2145 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2146 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2147 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2148 }
2149
Esteban Talavera01576862016-12-15 11:16:44 +00002150 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002151 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2152 .thenReturn(true);
2153 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2154 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2155 .thenReturn(true);
2156 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2157
2158 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002159 }
Victor Chang3e794af2016-03-04 13:48:17 +00002160
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002161 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2162 throws Exception {
2163 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002164 mContext.packageName = admin1.getPackageName();
2165 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002166 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2167 false/* because of completed device setup */);
2168 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2169 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2170 false/* because of non-split user */);
2171 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2172 false/* because of non-split user */);
2173 }
2174
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002175 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2176 throws Exception {
2177 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2178 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2179 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2180 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2181 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2182 DevicePolicyManager.CODE_OK);
2183 assertCheckProvisioningPreCondition(
2184 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2185 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2186 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2187 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2188 }
2189
Esteban Talavera01576862016-12-15 11:16:44 +00002190 public void testIsProvisioningAllowed_nonSplitUser_withDo_primaryUser() throws Exception {
2191 setDeviceOwner();
2192 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2193 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2194 mContext.packageName = admin1.getPackageName();
2195
2196 // COMP mode is allowed.
2197 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2198
2199 when(mContext.userManager.hasUserRestriction(
2200 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2201 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2202 .thenReturn(true);
2203
2204 // The DO should be allowed to initiate provisioning if it set the restriction itself.
2205 when(mContext.userManager.getUserRestrictionSource(
2206 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2207 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2208 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2209 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2210
2211 // The DO should not be allowed to initiate provisioning if the restriction is set by
2212 // another entity.
2213 when(mContext.userManager.getUserRestrictionSource(
2214 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2215 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2216 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2217 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2218 }
2219
2220 public void
2221 testCheckProvisioningPreCondition_nonSplitUser_withDo_primaryUser() throws Exception {
2222 setDeviceOwner();
2223 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2224 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2225
2226 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2227 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
2228
2229 // COMP mode is allowed.
2230 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2231 DevicePolicyManager.CODE_OK);
2232
2233 // And other DPCs can also provisioning a managed profile (DO + BYOD case).
2234 assertCheckProvisioningPreCondition(
2235 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2236 "some.other.dpc.package.name",
2237 DevicePolicyManager.CODE_OK);
2238
2239 when(mContext.userManager.hasUserRestriction(
2240 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2241 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2242 .thenReturn(true);
2243
2244 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2245 // other packages should be forbidden.
2246 when(mContext.userManager.getUserRestrictionSource(
2247 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2248 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2249 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2250 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2251 DevicePolicyManager.CODE_OK);
2252 assertCheckProvisioningPreCondition(
2253 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2254 "some.other.dpc.package.name",
2255 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2256
2257 // The DO should not be allowed to initiate provisioning if the restriction is set by
2258 // another entity.
2259 when(mContext.userManager.getUserRestrictionSource(
2260 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2261 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2262 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2263 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2264 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2265 assertCheckProvisioningPreCondition(
2266 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2267 "some.other.dpc.package.name",
2268 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2269 }
2270
2271 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002272 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2273 .thenReturn(true);
2274 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2275 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2276 .thenReturn(false);
2277 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2278
2279 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002280 }
Victor Chang3e794af2016-03-04 13:48:17 +00002281
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002282 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2283 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002284 mContext.packageName = admin1.getPackageName();
2285 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002286 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2287 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2288 false /* because canAddMoreManagedProfiles returns false */);
2289 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2290 true);
2291 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2292 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002293 }
2294
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002295 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2296 throws Exception {
2297 setup_splitUser_firstBoot_systemUser();
2298 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2299 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2300 DevicePolicyManager.CODE_OK);
2301 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002302 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002303 assertCheckProvisioningPreCondition(
2304 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2305 DevicePolicyManager.CODE_OK);
2306 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2307 DevicePolicyManager.CODE_SYSTEM_USER);
2308 }
2309
Esteban Talavera01576862016-12-15 11:16:44 +00002310 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002311 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2312 .thenReturn(true);
2313 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2314 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2315 .thenReturn(false);
2316 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2317
2318 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002319 }
Victor Chang3e794af2016-03-04 13:48:17 +00002320
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002321 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2322 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002323 mContext.packageName = admin1.getPackageName();
2324 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002325 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2326 true/* it's undefined behavior. Can be changed into false in the future */);
2327 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2328 false /* because canAddMoreManagedProfiles returns false */);
2329 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2330 true/* it's undefined behavior. Can be changed into false in the future */);
2331 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2332 false/* because calling uid is system user */);
2333 }
2334
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002335 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2336 throws Exception {
2337 setup_splitUser_afterDeviceSetup_systemUser();
2338 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2339 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2340 DevicePolicyManager.CODE_OK);
2341 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002342 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002343 assertCheckProvisioningPreCondition(
2344 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2345 DevicePolicyManager.CODE_OK);
2346 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2347 DevicePolicyManager.CODE_SYSTEM_USER);
2348 }
2349
Esteban Talavera01576862016-12-15 11:16:44 +00002350 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002351 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2352 .thenReturn(true);
2353 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2354 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2355 true)).thenReturn(true);
2356 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2357
2358 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002359 }
Victor Chang3e794af2016-03-04 13:48:17 +00002360
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002361 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2362 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002363 mContext.packageName = admin1.getPackageName();
2364 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002365 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2366 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2367 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2368 true);
2369 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002370 }
2371
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002372 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002373 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002374 setup_splitUser_firstBoot_primaryUser();
2375 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2376 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2377 DevicePolicyManager.CODE_OK);
2378 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2379 DevicePolicyManager.CODE_OK);
2380 assertCheckProvisioningPreCondition(
2381 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2382 DevicePolicyManager.CODE_OK);
2383 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2384 DevicePolicyManager.CODE_OK);
2385 }
2386
Esteban Talavera01576862016-12-15 11:16:44 +00002387 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002388 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2389 .thenReturn(true);
2390 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2391 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2392 true)).thenReturn(true);
2393 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2394
2395 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002396 }
Victor Chang3e794af2016-03-04 13:48:17 +00002397
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002398 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2399 throws Exception {
2400 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002401 mContext.packageName = admin1.getPackageName();
2402 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002403 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2404 true/* it's undefined behavior. Can be changed into false in the future */);
2405 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2406 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2407 true/* it's undefined behavior. Can be changed into false in the future */);
2408 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2409 false/* because user setup completed */);
2410 }
2411
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002412 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002413 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002414 setup_splitUser_afterDeviceSetup_primaryUser();
2415 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2416 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2417 DevicePolicyManager.CODE_OK);
2418 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2419 DevicePolicyManager.CODE_OK);
2420 assertCheckProvisioningPreCondition(
2421 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2422 DevicePolicyManager.CODE_OK);
2423 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2424 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2425 }
2426
Esteban Talavera01576862016-12-15 11:16:44 +00002427 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002428 setDeviceOwner();
2429
2430 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2431 .thenReturn(true);
2432 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2433 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2434 .thenReturn(false);
2435 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2436
2437 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002438 }
Victor Chang3e794af2016-03-04 13:48:17 +00002439
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002440 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2441 throws Exception {
2442 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002443 mContext.packageName = admin1.getPackageName();
2444 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002445 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2446 false /* can't provision managed profile on system user */);
2447 }
2448
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002449 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002450 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002451 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2452 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2453 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2454 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2455 }
2456
2457 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002458 setDeviceOwner();
2459
2460 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2461 .thenReturn(true);
2462 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2463 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2464 true)).thenReturn(true);
2465 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2466
2467 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002468 }
Victor Chang3e794af2016-03-04 13:48:17 +00002469
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002470 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2471 throws Exception {
2472 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002473 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2474 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002475 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2476 }
2477
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002478 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002479 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002480 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2481 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002482
2483 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002484 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2485 DevicePolicyManager.CODE_OK);
2486 }
2487
2488 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002489 setDeviceOwner();
2490
2491 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2492 .thenReturn(true);
2493 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002494 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002495 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2496 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002497 .thenReturn(true);
2498 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002499 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002500 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2501 true)).thenReturn(true);
2502 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2503
2504 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002505 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002506
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002507 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2508 throws Exception {
2509 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002510 mContext.packageName = admin1.getPackageName();
2511 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002512 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2513 }
2514
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002515 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2516 throws Exception {
2517 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2518 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2519 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2520 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2521 }
2522
2523 public void testCheckProvisioningPreCondition_permission() {
2524 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2525 try {
Esteban Talavera01576862016-12-15 11:16:44 +00002526 dpm.checkProvisioningPreCondition(
2527 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002528 fail("Didn't throw SecurityException");
2529 } catch (SecurityException expected) {
2530 }
2531 }
2532
Victor Chang3577ed22016-08-25 18:49:26 +01002533 public void testForceUpdateUserSetupComplete_permission() {
2534 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2535 try {
2536 dpm.forceUpdateUserSetupComplete();
2537 fail("Didn't throw SecurityException");
2538 } catch (SecurityException expected) {
2539 }
2540 }
2541
2542 public void testForceUpdateUserSetupComplete_systemUser() {
2543 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2544 // GIVEN calling from user 20
2545 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2546 try {
2547 dpm.forceUpdateUserSetupComplete();
2548 fail("Didn't throw SecurityException");
2549 } catch (SecurityException expected) {
2550 }
2551 }
2552
2553 public void testForceUpdateUserSetupComplete_userbuild() {
2554 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2555 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2556
2557 final int userId = UserHandle.USER_SYSTEM;
2558 // GIVEN userComplete is false in SettingsProvider
2559 setUserSetupCompleteForUser(false, userId);
2560
2561 // GIVEN userComplete is true in DPM
2562 DevicePolicyManagerService.DevicePolicyData userData =
2563 new DevicePolicyManagerService.DevicePolicyData(userId);
2564 userData.mUserSetupComplete = true;
2565 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2566
2567 // GIVEN it's user build
2568 mContext.buildMock.isDebuggable = false;
2569
2570 assertTrue(dpms.hasUserSetupCompleted());
2571
2572 dpm.forceUpdateUserSetupComplete();
2573
2574 // THEN the state in dpms is not changed
2575 assertTrue(dpms.hasUserSetupCompleted());
2576 }
2577
2578 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2579 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2580 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2581
2582 final int userId = UserHandle.USER_SYSTEM;
2583 // GIVEN userComplete is false in SettingsProvider
2584 setUserSetupCompleteForUser(false, userId);
2585
2586 // GIVEN userComplete is true in DPM
2587 DevicePolicyManagerService.DevicePolicyData userData =
2588 new DevicePolicyManagerService.DevicePolicyData(userId);
2589 userData.mUserSetupComplete = true;
2590 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2591
2592 // GIVEN it's userdebug build
2593 mContext.buildMock.isDebuggable = true;
2594
2595 assertTrue(dpms.hasUserSetupCompleted());
2596
2597 dpm.forceUpdateUserSetupComplete();
2598
2599 // THEN the state in dpms is not changed
2600 assertFalse(dpms.hasUserSetupCompleted());
2601 }
2602
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002603 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002604 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002605 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2606 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2607 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2608 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002609 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002610 }
2611
2612 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2613 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2614 setupDeviceOwner();
2615 when(mContext.userManager.getUserCount()).thenReturn(1);
2616 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2617 .thenReturn(true);
2618
2619 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002620 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002621
2622 // Enabling logging should not change the timestamp.
2623 dpm.setSecurityLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002624 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002625
2626 // Retrieving the logs should update the timestamp.
2627 final long beforeRetrieval = System.currentTimeMillis();
2628 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002629 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002630 final long afterRetrieval = System.currentTimeMillis();
2631 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2632 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2633
2634 // Retrieving the pre-boot logs should update the timestamp.
2635 Thread.sleep(2);
2636 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002637 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002638 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2639
2640 // Checking the timestamp again should not change it.
2641 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002642 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002643
2644 // Retrieving the logs again should update the timestamp.
2645 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002646 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002647 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2648
2649 // Disabling logging should not change the timestamp.
2650 Thread.sleep(2);
2651 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002652 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002653
2654 // Restarting the DPMS should not lose the timestamp.
2655 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002656 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002657
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002658 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2659 mContext.binder.callingUid = 1234567;
2660 mContext.callerPermissions.add(permission.MANAGE_USERS);
2661 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2662 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2663
2664 // System can retrieve the timestamp.
2665 mContext.binder.clearCallingIdentity();
2666 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2667
2668 // Removing the device owner should clear the timestamp.
2669 clearDeviceOwner();
2670 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002671 }
2672
2673 public void testGetLastBugReportRequestTime() throws Exception {
2674 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2675 setupDeviceOwner();
2676 when(mContext.userManager.getUserCount()).thenReturn(1);
2677 mContext.packageName = admin1.getPackageName();
2678 mContext.applicationInfo = new ApplicationInfo();
2679 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2680 .thenReturn(Color.WHITE);
2681 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2682 anyObject())).thenReturn(Color.WHITE);
2683
2684 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002685 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002686
2687 // Requesting a bug report should update the timestamp.
2688 final long beforeRequest = System.currentTimeMillis();
2689 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002690 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002691 final long afterRequest = System.currentTimeMillis();
2692 assertTrue(bugReportRequestTime >= beforeRequest);
2693 assertTrue(bugReportRequestTime <= afterRequest);
2694
2695 // Checking the timestamp again should not change it.
2696 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002697 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002698
2699 // Restarting the DPMS should not lose the timestamp.
2700 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002701 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002702
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002703 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2704 mContext.binder.callingUid = 1234567;
2705 mContext.callerPermissions.add(permission.MANAGE_USERS);
2706 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2707 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2708
2709 // System can retrieve the timestamp.
2710 mContext.binder.clearCallingIdentity();
2711 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2712
2713 // Removing the device owner should clear the timestamp.
2714 clearDeviceOwner();
2715 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002716 }
2717
2718 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2719 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2720 setupDeviceOwner();
2721 when(mContext.userManager.getUserCount()).thenReturn(1);
2722 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2723 .thenReturn(true);
2724
2725 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002726 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002727
2728 // Attempting to retrieve logs without enabling logging should not change the timestamp.
2729 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002730 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002731
2732 // Enabling logging should not change the timestamp.
2733 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002734 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002735
2736 // Retrieving the logs should update the timestamp.
2737 final long beforeRetrieval = System.currentTimeMillis();
2738 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002739 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002740 final long afterRetrieval = System.currentTimeMillis();
2741 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
2742 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
2743
2744 // Checking the timestamp again should not change it.
2745 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002746 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002747
2748 // Retrieving the logs again should update the timestamp.
2749 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002750 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002751 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
2752
2753 // Disabling logging should not change the timestamp.
2754 Thread.sleep(2);
2755 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002756 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002757
2758 // Restarting the DPMS should not lose the timestamp.
2759 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002760 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2761
2762 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2763 mContext.binder.callingUid = 1234567;
2764 mContext.callerPermissions.add(permission.MANAGE_USERS);
2765 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2766 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2767
2768 // System can retrieve the timestamp.
2769 mContext.binder.clearCallingIdentity();
2770 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2771
2772 // Removing the device owner should clear the timestamp.
2773 clearDeviceOwner();
2774 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002775 }
2776
Tony Mak2f26b792016-11-28 17:54:51 +00002777 public void testGetBindDeviceAdminTargetUsers() throws Exception {
2778 // Setup device owner.
2779 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2780 setupDeviceOwner();
2781
2782 // Only device owner is setup, the result list should be empty.
2783 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2784 MoreAsserts.assertEmpty(targetUsers);
2785
2786 // Setup a managed profile managed by the same admin.
2787 final int MANAGED_PROFILE_USER_ID = 15;
2788 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2789 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2790
2791 // Add a secondary user, it should never talk with.
2792 final int ANOTHER_USER_ID = 36;
2793 mContext.addUser(ANOTHER_USER_ID, 0);
2794
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002795 // Since the managed profile is not affiliated, they should not be allowed to talk to each
2796 // other.
2797 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2798 MoreAsserts.assertEmpty(targetUsers);
2799
2800 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2801 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2802 MoreAsserts.assertEmpty(targetUsers);
2803
2804 // Setting affiliation ids
2805 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
2806 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2807 dpm.setAffiliationIds(admin1, userAffiliationIds);
2808
2809 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2810 dpm.setAffiliationIds(admin1, userAffiliationIds);
2811
Tony Mak2f26b792016-11-28 17:54:51 +00002812 // Calling from device owner admin, the result list should just contain the managed
2813 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002814 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00002815 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2816 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
2817
2818 // Calling from managed profile admin, the result list should just contain the system
2819 // user id.
2820 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2821 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2822 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002823
2824 // Changing affiliation ids in one
2825 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
2826
2827 // Since the managed profile is not affiliated any more, they should not be allowed to talk
2828 // to each other.
2829 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2830 MoreAsserts.assertEmpty(targetUsers);
2831
2832 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2833 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2834 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00002835 }
2836
2837 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
2838 // Setup a device owner.
2839 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2840 setupDeviceOwner();
2841
2842 // Set up a managed profile managed by different package.
2843 final int MANAGED_PROFILE_USER_ID = 15;
2844 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2845 final ComponentName adminDifferentPackage =
2846 new ComponentName("another.package", "whatever.class");
2847 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
2848
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002849 // Setting affiliation ids
2850 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
2851 dpm.setAffiliationIds(admin1, userAffiliationIds);
2852
2853 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2854 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
2855
Tony Mak2f26b792016-11-28 17:54:51 +00002856 // Calling from device owner admin, we should get zero bind device admin target users as
2857 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002858 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00002859 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2860 MoreAsserts.assertEmpty(targetUsers);
2861
2862 // Calling from managed profile admin, we should still get zero target users for the same
2863 // reason.
2864 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2865 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
2866 MoreAsserts.assertEmpty(targetUsers);
2867 }
2868
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01002869 public void testIsDeviceManaged() throws Exception {
2870 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2871 setupDeviceOwner();
2872
2873 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
2874 // find out that the device has a device owner.
2875 assertTrue(dpm.isDeviceManaged());
2876 mContext.binder.callingUid = 1234567;
2877 mContext.callerPermissions.add(permission.MANAGE_USERS);
2878 assertTrue(dpm.isDeviceManaged());
2879 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2880 mContext.binder.clearCallingIdentity();
2881 assertTrue(dpm.isDeviceManaged());
2882
2883 clearDeviceOwner();
2884
2885 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
2886 // not have a device owner.
2887 mContext.binder.callingUid = 1234567;
2888 mContext.callerPermissions.add(permission.MANAGE_USERS);
2889 assertFalse(dpm.isDeviceManaged());
2890 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2891 mContext.binder.clearCallingIdentity();
2892 assertFalse(dpm.isDeviceManaged());
2893 }
2894
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01002895 public void testDeviceOwnerOrganizationName() throws Exception {
2896 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2897 setupDeviceOwner();
2898
2899 dpm.setOrganizationName(admin1, "organization");
2900
2901 // Device owner can retrieve organization managing the device.
2902 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2903
2904 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
2905 mContext.binder.callingUid = 1234567;
2906 mContext.callerPermissions.add(permission.MANAGE_USERS);
2907 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2908 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2909
2910 // System can retrieve organization managing the device.
2911 mContext.binder.clearCallingIdentity();
2912 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2913
2914 // Removing the device owner clears the organization managing the device.
2915 clearDeviceOwner();
2916 assertNull(dpm.getDeviceOwnerOrganizationName());
2917 }
2918
Victor Chang3e794af2016-03-04 13:48:17 +00002919 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
2920 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
2921 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
2922 dpms.notifyChangeToContentObserver(
2923 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
2924 }
2925
2926 private void assertProvisioningAllowed(String action, boolean expected) {
2927 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
2928 dpm.isProvisioningAllowed(action));
2929 }
Tony Mak2f26b792016-11-28 17:54:51 +00002930
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002931 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00002932 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
2933 }
2934
2935 private void assertCheckProvisioningPreCondition(
2936 String action, String packageName, int provisioningCondition) {
2937 assertEquals("checkProvisioningPreCondition("
2938 + action + ", " + packageName + ") returning unexpected result",
2939 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002940 }
2941
Tony Mak2f26b792016-11-28 17:54:51 +00002942 /**
2943 * Setup a managed profile with the specified admin and its uid.
2944 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
2945 * @param adminUid uid of the admin package.
2946 * @param copyFromAdmin package information for {@code admin} will be built based on this
2947 * component's information.
2948 */
2949 private void addManagedProfile(
2950 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
2951 final int userId = UserHandle.getUserId(adminUid);
2952 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
2953 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2954 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
2955 dpm.setActiveAdmin(admin, false, userId);
2956 assertTrue(dpm.setProfileOwner(admin, null, userId));
2957 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2958 }
Victor Chang3e794af2016-03-04 13:48:17 +00002959}