blob: 98a26aba4d92db49e97f0d7140b9e4a3b6b95310 [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;
Rubin Xued1928a2016-02-11 17:23:06 +000025import android.content.pm.ApplicationInfo;
26import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070027import android.content.pm.PackageManager;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010028import android.content.res.Resources;
29import android.graphics.Color;
30import android.net.IIpConnectivityMetrics;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080031import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080032import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070033import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080034import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070035import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070036import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080037import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000038import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080039import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000040import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010041import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070042import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070043
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010044import com.android.internal.R;
Alan Treadwayafad8782016-01-19 15:15:08 +000045import com.android.server.LocalServices;
46import com.android.server.SystemService;
47
Makoto Onukib643fb02015-09-22 15:03:44 -070048import org.mockito.invocation.InvocationOnMock;
49import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070050
Makoto Onukic8a5a552015-11-19 14:29:12 -080051import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000052import java.util.Arrays;
Makoto Onukib643fb02015-09-22 15:03:44 -070053import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070054import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070055import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010056import java.util.Set;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070057
58import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070059import static org.mockito.Matchers.anyInt;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010060import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070061import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070062import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070063import static org.mockito.Matchers.isNull;
Makoto Onukib643fb02015-09-22 15:03:44 -070064import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070065import static org.mockito.Mockito.doReturn;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080066import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070067import static org.mockito.Mockito.times;
68import static org.mockito.Mockito.verify;
69import static org.mockito.Mockito.when;
70
71/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070072 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070073 *
74 m FrameworksServicesTests &&
75 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000076 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070077 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080078 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070079
80 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
81 */
Benjamin Franz6d009032016-01-25 18:56:38 +000082@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070083public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000084 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
85 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
86 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
87
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070088 private DpmMockContext mContext;
89 public DevicePolicyManager dpm;
90 public DevicePolicyManagerServiceTestable dpms;
91
92 @Override
93 protected void setUp() throws Exception {
94 super.setUp();
95
96 mContext = getContext();
97
98 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
99 .thenReturn(true);
100
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800101 // By default, pretend all users are running and unlocked.
102 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
103
Makoto Onukia52562c2015-10-01 16:12:31 -0700104 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700105
Makoto Onukid932f762015-09-29 16:53:38 -0700106 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
107 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
108 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800109 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700110
Makoto Onukib643fb02015-09-22 15:03:44 -0700111 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700112 }
113
Makoto Onukia52562c2015-10-01 16:12:31 -0700114 private void initializeDpms() {
115 // Need clearCallingIdentity() to pass permission checks.
116 final long ident = mContext.binder.clearCallingIdentity();
117 try {
118 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
119
120 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
121
122 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
123 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
124
125 dpm = new DevicePolicyManagerTestable(mContext, dpms);
126 } finally {
127 mContext.binder.restoreCallingIdentity(ident);
128 }
129 }
130
Makoto Onukib643fb02015-09-22 15:03:44 -0700131 private void setUpUserManager() {
132 // Emulate UserManager.set/getApplicationRestriction().
133 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
134
135 // UM.setApplicationRestrictions() will save to appRestrictions.
136 doAnswer(new Answer<Void>() {
137 @Override
138 public Void answer(InvocationOnMock invocation) throws Throwable {
139 String pkg = (String) invocation.getArguments()[0];
140 Bundle bundle = (Bundle) invocation.getArguments()[1];
141 UserHandle user = (UserHandle) invocation.getArguments()[2];
142
143 appRestrictions.put(Pair.create(pkg, user), bundle);
144
145 return null;
146 }
147 }).when(mContext.userManager).setApplicationRestrictions(
148 anyString(), any(Bundle.class), any(UserHandle.class));
149
150 // UM.getApplicationRestrictions() will read from appRestrictions.
151 doAnswer(new Answer<Bundle>() {
152 @Override
153 public Bundle answer(InvocationOnMock invocation) throws Throwable {
154 String pkg = (String) invocation.getArguments()[0];
155 UserHandle user = (UserHandle) invocation.getArguments()[1];
156
157 return appRestrictions.get(Pair.create(pkg, user));
158 }
159 }).when(mContext.userManager).getApplicationRestrictions(
160 anyString(), any(UserHandle.class));
161
Makoto Onukid932f762015-09-29 16:53:38 -0700162 // Add the first secondary user.
163 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700164 }
165
166 private void setAsProfileOwner(ComponentName admin) {
167 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
168 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
169
Makoto Onukia4f11972015-10-01 13:19:58 -0700170 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700171 dpm.setActiveAdmin(admin, /* replace =*/ false);
172
173 // Fire!
174 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
175
176 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700177 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700178 }
179
180 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700181 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
182 .thenReturn(false);
183
184 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
185 new DevicePolicyManagerServiceTestable(mContext, dataDir);
186
187 // If the device has no DPMS feature, it shouldn't register the local service.
188 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
189 }
190
191 /**
192 * Caller doesn't have proper permissions.
193 */
194 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700195 // 1. Failure cases.
196
197 // Caller doesn't have MANAGE_DEVICE_ADMINS.
198 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700199 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700200 fail("Didn't throw SecurityException");
201 } catch (SecurityException expected) {
202 }
203
204 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
205 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
206 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700207 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700208 fail("Didn't throw SecurityException");
209 } catch (SecurityException expected) {
210 }
211 }
212
Makoto Onukif76b06a2015-09-22 15:03:44 -0700213 /**
214 * Test for:
215 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800216 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700217 * {@link DevicePolicyManager#isAdminActive}
218 * {@link DevicePolicyManager#isAdminActiveAsUser}
219 * {@link DevicePolicyManager#getActiveAdmins}
220 * {@link DevicePolicyManager#getActiveAdminsAsUser}
221 */
222 public void testSetActiveAdmin() throws Exception {
223 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700224 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
225
Makoto Onukif76b06a2015-09-22 15:03:44 -0700226 // 2. Call the API.
227 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700228
229 // 3. Verify internal calls.
230
231 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700232 verify(mContext.spiedContext).sendBroadcastAsUser(
233 MockUtils.checkIntentAction(
234 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
235 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
236 verify(mContext.spiedContext).sendBroadcastAsUser(
237 MockUtils.checkIntentAction(
238 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700239 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
240
Makoto Onukif76b06a2015-09-22 15:03:44 -0700241 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
242 eq(admin1.getPackageName()),
243 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
244 eq(PackageManager.DONT_KILL_APP),
245 eq(DpmMockContext.CALLER_USER_HANDLE),
246 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700247
248 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700249
250 // Make sure it's active admin1.
251 assertTrue(dpm.isAdminActive(admin1));
252 assertFalse(dpm.isAdminActive(admin2));
253 assertFalse(dpm.isAdminActive(admin3));
254
255 // But not admin1 for a different user.
256
257 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
258 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
259 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
260
261 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
262 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
263
264 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
265
266 // Next, add one more admin.
267 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700268 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
269 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700270
271 dpm.setActiveAdmin(admin2, /* replace =*/ false);
272
273 // Now we have two admins.
274 assertTrue(dpm.isAdminActive(admin1));
275 assertTrue(dpm.isAdminActive(admin2));
276 assertFalse(dpm.isAdminActive(admin3));
277
278 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
279 // again. (times(1) because it was previously called for admin1)
280 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
281 eq(admin1.getPackageName()),
282 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
283 eq(PackageManager.DONT_KILL_APP),
284 eq(DpmMockContext.CALLER_USER_HANDLE),
285 anyString());
286
287 // 4. Add the same admin1 again without replace, which should throw.
288 try {
289 dpm.setActiveAdmin(admin1, /* replace =*/ false);
290 fail("Didn't throw");
291 } catch (IllegalArgumentException expected) {
292 }
293
294 // 5. Add the same admin1 again with replace, which should succeed.
295 dpm.setActiveAdmin(admin1, /* replace =*/ true);
296
297 // TODO make sure it's replaced.
298
299 // 6. Test getActiveAdmins()
300 List<ComponentName> admins = dpm.getActiveAdmins();
301 assertEquals(2, admins.size());
302 assertEquals(admin1, admins.get(0));
303 assertEquals(admin2, admins.get(1));
304
305 // Another user has no admins.
306 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
307
308 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
309 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
310
311 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
312 }
313
Makoto Onukid932f762015-09-29 16:53:38 -0700314 public void testSetActiveAdmin_multiUsers() throws Exception {
315
316 final int ANOTHER_USER_ID = 100;
317 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
318
319 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
320
321 // Set up pacakge manager for the other user.
322 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700323
324 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
325
326 dpm.setActiveAdmin(admin1, /* replace =*/ false);
327
328 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
329 dpm.setActiveAdmin(admin2, /* replace =*/ false);
330
331
332 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
333 assertTrue(dpm.isAdminActive(admin1));
334 assertFalse(dpm.isAdminActive(admin2));
335
336 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
337 assertFalse(dpm.isAdminActive(admin1));
338 assertTrue(dpm.isAdminActive(admin2));
339 }
340
Makoto Onukif76b06a2015-09-22 15:03:44 -0700341 /**
342 * Test for:
343 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800344 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700345 */
346 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
347 // 1. Make sure the caller has proper permissions.
348 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
349
350 dpm.setActiveAdmin(admin1, /* replace =*/ false);
351 assertTrue(dpm.isAdminActive(admin1));
352
353 // Add the same admin1 again without replace, which should throw.
354 try {
355 dpm.setActiveAdmin(admin1, /* replace =*/ false);
356 fail("Didn't throw");
357 } catch (IllegalArgumentException expected) {
358 }
359 }
360
361 /**
362 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800363 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
364 * BIND_DEVICE_ADMIN.
365 */
366 public void testSetActiveAdmin_permissionCheck() throws Exception {
367 // 1. Make sure the caller has proper permissions.
368 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
369
370 try {
371 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
372 fail();
373 } catch (IllegalArgumentException expected) {
374 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
375 }
376 assertFalse(dpm.isAdminActive(adminNoPerm));
377
378 // Change the target API level to MNC. Now it can be set as DA.
379 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
380 VERSION_CODES.M);
381 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
382 assertTrue(dpm.isAdminActive(adminNoPerm));
383
384 // TODO Test the "load from the file" case where DA will still be loaded even without
385 // BIND_DEVICE_ADMIN and target API is N.
386 }
387
388 /**
389 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700390 * {@link DevicePolicyManager#removeActiveAdmin}
391 */
392 public void testRemoveActiveAdmin_SecurityException() {
393 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
394
395 // Add admin.
396
397 dpm.setActiveAdmin(admin1, /* replace =*/ false);
398
399 assertTrue(dpm.isAdminActive(admin1));
400
401 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
402
403 // Directly call the DPMS method with a different userid, which should fail.
404 try {
405 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
406 fail("Didn't throw SecurityException");
407 } catch (SecurityException expected) {
408 }
409
410 // Try to remove active admin with a different caller userid should fail too, without
411 // having MANAGE_DEVICE_ADMINS.
412 mContext.callerPermissions.clear();
413
Makoto Onukid932f762015-09-29 16:53:38 -0700414 // Change the caller, and call into DPMS directly with a different user-id.
415
Makoto Onukif76b06a2015-09-22 15:03:44 -0700416 mContext.binder.callingUid = 1234567;
417 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700418 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700419 fail("Didn't throw SecurityException");
420 } catch (SecurityException expected) {
421 }
422 }
423
424 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800425 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
426 * (because we can't send the remove broadcast).
427 */
428 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
429 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
430
431 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
432
433 // Add admin.
434
435 dpm.setActiveAdmin(admin1, /* replace =*/ false);
436
437 assertTrue(dpm.isAdminActive(admin1));
438
439 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
440
441 // 1. User not unlocked.
442 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
443 .thenReturn(false);
444 try {
445 dpm.removeActiveAdmin(admin1);
446 fail("Didn't throw IllegalStateException");
447 } catch (IllegalStateException expected) {
448 MoreAsserts.assertContainsRegex(
449 "User must be running and unlocked", expected.getMessage());
450 }
451
452 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
453
454 // 2. User unlocked.
455 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
456 .thenReturn(true);
457
458 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700459 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800460 }
461
462 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700463 * Test for:
464 * {@link DevicePolicyManager#removeActiveAdmin}
465 */
Makoto Onukid932f762015-09-29 16:53:38 -0700466 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700467 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
468
469 // Add admin1.
470
471 dpm.setActiveAdmin(admin1, /* replace =*/ false);
472
473 assertTrue(dpm.isAdminActive(admin1));
474 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
475
476 // Different user, but should work, because caller has proper permissions.
477 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700478
479 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700480 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700481
482 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700483 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700484
485 // TODO DO Still can't be removed in this case.
486 }
487
488 /**
489 * Test for:
490 * {@link DevicePolicyManager#removeActiveAdmin}
491 */
492 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
493 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
494 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
495
496 // Add admin1.
497
498 dpm.setActiveAdmin(admin1, /* replace =*/ false);
499
500 assertTrue(dpm.isAdminActive(admin1));
501 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
502
503 // Broadcast from saveSettingsLocked().
504 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
505 MockUtils.checkIntentAction(
506 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
507 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
508
509 // Remove. No permissions, but same user, so it'll work.
510 mContext.callerPermissions.clear();
511 dpm.removeActiveAdmin(admin1);
512
Makoto Onukif76b06a2015-09-22 15:03:44 -0700513 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
514 MockUtils.checkIntentAction(
515 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
516 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
517 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700518 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700519 eq(dpms.mHandler),
520 eq(Activity.RESULT_OK),
521 isNull(String.class),
522 isNull(Bundle.class));
523
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700524 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700525
526 // Again broadcast from saveSettingsLocked().
527 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
528 MockUtils.checkIntentAction(
529 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
530 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
531
532 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700533 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700534
535 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000536 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700537 */
538 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000539 setDeviceOwner();
540
541 // Try to set a profile owner on the same user, which should fail.
542 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
543 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
544 try {
545 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
546 fail("IllegalStateException not thrown");
547 } catch (IllegalStateException expected) {
548 assertTrue("Message was: " + expected.getMessage(),
549 expected.getMessage().contains("already has a device owner"));
550 }
551
552 // DO admin can't be deactivated.
553 dpm.removeActiveAdmin(admin1);
554 assertTrue(dpm.isAdminActive(admin1));
555
556 // TODO Test getDeviceOwnerName() too. To do so, we need to change
557 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
558 }
559
560 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700561 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800562 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700563 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
564 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
565
Makoto Onukid932f762015-09-29 16:53:38 -0700566 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700567 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
568
Makoto Onukid932f762015-09-29 16:53:38 -0700569 // Make sure admin1 is installed on system user.
570 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700571
Makoto Onukic8a5a552015-11-19 14:29:12 -0800572 // Check various get APIs.
573 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
574
Makoto Onukib643fb02015-09-22 15:03:44 -0700575 // DO needs to be an DA.
576 dpm.setActiveAdmin(admin1, /* replace =*/ false);
577
578 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700579 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700580
Makoto Onukic8a5a552015-11-19 14:29:12 -0800581 // getDeviceOwnerComponent should return the admin1 component.
582 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
583 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
584
585 // Check various get APIs.
586 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
587
588 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
589 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
590 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
591 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
592
593 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
594
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000595 // Verify internal calls.
596 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
597 eq(admin1.getPackageName()));
598
Makoto Onukib643fb02015-09-22 15:03:44 -0700599 // TODO We should check if the caller has called clearCallerIdentity().
600 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
601 eq(UserHandle.USER_SYSTEM), eq(false));
602
603 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
604 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
605 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
606
Makoto Onukic8a5a552015-11-19 14:29:12 -0800607 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700608 }
609
Makoto Onukic8a5a552015-11-19 14:29:12 -0800610 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
611 final int origCallingUser = mContext.binder.callingUid;
612 final List origPermissions = new ArrayList(mContext.callerPermissions);
613 mContext.callerPermissions.clear();
614
615 mContext.callerPermissions.add(permission.MANAGE_USERS);
616
617 mContext.binder.callingUid = Process.SYSTEM_UID;
618
619 // TODO Test getDeviceOwnerName() too. To do so, we need to change
620 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
621 if (hasDeviceOwner) {
622 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
623 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
624 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
625
626 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
627 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
628 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
629 } else {
630 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
631 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
632 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
633
634 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
635 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
636 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
637 }
638
639 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
640 if (hasDeviceOwner) {
641 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
642 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
643 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
644
645 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
646 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
647 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
648 } else {
649 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
650 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
651 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
652
653 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
654 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
655 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
656 }
657
658 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
659 // Still with MANAGE_USERS.
660 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
661 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
662 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
663
664 if (hasDeviceOwner) {
665 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
666 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
667 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
668 } else {
669 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
670 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
671 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
672 }
673
674 mContext.binder.callingUid = Process.SYSTEM_UID;
675 mContext.callerPermissions.remove(permission.MANAGE_USERS);
676 // System can still call "OnAnyUser" without MANAGE_USERS.
677 if (hasDeviceOwner) {
678 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
679 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
680 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
681
682 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
683 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
684 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
685 } else {
686 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
687 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
688 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
689
690 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
691 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
692 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
693 }
694
695 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
696 // Still no MANAGE_USERS.
697 if (hasDeviceOwner) {
698 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
699 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
700 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
701 } else {
702 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
703 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
704 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
705 }
706
707 try {
708 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
709 fail();
710 } catch (SecurityException expected) {
711 }
712 try {
713 dpm.getDeviceOwnerComponentOnAnyUser();
714 fail();
715 } catch (SecurityException expected) {
716 }
717 try {
718 dpm.getDeviceOwnerUserId();
719 fail();
720 } catch (SecurityException expected) {
721 }
722 try {
723 dpm.getDeviceOwnerNameOnAnyUser();
724 fail();
725 } catch (SecurityException expected) {
726 }
727
728 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
729 // Still no MANAGE_USERS.
730 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
731 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
732 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
733
734 try {
735 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
736 fail();
737 } catch (SecurityException expected) {
738 }
739 try {
740 dpm.getDeviceOwnerComponentOnAnyUser();
741 fail();
742 } catch (SecurityException expected) {
743 }
744 try {
745 dpm.getDeviceOwnerUserId();
746 fail();
747 } catch (SecurityException expected) {
748 }
749 try {
750 dpm.getDeviceOwnerNameOnAnyUser();
751 fail();
752 } catch (SecurityException expected) {
753 }
754
755 // Restore.
756 mContext.binder.callingUid = origCallingUser;
757 mContext.callerPermissions.addAll(origPermissions);
758 }
759
760
Makoto Onukib643fb02015-09-22 15:03:44 -0700761 /**
762 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
763 */
764 public void testSetDeviceOwner_noSuchPackage() {
765 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800766 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700767 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
768 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
769
770 // Call from a process on the system user.
771 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
772
Makoto Onukib643fb02015-09-22 15:03:44 -0700773 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700774 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700775 fail("Didn't throw IllegalArgumentException");
776 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700777 assertTrue("Message was: " + expected.getMessage(),
778 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700779 }
780 }
781
782 public void testSetDeviceOwner_failures() throws Exception {
783 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
784 }
785
Makoto Onukia52562c2015-10-01 16:12:31 -0700786 public void testClearDeviceOwner() throws Exception {
787 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800788 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700789 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
790 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
791
792 // Set admin1 as a DA to the secondary user.
793 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
794
795 dpm.setActiveAdmin(admin1, /* replace =*/ false);
796
797 // Set admin 1 as the DO to the system user.
798
799 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
800 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
801 dpm.setActiveAdmin(admin1, /* replace =*/ false);
802 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
803
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000804 // Verify internal calls.
805 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
806 eq(admin1.getPackageName()));
807
Makoto Onukic8a5a552015-11-19 14:29:12 -0800808 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700809
Makoto Onuki90b89652016-01-28 14:44:18 -0800810 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
811
812 assertTrue(dpm.isAdminActive(admin1));
813 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
814
Makoto Onukia52562c2015-10-01 16:12:31 -0700815 // Set up other mocks.
816 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
817
818 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700819 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700820 eq(admin1.getPackageName()),
821 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800822
823 // But first pretend the user is locked. Then it should fail.
824 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
825 try {
826 dpm.clearDeviceOwnerApp(admin1.getPackageName());
827 fail("Didn't throw IllegalStateException");
828 } catch (IllegalStateException expected) {
829 MoreAsserts.assertContainsRegex(
830 "User must be running and unlocked", expected.getMessage());
831 }
832
833 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800834 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700835 dpm.clearDeviceOwnerApp(admin1.getPackageName());
836
837 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800838 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700839
Makoto Onuki90b89652016-01-28 14:44:18 -0800840 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
841 eq(UserHandle.USER_SYSTEM),
842 MockUtils.checkUserRestrictions(),
843 MockUtils.checkUserRestrictions()
844 );
845
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700846 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100847
848 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
849 // and once for clearing it.
850 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
851 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
852 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700853 // TODO Check other calls.
854 }
855
856 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
857 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800858 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700859 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
860 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
861
862 // Set admin1 as a DA to the secondary user.
863 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
864
865 dpm.setActiveAdmin(admin1, /* replace =*/ false);
866
867 // Set admin 1 as the DO to the system user.
868
869 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
870 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
871 dpm.setActiveAdmin(admin1, /* replace =*/ false);
872 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
873
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000874 // Verify internal calls.
875 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
876 eq(admin1.getPackageName()));
877
Makoto Onukic8a5a552015-11-19 14:29:12 -0800878 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700879
880 // Now call clear from the secondary user, which should throw.
881 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
882
883 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700884 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700885 eq(admin1.getPackageName()),
886 anyInt());
887 try {
888 dpm.clearDeviceOwnerApp(admin1.getPackageName());
889 fail("Didn't throw");
890 } catch (SecurityException e) {
891 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
892 }
893
Makoto Onukic8a5a552015-11-19 14:29:12 -0800894 // DO shouldn't be removed.
895 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700896 }
897
Makoto Onukib643fb02015-09-22 15:03:44 -0700898 public void testSetProfileOwner() throws Exception {
899 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700900
Makoto Onuki90b89652016-01-28 14:44:18 -0800901 // PO admin can't be deactivated.
902 dpm.removeActiveAdmin(admin1);
903 assertTrue(dpm.isAdminActive(admin1));
904
Makoto Onuki803d6752015-10-30 12:58:39 -0700905 // Try setting DO on the same user, which should fail.
906 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
907 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
908 try {
909 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
910 fail("IllegalStateException not thrown");
911 } catch (IllegalStateException expected) {
912 assertTrue("Message was: " + expected.getMessage(),
913 expected.getMessage().contains("already has a profile owner"));
914 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700915 }
916
Makoto Onuki90b89652016-01-28 14:44:18 -0800917 public void testClearProfileOwner() throws Exception {
918 setAsProfileOwner(admin1);
919
920 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
921
922 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
923 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
924
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800925 // First try when the user is locked, which should fail.
926 when(mContext.userManager.isUserUnlocked(anyInt()))
927 .thenReturn(false);
928 try {
929 dpm.clearProfileOwner(admin1);
930 fail("Didn't throw IllegalStateException");
931 } catch (IllegalStateException expected) {
932 MoreAsserts.assertContainsRegex(
933 "User must be running and unlocked", expected.getMessage());
934 }
935 // Clear, really.
936 when(mContext.userManager.isUserUnlocked(anyInt()))
937 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800938 dpm.clearProfileOwner(admin1);
939
940 // Check
941 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700942 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -0800943 }
944
Makoto Onukib643fb02015-09-22 15:03:44 -0700945 public void testSetProfileOwner_failures() throws Exception {
946 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
947 }
948
Makoto Onukia52562c2015-10-01 16:12:31 -0700949 public void testGetDeviceOwnerAdminLocked() throws Exception {
950 checkDeviceOwnerWithMultipleDeviceAdmins();
951 }
952
953 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
954 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
955 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
956 // make sure it gets the right component from the right user.
957
958 final int ANOTHER_USER_ID = 100;
959 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
960
961 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
962
963 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800964 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700965 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
966 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
967
968 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
969
Victor Change29cd472016-03-02 20:57:42 +0000970 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
971
Makoto Onukia52562c2015-10-01 16:12:31 -0700972 // Make sure the admin packge is installed to each user.
973 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
974 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
975
976 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
977 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
978
979 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
980
981
982 // Set active admins to the users.
983 dpm.setActiveAdmin(admin1, /* replace =*/ false);
984 dpm.setActiveAdmin(admin3, /* replace =*/ false);
985
986 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
987 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
988
989 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
990
991 // Set DO on the first non-system user.
992 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
993 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
994
Makoto Onukic8a5a552015-11-19 14:29:12 -0800995 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -0700996
997 // Then check getDeviceOwnerAdminLocked().
998 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
999 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1000 }
1001
1002 /**
1003 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001004 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1005 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001006 *
1007 * We didn't use to persist the DO component class name, but now we do, and the above method
1008 * finds the right component from a package name upon migration.
1009 */
1010 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001011 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001012 checkDeviceOwnerWithMultipleDeviceAdmins();
1013
1014 // Overwrite the device owner setting and clears the clas name.
1015 dpms.mOwners.setDeviceOwner(
1016 new ComponentName(admin2.getPackageName(), ""),
1017 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1018 dpms.mOwners.writeDeviceOwner();
1019
1020 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001021 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001022
1023 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001024 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1025 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001026 initializeDpms();
1027
1028 // Now the DO component name is a full name.
1029 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1030 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001031 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001032 }
1033
Makoto Onukib643fb02015-09-22 15:03:44 -07001034 public void testSetGetApplicationRestriction() {
1035 setAsProfileOwner(admin1);
1036
1037 {
1038 Bundle rest = new Bundle();
1039 rest.putString("KEY_STRING", "Foo1");
1040 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1041 }
1042
1043 {
1044 Bundle rest = new Bundle();
1045 rest.putString("KEY_STRING", "Foo2");
1046 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1047 }
1048
1049 {
1050 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1051 assertNotNull(returned);
1052 assertEquals(returned.size(), 1);
1053 assertEquals(returned.get("KEY_STRING"), "Foo1");
1054 }
1055
1056 {
1057 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1058 assertNotNull(returned);
1059 assertEquals(returned.size(), 1);
1060 assertEquals(returned.get("KEY_STRING"), "Foo2");
1061 }
1062
1063 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1064 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1065 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001066
Esteban Talaverabf60f722015-12-10 16:26:44 +00001067 public void testApplicationRestrictionsManagingApp() throws Exception {
1068 setAsProfileOwner(admin1);
1069
Rubin Xued1928a2016-02-11 17:23:06 +00001070 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001071 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1072 final int appRestrictionsManagerAppId = 20987;
1073 final int appRestrictionsManagerUid = UserHandle.getUid(
1074 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001075 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001076 eq(appRestrictionsManagerPackage),
1077 eq(DpmMockContext.CALLER_USER_HANDLE));
1078 mContext.binder.callingUid = appRestrictionsManagerUid;
1079
Rubin Xued1928a2016-02-11 17:23:06 +00001080 final PackageInfo pi = new PackageInfo();
1081 pi.applicationInfo = new ApplicationInfo();
1082 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1083 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1084 eq(appRestrictionsManagerPackage),
1085 anyInt(),
1086 eq(DpmMockContext.CALLER_USER_HANDLE));
1087
Esteban Talaverabf60f722015-12-10 16:26:44 +00001088 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1089 // delegated that permission yet.
1090 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1091 Bundle rest = new Bundle();
1092 rest.putString("KEY_STRING", "Foo1");
1093 try {
1094 dpm.setApplicationRestrictions(null, "pkg1", rest);
1095 fail("Didn't throw expected SecurityException");
1096 } catch (SecurityException expected) {
1097 MoreAsserts.assertContainsRegex(
1098 "caller cannot manage application restrictions", expected.getMessage());
1099 }
1100 try {
1101 dpm.getApplicationRestrictions(null, "pkg1");
1102 fail("Didn't throw expected SecurityException");
1103 } catch (SecurityException expected) {
1104 MoreAsserts.assertContainsRegex(
1105 "caller cannot manage application restrictions", expected.getMessage());
1106 }
1107
1108 // Check via the profile owner that no restrictions were set.
1109 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1110 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1111
Rubin Xued1928a2016-02-11 17:23:06 +00001112 // Check the API does not allow setting a non-existent package
1113 try {
1114 dpm.setApplicationRestrictionsManagingPackage(admin1,
1115 nonExistAppRestrictionsManagerPackage);
1116 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001117 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001118 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001119 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001120 }
1121
Esteban Talaverabf60f722015-12-10 16:26:44 +00001122 // Let appRestrictionsManagerPackage manage app restrictions
1123 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1124 assertEquals(appRestrictionsManagerPackage,
1125 dpm.getApplicationRestrictionsManagingPackage(admin1));
1126
1127 // Now that package should be able to set and retrieve app restrictions.
1128 mContext.binder.callingUid = appRestrictionsManagerUid;
1129 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1130 dpm.setApplicationRestrictions(null, "pkg1", rest);
1131 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1132 assertEquals(1, returned.size(), 1);
1133 assertEquals("Foo1", returned.get("KEY_STRING"));
1134
1135 // The same app running on a separate user shouldn't be able to manage app restrictions.
1136 mContext.binder.callingUid = UserHandle.getUid(
1137 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1138 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1139 try {
1140 dpm.setApplicationRestrictions(null, "pkg1", rest);
1141 fail("Didn't throw expected SecurityException");
1142 } catch (SecurityException expected) {
1143 MoreAsserts.assertContainsRegex(
1144 "caller cannot manage application restrictions", expected.getMessage());
1145 }
1146
1147 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1148 // too.
1149 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1150 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1151 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1152 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1153
1154 // Removing the ability for the package to manage app restrictions.
1155 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1156 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1157 mContext.binder.callingUid = appRestrictionsManagerUid;
1158 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1159 try {
1160 dpm.setApplicationRestrictions(null, "pkg1", null);
1161 fail("Didn't throw expected SecurityException");
1162 } catch (SecurityException expected) {
1163 MoreAsserts.assertContainsRegex(
1164 "caller cannot manage application restrictions", expected.getMessage());
1165 }
1166 }
1167
Makoto Onukia4f11972015-10-01 13:19:58 -07001168 public void testSetUserRestriction_asDo() throws Exception {
1169 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001170 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001171 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1172 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1173
1174 // First, set DO.
1175
1176 // Call from a process on the system user.
1177 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1178
1179 // Make sure admin1 is installed on system user.
1180 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001181
1182 // Call.
1183 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001184 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001185 UserHandle.USER_SYSTEM));
1186
Makoto Onuki068c54a2015-10-13 14:34:03 -07001187 DpmTestUtils.assertRestrictions(
1188 DpmTestUtils.newRestrictions(),
1189 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1190 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001191 DpmTestUtils.assertRestrictions(
1192 DpmTestUtils.newRestrictions(),
1193 dpm.getUserRestrictions(admin1)
1194 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001195
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001196 reset(mContext.userManagerInternal);
1197
1198 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1199 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1200 eq(UserHandle.USER_SYSTEM),
1201 MockUtils.checkUserRestrictions(),
1202 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001203 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001204 reset(mContext.userManagerInternal);
1205
Makoto Onukia4f11972015-10-01 13:19:58 -07001206 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001207 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1208 eq(UserHandle.USER_SYSTEM),
1209 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1210 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1211 );
1212 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001213
Makoto Onuki068c54a2015-10-13 14:34:03 -07001214 DpmTestUtils.assertRestrictions(
1215 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001216 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001217 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1218 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001219 DpmTestUtils.assertRestrictions(
1220 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001221 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001222 dpm.getUserRestrictions(admin1)
1223 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001224
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001225 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1226 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1227 eq(UserHandle.USER_SYSTEM),
1228 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1229 MockUtils.checkUserRestrictions()
1230 );
1231 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001232
Makoto Onuki068c54a2015-10-13 14:34:03 -07001233 DpmTestUtils.assertRestrictions(
1234 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1235 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1236 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001237 DpmTestUtils.assertRestrictions(
1238 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1239 dpm.getUserRestrictions(admin1)
1240 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001241
1242 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001243 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1244 eq(UserHandle.USER_SYSTEM),
1245 MockUtils.checkUserRestrictions(),
1246 MockUtils.checkUserRestrictions()
1247 );
1248 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001249
Makoto Onuki068c54a2015-10-13 14:34:03 -07001250 DpmTestUtils.assertRestrictions(
1251 DpmTestUtils.newRestrictions(),
1252 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1253 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001254 DpmTestUtils.assertRestrictions(
1255 DpmTestUtils.newRestrictions(),
1256 dpm.getUserRestrictions(admin1)
1257 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001258
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001259 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1260 // DO sets them, the scope is global.
1261 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1262 reset(mContext.userManagerInternal);
1263 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1264 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1265 eq(UserHandle.USER_SYSTEM),
1266 MockUtils.checkUserRestrictions(),
1267 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1268 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1269 );
1270 reset(mContext.userManagerInternal);
1271
1272 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1273 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1274
1275
1276 // More tests.
1277 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1278 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1279 eq(UserHandle.USER_SYSTEM),
1280 MockUtils.checkUserRestrictions(),
1281 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1282 );
1283 reset(mContext.userManagerInternal);
1284
1285 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1286 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1287 eq(UserHandle.USER_SYSTEM),
1288 MockUtils.checkUserRestrictions(),
1289 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1290 UserManager.DISALLOW_ADD_USER)
1291 );
1292 reset(mContext.userManagerInternal);
1293
1294 dpm.setCameraDisabled(admin1, true);
1295 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1296 eq(UserHandle.USER_SYSTEM),
1297 // DISALLOW_CAMERA will be applied to both local and global.
1298 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1299 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1300 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1301 );
1302 reset(mContext.userManagerInternal);
1303
1304 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1305 // locally.
1306 dpm.setCameraDisabled(admin1, false);
1307 reset(mContext.userManagerInternal);
1308
1309 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1310 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1311 dpm.setCameraDisabled(admin2, true);
1312
1313 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1314 eq(UserHandle.USER_SYSTEM),
1315 // DISALLOW_CAMERA will be applied to both local and global.
1316 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1317 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1318 UserManager.DISALLOW_ADD_USER)
1319 );
1320 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001321 // TODO Make sure restrictions are written to the file.
1322 }
1323
1324 public void testSetUserRestriction_asPo() {
1325 setAsProfileOwner(admin1);
1326
Makoto Onuki068c54a2015-10-13 14:34:03 -07001327 DpmTestUtils.assertRestrictions(
1328 DpmTestUtils.newRestrictions(),
1329 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1330 .ensureUserRestrictions()
1331 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001332
1333 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001334 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1335 eq(DpmMockContext.CALLER_USER_HANDLE),
1336 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1337 isNull(Bundle.class)
1338 );
1339 reset(mContext.userManagerInternal);
1340
Makoto Onukia4f11972015-10-01 13:19:58 -07001341 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001342 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1343 eq(DpmMockContext.CALLER_USER_HANDLE),
1344 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1345 UserManager.DISALLOW_OUTGOING_CALLS),
1346 isNull(Bundle.class)
1347 );
1348 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001349
Makoto Onuki068c54a2015-10-13 14:34:03 -07001350 DpmTestUtils.assertRestrictions(
1351 DpmTestUtils.newRestrictions(
1352 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1353 UserManager.DISALLOW_OUTGOING_CALLS
1354 ),
1355 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1356 .ensureUserRestrictions()
1357 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001358 DpmTestUtils.assertRestrictions(
1359 DpmTestUtils.newRestrictions(
1360 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1361 UserManager.DISALLOW_OUTGOING_CALLS
1362 ),
1363 dpm.getUserRestrictions(admin1)
1364 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001365
1366 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001367 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1368 eq(DpmMockContext.CALLER_USER_HANDLE),
1369 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1370 isNull(Bundle.class)
1371 );
1372 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001373
1374 DpmTestUtils.assertRestrictions(
1375 DpmTestUtils.newRestrictions(
1376 UserManager.DISALLOW_OUTGOING_CALLS
1377 ),
1378 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1379 .ensureUserRestrictions()
1380 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001381 DpmTestUtils.assertRestrictions(
1382 DpmTestUtils.newRestrictions(
1383 UserManager.DISALLOW_OUTGOING_CALLS
1384 ),
1385 dpm.getUserRestrictions(admin1)
1386 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001387
1388 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001389 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1390 eq(DpmMockContext.CALLER_USER_HANDLE),
1391 MockUtils.checkUserRestrictions(),
1392 isNull(Bundle.class)
1393 );
1394 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001395
Makoto Onuki068c54a2015-10-13 14:34:03 -07001396 DpmTestUtils.assertRestrictions(
1397 DpmTestUtils.newRestrictions(),
1398 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1399 .ensureUserRestrictions()
1400 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001401 DpmTestUtils.assertRestrictions(
1402 DpmTestUtils.newRestrictions(),
1403 dpm.getUserRestrictions(admin1)
1404 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001405
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001406 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1407 // though when DO sets them they'll be applied globally.
1408 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1409 reset(mContext.userManagerInternal);
1410 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1411 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1412 eq(DpmMockContext.CALLER_USER_HANDLE),
1413 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1414 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1415 isNull(Bundle.class)
1416 );
1417 reset(mContext.userManagerInternal);
1418
1419 dpm.setCameraDisabled(admin1, true);
1420 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1421 eq(DpmMockContext.CALLER_USER_HANDLE),
1422 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1423 UserManager.DISALLOW_ADJUST_VOLUME,
1424 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1425 isNull(Bundle.class)
1426 );
1427 reset(mContext.userManagerInternal);
1428
Makoto Onukia4f11972015-10-01 13:19:58 -07001429 // TODO Make sure restrictions are written to the file.
1430 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001431
1432 public void testGetMacAddress() throws Exception {
1433 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1434 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1435 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1436
1437 // In this test, change the caller user to "system".
1438 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1439
1440 // Make sure admin1 is installed on system user.
1441 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1442
1443 // Test 1. Caller doesn't have DO or DA.
1444 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001445 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001446 fail();
1447 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001448 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001449 }
1450
1451 // DO needs to be an DA.
1452 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1453 assertTrue(dpm.isAdminActive(admin1));
1454
1455 // Test 2. Caller has DA, but not DO.
1456 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001457 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001458 fail();
1459 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001460 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001461 }
1462
1463 // Test 3. Caller has PO, but not DO.
1464 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1465 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001466 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001467 fail();
1468 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001469 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001470 }
1471
1472 // Remove PO.
1473 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001474 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001475 // Test 4, Caller is DO now.
1476 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1477
1478 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001479 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001480
1481 // 4-2. Returns WifiInfo, but with the default MAC.
1482 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001483 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001484
1485 // 4-3. With a real MAC address.
1486 final WifiInfo wi = new WifiInfo();
1487 wi.setMacAddress("11:22:33:44:55:66");
1488 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001489 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001490 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001491
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001492 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001493 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1494 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1495
1496 // In this test, change the caller user to "system".
1497 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1498
1499 // Make sure admin1 is installed on system user.
1500 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1501
1502 // Set admin1 as DA.
1503 dpm.setActiveAdmin(admin1, false);
1504 assertTrue(dpm.isAdminActive(admin1));
1505 try {
1506 dpm.reboot(admin1);
1507 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1508 } catch (SecurityException expected) {
1509 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1510 }
1511
1512 // Set admin1 as PO.
1513 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1514 try {
1515 dpm.reboot(admin1);
1516 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1517 } catch (SecurityException expected) {
1518 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1519 }
1520
1521 // Remove PO and add DO.
1522 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001523 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001524 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1525
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001526 // admin1 is DO.
1527 // Set current call state of device to ringing.
1528 when(mContext.telephonyManager.getCallState())
1529 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1530 try {
1531 dpm.reboot(admin1);
1532 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1533 } catch (IllegalStateException expected) {
1534 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1535 }
1536
1537 // Set current call state of device to dialing/active.
1538 when(mContext.telephonyManager.getCallState())
1539 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1540 try {
1541 dpm.reboot(admin1);
1542 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1543 } catch (IllegalStateException expected) {
1544 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1545 }
1546
1547 // Set current call state of device to idle.
1548 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001549 dpm.reboot(admin1);
1550 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001551
1552 public void testSetGetSupportText() {
1553 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1554 dpm.setActiveAdmin(admin1, true);
1555 dpm.setActiveAdmin(admin2, true);
1556 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1557
1558 // Null default support messages.
1559 {
1560 assertNull(dpm.getLongSupportMessage(admin1));
1561 assertNull(dpm.getShortSupportMessage(admin1));
1562 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1563 assertNull(dpm.getShortSupportMessageForUser(admin1,
1564 DpmMockContext.CALLER_USER_HANDLE));
1565 assertNull(dpm.getLongSupportMessageForUser(admin1,
1566 DpmMockContext.CALLER_USER_HANDLE));
1567 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1568 }
1569
1570 // Only system can call the per user versions.
1571 {
1572 try {
1573 dpm.getShortSupportMessageForUser(admin1,
1574 DpmMockContext.CALLER_USER_HANDLE);
1575 fail("Only system should be able to call getXXXForUser versions");
1576 } catch (SecurityException expected) {
1577 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1578 }
1579 try {
1580 dpm.getLongSupportMessageForUser(admin1,
1581 DpmMockContext.CALLER_USER_HANDLE);
1582 fail("Only system should be able to call getXXXForUser versions");
1583 } catch (SecurityException expected) {
1584 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1585 }
1586 }
1587
1588 // Can't set message for admin in another uid.
1589 {
1590 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1591 try {
1592 dpm.setShortSupportMessage(admin1, "Some text");
1593 fail("Admins should only be able to change their own support text.");
1594 } catch (SecurityException expected) {
1595 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1596 }
1597 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1598 }
1599
1600 // Set/Get short returns what it sets and other admins text isn't changed.
1601 {
1602 final String supportText = "Some text to test with.";
1603 dpm.setShortSupportMessage(admin1, supportText);
1604 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1605 assertNull(dpm.getLongSupportMessage(admin1));
1606 assertNull(dpm.getShortSupportMessage(admin2));
1607
1608 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1609 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1610 DpmMockContext.CALLER_USER_HANDLE));
1611 assertNull(dpm.getShortSupportMessageForUser(admin2,
1612 DpmMockContext.CALLER_USER_HANDLE));
1613 assertNull(dpm.getLongSupportMessageForUser(admin1,
1614 DpmMockContext.CALLER_USER_HANDLE));
1615 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1616
1617 dpm.setShortSupportMessage(admin1, null);
1618 assertNull(dpm.getShortSupportMessage(admin1));
1619 }
1620
1621 // Set/Get long returns what it sets and other admins text isn't changed.
1622 {
1623 final String supportText = "Some text to test with.\nWith more text.";
1624 dpm.setLongSupportMessage(admin1, supportText);
1625 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1626 assertNull(dpm.getShortSupportMessage(admin1));
1627 assertNull(dpm.getLongSupportMessage(admin2));
1628
1629 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1630 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1631 DpmMockContext.CALLER_USER_HANDLE));
1632 assertNull(dpm.getLongSupportMessageForUser(admin2,
1633 DpmMockContext.CALLER_USER_HANDLE));
1634 assertNull(dpm.getShortSupportMessageForUser(admin1,
1635 DpmMockContext.CALLER_USER_HANDLE));
1636 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1637
1638 dpm.setLongSupportMessage(admin1, null);
1639 assertNull(dpm.getLongSupportMessage(admin1));
1640 }
1641 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001642
1643 /**
1644 * Test for:
1645 * {@link DevicePolicyManager#setAffiliationIds}
1646 * {@link DevicePolicyManager#isAffiliatedUser}
1647 */
1648 public void testUserAffiliation() throws Exception {
1649 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1650 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1651 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1652
1653 // Check that the system user is unaffiliated.
1654 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1655 assertFalse(dpm.isAffiliatedUser());
1656
1657 // Set a device owner on the system user. Check that the system user becomes affiliated.
1658 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1659 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1660 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1661 assertTrue(dpm.isAffiliatedUser());
1662
1663 // Install a profile owner whose package name matches the device owner on a test user. Check
1664 // that the test user is unaffiliated.
1665 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1666 setAsProfileOwner(admin2);
1667 assertFalse(dpm.isAffiliatedUser());
1668
1669 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1670 // unaffiliated.
1671 final Set<String> userAffiliationIds = new ArraySet<>();
1672 userAffiliationIds.add("red");
1673 userAffiliationIds.add("green");
1674 userAffiliationIds.add("blue");
1675 dpm.setAffiliationIds(admin2, userAffiliationIds);
1676 assertFalse(dpm.isAffiliatedUser());
1677
1678 // Have the device owner specify a set of affiliation ids that do not intersect with those
1679 // specified by the profile owner. Check that the test user remains unaffiliated.
1680 final Set<String> deviceAffiliationIds = new ArraySet<>();
1681 deviceAffiliationIds.add("cyan");
1682 deviceAffiliationIds.add("yellow");
1683 deviceAffiliationIds.add("magenta");
1684 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1685 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
1686 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1687 assertFalse(dpm.isAffiliatedUser());
1688
1689 // Have the profile owner specify a set of affiliation ids that intersect with those
1690 // specified by the device owner. Check that the test user becomes affiliated.
1691 userAffiliationIds.add("yellow");
1692 dpm.setAffiliationIds(admin2, userAffiliationIds);
1693 assertTrue(dpm.isAffiliatedUser());
1694
1695 // Change the profile owner to one whose package name does not match the device owner. Check
1696 // that the test user is not affiliated anymore.
1697 dpm.clearProfileOwner(admin2);
1698 final ComponentName admin = new ComponentName("test", "test");
Makoto Onuki184db602016-02-17 15:35:01 -08001699
1700 setUpPackageManagerForFakeAdmin(admin, DpmMockContext.CALLER_UID,
1701 /* enabledSetting =*/ PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
1702 /* appTargetSdk = */ null, admin2);
1703
1704 dpm.setActiveAdmin(admin, /* refreshing =*/ true, DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001705 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1706 assertFalse(dpm.isAffiliatedUser());
1707
1708 // Check that the system user remains affiliated.
1709 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1710 assertTrue(dpm.isAffiliatedUser());
1711 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001712
1713 public void testGetUserProvisioningState_defaultResult() {
1714 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1715 }
1716
1717 public void testSetUserProvisioningState_permission() throws Exception {
1718 setupProfileOwner();
1719 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1720
1721 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1722 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1723 }
1724
1725 public void testSetUserProvisioningState_unprivileged() throws Exception {
1726 setupProfileOwner();
1727 try {
1728 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1729 DpmMockContext.CALLER_USER_HANDLE);
1730 fail("Expected SecurityException");
1731 } catch (SecurityException expected) {
1732 }
1733 }
1734
1735 public void testSetUserProvisioningState_noManagement() {
1736 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1737 try {
1738 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1739 DpmMockContext.CALLER_USER_HANDLE);
1740 fail("IllegalStateException expected");
1741 } catch (IllegalStateException e) {
1742 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1743 e.getMessage());
1744 }
1745 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1746 }
1747
1748 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1749 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1750 setupDeviceOwner();
1751 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1752
1753 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1754 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1755 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1756 }
1757
1758 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1759 throws Exception {
1760 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1761 setupDeviceOwner();
1762 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1763
1764 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1765 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1766 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1767 }
1768
1769 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1770 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1771 setupDeviceOwner();
1772 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1773
1774 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1775 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1776 }
1777
1778 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1779 throws Exception {
1780 setupProfileOwner();
1781 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1782
1783 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1784 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1785 DevicePolicyManager.STATE_USER_UNMANAGED);
1786 }
1787
1788 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1789 throws Exception {
1790 setupProfileOwner();
1791 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1792
1793 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1794 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1795 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1796 }
1797
1798 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1799 setupProfileOwner();
1800 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1801
1802 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1803 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1804 }
1805
1806 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
1807 setupProfileOwner();
1808 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1809
1810 try {
1811 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1812 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1813 DevicePolicyManager.STATE_USER_UNMANAGED);
1814 fail("Expected IllegalStateException");
1815 } catch (IllegalStateException e) {
1816 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1817 e.getMessage());
1818 }
1819 }
1820
1821 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
1822 throws Exception {
1823 setupProfileOwner();
1824 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1825
1826 try {
1827 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1828 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1829 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
1830 fail("Expected IllegalStateException");
1831 } catch (IllegalStateException e) {
1832 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1833 e.getMessage());
1834 }
1835 }
1836
1837 private void exerciseUserProvisioningTransitions(int userId, int... states) {
1838 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1839 for (int state : states) {
1840 dpm.setUserProvisioningState(state, userId);
1841 assertEquals(state, dpm.getUserProvisioningState());
1842 }
1843 }
1844
1845 private void setupProfileOwner() throws Exception {
1846 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1847
1848 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1849 dpm.setActiveAdmin(admin1, false);
1850 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
1851
1852 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1853 }
1854
1855 private void setupDeviceOwner() throws Exception {
1856 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1857
1858 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1859 dpm.setActiveAdmin(admin1, false);
1860 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1861
1862 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1863 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001864
1865 public void testSetMaximumTimeToLock() {
1866 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1867
1868 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1869 dpm.setActiveAdmin(admin2, /* replace =*/ false);
1870
1871 reset(mMockContext.powerManagerInternal);
1872 reset(mMockContext.settings);
1873
1874 dpm.setMaximumTimeToLock(admin1, 0);
1875 verifyScreenTimeoutCall(null, false);
1876 reset(mMockContext.powerManagerInternal);
1877 reset(mMockContext.settings);
1878
1879 dpm.setMaximumTimeToLock(admin1, 1);
1880 verifyScreenTimeoutCall(1, true);
1881 reset(mMockContext.powerManagerInternal);
1882 reset(mMockContext.settings);
1883
1884 dpm.setMaximumTimeToLock(admin2, 10);
1885 verifyScreenTimeoutCall(null, false);
1886 reset(mMockContext.powerManagerInternal);
1887 reset(mMockContext.settings);
1888
1889 dpm.setMaximumTimeToLock(admin1, 5);
1890 verifyScreenTimeoutCall(5, true);
1891 reset(mMockContext.powerManagerInternal);
1892 reset(mMockContext.settings);
1893
1894 dpm.setMaximumTimeToLock(admin2, 4);
1895 verifyScreenTimeoutCall(4, true);
1896 reset(mMockContext.powerManagerInternal);
1897 reset(mMockContext.settings);
1898
1899 dpm.setMaximumTimeToLock(admin1, 0);
1900 reset(mMockContext.powerManagerInternal);
1901 reset(mMockContext.settings);
1902
1903 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
1904 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1905 reset(mMockContext.powerManagerInternal);
1906 reset(mMockContext.settings);
1907
1908 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
1909 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1910 reset(mMockContext.powerManagerInternal);
1911 reset(mMockContext.settings);
1912
1913 dpm.setMaximumTimeToLock(admin2, 10);
1914 verifyScreenTimeoutCall(10, true);
1915 reset(mMockContext.powerManagerInternal);
1916 reset(mMockContext.settings);
1917
1918 // There's no restriction; shold be set to MAX.
1919 dpm.setMaximumTimeToLock(admin2, 0);
1920 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
1921 }
1922
Michal Karpinski943aabd2016-10-06 11:09:25 +01001923 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
1924 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1925 setupDeviceOwner();
1926 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1927
1928 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
1929 final long ONE_MINUTE = 60 * 1000;
1930
1931 // aggregation should be the default if unset by any admin
1932 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1933 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1934
1935 // admin not participating by default
1936 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1937
1938 //clamping from the top
1939 dpm.setRequiredStrongAuthTimeout(admin1,
1940 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1941 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
1942 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1943 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1944 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1945
1946 // 0 means default
1947 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1948 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1949 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1950 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1951
1952 // clamping from the bottom
1953 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
1954 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1955 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1956
1957 // value within range
1958 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1959 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1960 + ONE_MINUTE);
1961 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1962 + ONE_MINUTE);
1963
1964 // reset to default
1965 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1966 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1967 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1968 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1969
1970 // negative value
1971 try {
1972 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
1973 fail("Didn't throw IllegalArgumentException");
1974 } catch (IllegalArgumentException iae) {
1975 }
1976 }
1977
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001978 private void verifyScreenTimeoutCall(Integer expectedTimeout,
1979 boolean shouldStayOnWhilePluggedInBeCleared) {
1980 if (expectedTimeout == null) {
1981 verify(mMockContext.powerManagerInternal, times(0))
1982 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
1983 } else {
1984 verify(mMockContext.powerManagerInternal, times(1))
1985 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
1986 }
1987 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
1988 // UnfinishedVerificationException.
1989 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001990
Victor Chang3e794af2016-03-04 13:48:17 +00001991 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
1992 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
1993 .thenReturn(false);
1994 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
1995 .thenReturn(false);
1996 initializeDpms();
1997 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
1998 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
1999 .thenReturn(true);
2000 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2001
2002 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2003
2004 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2005 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2006 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2007 false);
2008 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2009 }
2010
2011 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2012 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2013 .thenReturn(false);
2014 initializeDpms();
2015 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2016 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2017 .thenReturn(true);
2018 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2019
2020 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2021
2022 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2023 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2024 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2025 false);
2026 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2027
2028 // Test again when split user is on
2029 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2030 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2031 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2032 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2033 true);
2034 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2035 }
2036
2037 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2038 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2039 .thenReturn(true);
2040 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2041 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2042 .thenReturn(true);
2043 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2044
2045 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2046
2047 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2048 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2049 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2050 false /* because of non-split user */);
2051 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2052 false /* because of non-split user */);
2053 }
2054
2055 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2056 throws Exception {
2057 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2058 .thenReturn(true);
2059 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2060 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2061 .thenReturn(true);
2062 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2063
2064 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2065
2066 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2067 false/* because of completed device setup */);
2068 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2069 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2070 false/* because of non-split user */);
2071 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2072 false/* because of non-split user */);
2073 }
2074
2075 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2076 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2077 .thenReturn(true);
2078 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2079 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2080 .thenReturn(false);
2081 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2082
2083 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2084
2085 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2086 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2087 false /* because canAddMoreManagedProfiles returns false */);
2088 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2089 true);
2090 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2091 false/* because calling uid is system user */);
2092
2093 }
2094
2095 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2096 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2097 .thenReturn(true);
2098 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2099 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2100 .thenReturn(false);
2101 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2102
2103 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2104
2105 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2106 true/* it's undefined behavior. Can be changed into false in the future */);
2107 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2108 false /* because canAddMoreManagedProfiles returns false */);
2109 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2110 true/* it's undefined behavior. Can be changed into false in the future */);
2111 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2112 false/* because calling uid is system user */);
2113 }
2114
2115 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2116 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2117 .thenReturn(true);
2118 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2119 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2120 true)).thenReturn(true);
2121 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2122
2123 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2124
2125 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2126 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2127 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2128 true);
2129 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
2130
2131 }
2132
2133 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2134 throws Exception {
2135 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2136 .thenReturn(true);
2137 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2138 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2139 true)).thenReturn(true);
2140 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2141
2142 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2143
2144 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2145 true/* it's undefined behavior. Can be changed into false in the future */);
2146 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2147 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2148 true/* it's undefined behavior. Can be changed into false in the future */);
2149 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2150 false/* because user setup completed */);
2151 }
2152
2153 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2154 throws Exception {
2155 setDeviceOwner();
2156
2157 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2158 .thenReturn(true);
2159 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2160 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2161 .thenReturn(false);
2162 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2163
2164 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2165
2166 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2167 false /* can't provision managed profile on system user */);
2168 }
2169
2170 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2171 throws Exception {
2172 setDeviceOwner();
2173
2174 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2175 .thenReturn(true);
2176 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2177 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2178 true)).thenReturn(true);
2179 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2180
2181 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2182
2183 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2184 }
2185
Victor Chang3577ed22016-08-25 18:49:26 +01002186 public void testForceUpdateUserSetupComplete_permission() {
2187 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2188 try {
2189 dpm.forceUpdateUserSetupComplete();
2190 fail("Didn't throw SecurityException");
2191 } catch (SecurityException expected) {
2192 }
2193 }
2194
2195 public void testForceUpdateUserSetupComplete_systemUser() {
2196 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2197 // GIVEN calling from user 20
2198 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2199 try {
2200 dpm.forceUpdateUserSetupComplete();
2201 fail("Didn't throw SecurityException");
2202 } catch (SecurityException expected) {
2203 }
2204 }
2205
2206 public void testForceUpdateUserSetupComplete_userbuild() {
2207 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2208 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2209
2210 final int userId = UserHandle.USER_SYSTEM;
2211 // GIVEN userComplete is false in SettingsProvider
2212 setUserSetupCompleteForUser(false, userId);
2213
2214 // GIVEN userComplete is true in DPM
2215 DevicePolicyManagerService.DevicePolicyData userData =
2216 new DevicePolicyManagerService.DevicePolicyData(userId);
2217 userData.mUserSetupComplete = true;
2218 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2219
2220 // GIVEN it's user build
2221 mContext.buildMock.isDebuggable = false;
2222
2223 assertTrue(dpms.hasUserSetupCompleted());
2224
2225 dpm.forceUpdateUserSetupComplete();
2226
2227 // THEN the state in dpms is not changed
2228 assertTrue(dpms.hasUserSetupCompleted());
2229 }
2230
2231 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2232 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2233 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2234
2235 final int userId = UserHandle.USER_SYSTEM;
2236 // GIVEN userComplete is false in SettingsProvider
2237 setUserSetupCompleteForUser(false, userId);
2238
2239 // GIVEN userComplete is true in DPM
2240 DevicePolicyManagerService.DevicePolicyData userData =
2241 new DevicePolicyManagerService.DevicePolicyData(userId);
2242 userData.mUserSetupComplete = true;
2243 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2244
2245 // GIVEN it's userdebug build
2246 mContext.buildMock.isDebuggable = true;
2247
2248 assertTrue(dpms.hasUserSetupCompleted());
2249
2250 dpm.forceUpdateUserSetupComplete();
2251
2252 // THEN the state in dpms is not changed
2253 assertFalse(dpms.hasUserSetupCompleted());
2254 }
2255
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002256 private long getLastSecurityLogRetrievalTime() {
2257 final long ident = mContext.binder.clearCallingIdentity();
2258 final long lastSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
2259 mContext.binder.restoreCallingIdentity(ident);
2260 return lastSecurityLogRetrievalTime;
2261 }
2262
2263 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2264 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2265 setupDeviceOwner();
2266 when(mContext.userManager.getUserCount()).thenReturn(1);
2267 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2268 .thenReturn(true);
2269
2270 // No logs were retrieved so far.
2271 assertEquals(-1, getLastSecurityLogRetrievalTime());
2272
2273 // Enabling logging should not change the timestamp.
2274 dpm.setSecurityLoggingEnabled(admin1, true);
2275 assertEquals(-1, getLastSecurityLogRetrievalTime());
2276
2277 // Retrieving the logs should update the timestamp.
2278 final long beforeRetrieval = System.currentTimeMillis();
2279 dpm.retrieveSecurityLogs(admin1);
2280 final long firstSecurityLogRetrievalTime = getLastSecurityLogRetrievalTime();
2281 final long afterRetrieval = System.currentTimeMillis();
2282 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2283 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2284
2285 // Retrieving the pre-boot logs should update the timestamp.
2286 Thread.sleep(2);
2287 dpm.retrievePreRebootSecurityLogs(admin1);
2288 final long secondSecurityLogRetrievalTime = getLastSecurityLogRetrievalTime();
2289 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2290
2291 // Checking the timestamp again should not change it.
2292 Thread.sleep(2);
2293 assertEquals(secondSecurityLogRetrievalTime, getLastSecurityLogRetrievalTime());
2294
2295 // Retrieving the logs again should update the timestamp.
2296 dpm.retrieveSecurityLogs(admin1);
2297 final long thirdSecurityLogRetrievalTime = getLastSecurityLogRetrievalTime();
2298 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2299
2300 // Disabling logging should not change the timestamp.
2301 Thread.sleep(2);
2302 dpm.setSecurityLoggingEnabled(admin1, false);
2303 assertEquals(thirdSecurityLogRetrievalTime, getLastSecurityLogRetrievalTime());
2304
2305 // Restarting the DPMS should not lose the timestamp.
2306 initializeDpms();
2307 assertEquals(thirdSecurityLogRetrievalTime, getLastSecurityLogRetrievalTime());
2308 }
2309
2310 private long getLastBugReportRequestTime() {
2311 final long ident = mContext.binder.clearCallingIdentity();
2312 final long lastBugRequestTime = dpm.getLastBugReportRequestTime();
2313 mContext.binder.restoreCallingIdentity(ident);
2314 return lastBugRequestTime;
2315 }
2316
2317 public void testGetLastBugReportRequestTime() throws Exception {
2318 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2319 setupDeviceOwner();
2320 when(mContext.userManager.getUserCount()).thenReturn(1);
2321 mContext.packageName = admin1.getPackageName();
2322 mContext.applicationInfo = new ApplicationInfo();
2323 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2324 .thenReturn(Color.WHITE);
2325 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2326 anyObject())).thenReturn(Color.WHITE);
2327
2328 // No bug reports were requested so far.
2329 assertEquals(-1, getLastSecurityLogRetrievalTime());
2330
2331 // Requesting a bug report should update the timestamp.
2332 final long beforeRequest = System.currentTimeMillis();
2333 dpm.requestBugreport(admin1);
2334 final long bugReportRequestTime = getLastBugReportRequestTime();
2335 final long afterRequest = System.currentTimeMillis();
2336 assertTrue(bugReportRequestTime >= beforeRequest);
2337 assertTrue(bugReportRequestTime <= afterRequest);
2338
2339 // Checking the timestamp again should not change it.
2340 Thread.sleep(2);
2341 assertEquals(bugReportRequestTime, getLastBugReportRequestTime());
2342
2343 // Restarting the DPMS should not lose the timestamp.
2344 initializeDpms();
2345 assertEquals(bugReportRequestTime, getLastBugReportRequestTime());
2346 }
2347
2348 private long getLastNetworkLogRetrievalTime() {
2349 final long ident = mContext.binder.clearCallingIdentity();
2350 final long lastNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
2351 mContext.binder.restoreCallingIdentity(ident);
2352 return lastNetworkLogRetrievalTime;
2353 }
2354
2355 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2356 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2357 setupDeviceOwner();
2358 when(mContext.userManager.getUserCount()).thenReturn(1);
2359 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2360 .thenReturn(true);
2361
2362 // No logs were retrieved so far.
2363 assertEquals(-1, getLastNetworkLogRetrievalTime());
2364
2365 // Attempting to retrieve logs without enabling logging should not change the timestamp.
2366 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
2367 assertEquals(-1, getLastNetworkLogRetrievalTime());
2368
2369 // Enabling logging should not change the timestamp.
2370 dpm.setNetworkLoggingEnabled(admin1, true);
2371 assertEquals(-1, getLastNetworkLogRetrievalTime());
2372
2373 // Retrieving the logs should update the timestamp.
2374 final long beforeRetrieval = System.currentTimeMillis();
2375 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
2376 final long firstNetworkLogRetrievalTime = getLastNetworkLogRetrievalTime();
2377 final long afterRetrieval = System.currentTimeMillis();
2378 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
2379 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
2380
2381 // Checking the timestamp again should not change it.
2382 Thread.sleep(2);
2383 assertEquals(firstNetworkLogRetrievalTime, getLastNetworkLogRetrievalTime());
2384
2385 // Retrieving the logs again should update the timestamp.
2386 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
2387 final long secondNetworkLogRetrievalTime = getLastNetworkLogRetrievalTime();
2388 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
2389
2390 // Disabling logging should not change the timestamp.
2391 Thread.sleep(2);
2392 dpm.setNetworkLoggingEnabled(admin1, false);
2393 assertEquals(secondNetworkLogRetrievalTime, getLastNetworkLogRetrievalTime());
2394
2395 // Restarting the DPMS should not lose the timestamp.
2396 initializeDpms();
2397 assertEquals(secondNetworkLogRetrievalTime, getLastNetworkLogRetrievalTime());
2398 }
2399
Victor Chang3e794af2016-03-04 13:48:17 +00002400 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
2401 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
2402 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
2403 dpms.notifyChangeToContentObserver(
2404 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
2405 }
2406
2407 private void assertProvisioningAllowed(String action, boolean expected) {
2408 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
2409 dpm.isProvisioningAllowed(action));
2410 }
2411}