blob: ed37b807141604920bbaab69e988cf3991c86d7e [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;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000053import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070054import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070055import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070056import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010057import java.util.Set;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070058
59import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070060import static org.mockito.Matchers.anyInt;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010061import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070062import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070063import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070064import static org.mockito.Matchers.isNull;
Makoto Onukib643fb02015-09-22 15:03:44 -070065import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070066import static org.mockito.Mockito.doReturn;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080067import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070068import static org.mockito.Mockito.times;
69import static org.mockito.Mockito.verify;
70import static org.mockito.Mockito.when;
71
72/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070073 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070074 *
75 m FrameworksServicesTests &&
76 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000077 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070078 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080079 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070080
81 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
82 */
Benjamin Franz6d009032016-01-25 18:56:38 +000083@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070084public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000085 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
86 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
87 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
88
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070089 private DpmMockContext mContext;
90 public DevicePolicyManager dpm;
91 public DevicePolicyManagerServiceTestable dpms;
92
93 @Override
94 protected void setUp() throws Exception {
95 super.setUp();
96
97 mContext = getContext();
98
99 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
100 .thenReturn(true);
101
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800102 // By default, pretend all users are running and unlocked.
103 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
104
Makoto Onukia52562c2015-10-01 16:12:31 -0700105 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700106
Makoto Onukid932f762015-09-29 16:53:38 -0700107 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
108 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
109 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800110 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700111
Makoto Onukib643fb02015-09-22 15:03:44 -0700112 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700113 }
114
Makoto Onukia52562c2015-10-01 16:12:31 -0700115 private void initializeDpms() {
116 // Need clearCallingIdentity() to pass permission checks.
117 final long ident = mContext.binder.clearCallingIdentity();
118 try {
119 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
120
121 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
122
123 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
124 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
125
126 dpm = new DevicePolicyManagerTestable(mContext, dpms);
127 } finally {
128 mContext.binder.restoreCallingIdentity(ident);
129 }
130 }
131
Makoto Onukib643fb02015-09-22 15:03:44 -0700132 private void setUpUserManager() {
133 // Emulate UserManager.set/getApplicationRestriction().
134 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
135
136 // UM.setApplicationRestrictions() will save to appRestrictions.
137 doAnswer(new Answer<Void>() {
138 @Override
139 public Void answer(InvocationOnMock invocation) throws Throwable {
140 String pkg = (String) invocation.getArguments()[0];
141 Bundle bundle = (Bundle) invocation.getArguments()[1];
142 UserHandle user = (UserHandle) invocation.getArguments()[2];
143
144 appRestrictions.put(Pair.create(pkg, user), bundle);
145
146 return null;
147 }
148 }).when(mContext.userManager).setApplicationRestrictions(
149 anyString(), any(Bundle.class), any(UserHandle.class));
150
151 // UM.getApplicationRestrictions() will read from appRestrictions.
152 doAnswer(new Answer<Bundle>() {
153 @Override
154 public Bundle answer(InvocationOnMock invocation) throws Throwable {
155 String pkg = (String) invocation.getArguments()[0];
156 UserHandle user = (UserHandle) invocation.getArguments()[1];
157
158 return appRestrictions.get(Pair.create(pkg, user));
159 }
160 }).when(mContext.userManager).getApplicationRestrictions(
161 anyString(), any(UserHandle.class));
162
Makoto Onukid932f762015-09-29 16:53:38 -0700163 // Add the first secondary user.
164 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700165 }
166
167 private void setAsProfileOwner(ComponentName admin) {
168 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
169 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
170
Makoto Onukia4f11972015-10-01 13:19:58 -0700171 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700172 dpm.setActiveAdmin(admin, /* replace =*/ false);
173
174 // Fire!
175 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
176
177 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700178 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700179 }
180
181 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700182 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
183 .thenReturn(false);
184
185 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
186 new DevicePolicyManagerServiceTestable(mContext, dataDir);
187
188 // If the device has no DPMS feature, it shouldn't register the local service.
189 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
190 }
191
192 /**
193 * Caller doesn't have proper permissions.
194 */
195 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700196 // 1. Failure cases.
197
198 // Caller doesn't have MANAGE_DEVICE_ADMINS.
199 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700200 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700201 fail("Didn't throw SecurityException");
202 } catch (SecurityException expected) {
203 }
204
205 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
206 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
207 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700208 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700209 fail("Didn't throw SecurityException");
210 } catch (SecurityException expected) {
211 }
212 }
213
Makoto Onukif76b06a2015-09-22 15:03:44 -0700214 /**
215 * Test for:
216 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800217 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700218 * {@link DevicePolicyManager#isAdminActive}
219 * {@link DevicePolicyManager#isAdminActiveAsUser}
220 * {@link DevicePolicyManager#getActiveAdmins}
221 * {@link DevicePolicyManager#getActiveAdminsAsUser}
222 */
223 public void testSetActiveAdmin() throws Exception {
224 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700225 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
226
Makoto Onukif76b06a2015-09-22 15:03:44 -0700227 // 2. Call the API.
228 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700229
230 // 3. Verify internal calls.
231
232 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700233 verify(mContext.spiedContext).sendBroadcastAsUser(
234 MockUtils.checkIntentAction(
235 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
236 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
237 verify(mContext.spiedContext).sendBroadcastAsUser(
238 MockUtils.checkIntentAction(
239 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700240 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
241
Makoto Onukif76b06a2015-09-22 15:03:44 -0700242 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
243 eq(admin1.getPackageName()),
244 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
245 eq(PackageManager.DONT_KILL_APP),
246 eq(DpmMockContext.CALLER_USER_HANDLE),
247 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700248
249 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700250
251 // Make sure it's active admin1.
252 assertTrue(dpm.isAdminActive(admin1));
253 assertFalse(dpm.isAdminActive(admin2));
254 assertFalse(dpm.isAdminActive(admin3));
255
256 // But not admin1 for a different user.
257
258 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
259 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
260 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
261
262 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
263 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
264
265 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
266
267 // Next, add one more admin.
268 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700269 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
270 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700271
272 dpm.setActiveAdmin(admin2, /* replace =*/ false);
273
274 // Now we have two admins.
275 assertTrue(dpm.isAdminActive(admin1));
276 assertTrue(dpm.isAdminActive(admin2));
277 assertFalse(dpm.isAdminActive(admin3));
278
279 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
280 // again. (times(1) because it was previously called for admin1)
281 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
282 eq(admin1.getPackageName()),
283 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
284 eq(PackageManager.DONT_KILL_APP),
285 eq(DpmMockContext.CALLER_USER_HANDLE),
286 anyString());
287
288 // 4. Add the same admin1 again without replace, which should throw.
289 try {
290 dpm.setActiveAdmin(admin1, /* replace =*/ false);
291 fail("Didn't throw");
292 } catch (IllegalArgumentException expected) {
293 }
294
295 // 5. Add the same admin1 again with replace, which should succeed.
296 dpm.setActiveAdmin(admin1, /* replace =*/ true);
297
298 // TODO make sure it's replaced.
299
300 // 6. Test getActiveAdmins()
301 List<ComponentName> admins = dpm.getActiveAdmins();
302 assertEquals(2, admins.size());
303 assertEquals(admin1, admins.get(0));
304 assertEquals(admin2, admins.get(1));
305
306 // Another user has no admins.
307 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
308
309 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
310 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
311
312 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
313 }
314
Makoto Onukid932f762015-09-29 16:53:38 -0700315 public void testSetActiveAdmin_multiUsers() throws Exception {
316
317 final int ANOTHER_USER_ID = 100;
318 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
319
320 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
321
322 // Set up pacakge manager for the other user.
323 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700324
325 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
326
327 dpm.setActiveAdmin(admin1, /* replace =*/ false);
328
329 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
330 dpm.setActiveAdmin(admin2, /* replace =*/ false);
331
332
333 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
334 assertTrue(dpm.isAdminActive(admin1));
335 assertFalse(dpm.isAdminActive(admin2));
336
337 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
338 assertFalse(dpm.isAdminActive(admin1));
339 assertTrue(dpm.isAdminActive(admin2));
340 }
341
Makoto Onukif76b06a2015-09-22 15:03:44 -0700342 /**
343 * Test for:
344 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800345 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700346 */
347 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
348 // 1. Make sure the caller has proper permissions.
349 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
350
351 dpm.setActiveAdmin(admin1, /* replace =*/ false);
352 assertTrue(dpm.isAdminActive(admin1));
353
354 // Add the same admin1 again without replace, which should throw.
355 try {
356 dpm.setActiveAdmin(admin1, /* replace =*/ false);
357 fail("Didn't throw");
358 } catch (IllegalArgumentException expected) {
359 }
360 }
361
362 /**
363 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800364 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
365 * BIND_DEVICE_ADMIN.
366 */
367 public void testSetActiveAdmin_permissionCheck() throws Exception {
368 // 1. Make sure the caller has proper permissions.
369 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
370
371 try {
372 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
373 fail();
374 } catch (IllegalArgumentException expected) {
375 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
376 }
377 assertFalse(dpm.isAdminActive(adminNoPerm));
378
379 // Change the target API level to MNC. Now it can be set as DA.
380 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
381 VERSION_CODES.M);
382 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
383 assertTrue(dpm.isAdminActive(adminNoPerm));
384
385 // TODO Test the "load from the file" case where DA will still be loaded even without
386 // BIND_DEVICE_ADMIN and target API is N.
387 }
388
389 /**
390 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700391 * {@link DevicePolicyManager#removeActiveAdmin}
392 */
393 public void testRemoveActiveAdmin_SecurityException() {
394 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
395
396 // Add admin.
397
398 dpm.setActiveAdmin(admin1, /* replace =*/ false);
399
400 assertTrue(dpm.isAdminActive(admin1));
401
402 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
403
404 // Directly call the DPMS method with a different userid, which should fail.
405 try {
406 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
407 fail("Didn't throw SecurityException");
408 } catch (SecurityException expected) {
409 }
410
411 // Try to remove active admin with a different caller userid should fail too, without
412 // having MANAGE_DEVICE_ADMINS.
413 mContext.callerPermissions.clear();
414
Makoto Onukid932f762015-09-29 16:53:38 -0700415 // Change the caller, and call into DPMS directly with a different user-id.
416
Makoto Onukif76b06a2015-09-22 15:03:44 -0700417 mContext.binder.callingUid = 1234567;
418 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700419 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700420 fail("Didn't throw SecurityException");
421 } catch (SecurityException expected) {
422 }
423 }
424
425 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800426 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
427 * (because we can't send the remove broadcast).
428 */
429 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
430 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
431
432 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
433
434 // Add admin.
435
436 dpm.setActiveAdmin(admin1, /* replace =*/ false);
437
438 assertTrue(dpm.isAdminActive(admin1));
439
440 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
441
442 // 1. User not unlocked.
443 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
444 .thenReturn(false);
445 try {
446 dpm.removeActiveAdmin(admin1);
447 fail("Didn't throw IllegalStateException");
448 } catch (IllegalStateException expected) {
449 MoreAsserts.assertContainsRegex(
450 "User must be running and unlocked", expected.getMessage());
451 }
452
453 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
454
455 // 2. User unlocked.
456 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
457 .thenReturn(true);
458
459 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700460 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800461 }
462
463 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700464 * Test for:
465 * {@link DevicePolicyManager#removeActiveAdmin}
466 */
Makoto Onukid932f762015-09-29 16:53:38 -0700467 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700468 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
469
470 // Add admin1.
471
472 dpm.setActiveAdmin(admin1, /* replace =*/ false);
473
474 assertTrue(dpm.isAdminActive(admin1));
475 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
476
477 // Different user, but should work, because caller has proper permissions.
478 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700479
480 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700481 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700482
483 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700484 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700485
486 // TODO DO Still can't be removed in this case.
487 }
488
489 /**
490 * Test for:
491 * {@link DevicePolicyManager#removeActiveAdmin}
492 */
493 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
494 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
495 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
496
497 // Add admin1.
498
499 dpm.setActiveAdmin(admin1, /* replace =*/ false);
500
501 assertTrue(dpm.isAdminActive(admin1));
502 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
503
504 // Broadcast from saveSettingsLocked().
505 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
506 MockUtils.checkIntentAction(
507 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
508 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
509
510 // Remove. No permissions, but same user, so it'll work.
511 mContext.callerPermissions.clear();
512 dpm.removeActiveAdmin(admin1);
513
Makoto Onukif76b06a2015-09-22 15:03:44 -0700514 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
515 MockUtils.checkIntentAction(
516 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
517 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
518 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700519 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700520 eq(dpms.mHandler),
521 eq(Activity.RESULT_OK),
522 isNull(String.class),
523 isNull(Bundle.class));
524
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700525 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700526
527 // Again broadcast from saveSettingsLocked().
528 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
529 MockUtils.checkIntentAction(
530 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
531 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
532
533 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700534 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700535
536 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000537 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700538 */
539 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000540 setDeviceOwner();
541
542 // Try to set a profile owner on the same user, which should fail.
543 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
544 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
545 try {
546 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
547 fail("IllegalStateException not thrown");
548 } catch (IllegalStateException expected) {
549 assertTrue("Message was: " + expected.getMessage(),
550 expected.getMessage().contains("already has a device owner"));
551 }
552
553 // DO admin can't be deactivated.
554 dpm.removeActiveAdmin(admin1);
555 assertTrue(dpm.isAdminActive(admin1));
556
557 // TODO Test getDeviceOwnerName() too. To do so, we need to change
558 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
559 }
560
561 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700562 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800563 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700564 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
565 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
566
Makoto Onukid932f762015-09-29 16:53:38 -0700567 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700568 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
569
Makoto Onukid932f762015-09-29 16:53:38 -0700570 // Make sure admin1 is installed on system user.
571 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700572
Makoto Onukic8a5a552015-11-19 14:29:12 -0800573 // Check various get APIs.
574 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
575
Makoto Onukib643fb02015-09-22 15:03:44 -0700576 // DO needs to be an DA.
577 dpm.setActiveAdmin(admin1, /* replace =*/ false);
578
579 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700580 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700581
Makoto Onukic8a5a552015-11-19 14:29:12 -0800582 // getDeviceOwnerComponent should return the admin1 component.
583 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
584 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
585
586 // Check various get APIs.
587 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
588
589 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
590 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
591 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
592 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
593
594 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
595
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000596 // Verify internal calls.
597 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
598 eq(admin1.getPackageName()));
599
Makoto Onukib643fb02015-09-22 15:03:44 -0700600 // TODO We should check if the caller has called clearCallerIdentity().
601 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
602 eq(UserHandle.USER_SYSTEM), eq(false));
603
604 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
605 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
606 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
607
Makoto Onukic8a5a552015-11-19 14:29:12 -0800608 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700609 }
610
Makoto Onukic8a5a552015-11-19 14:29:12 -0800611 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
612 final int origCallingUser = mContext.binder.callingUid;
613 final List origPermissions = new ArrayList(mContext.callerPermissions);
614 mContext.callerPermissions.clear();
615
616 mContext.callerPermissions.add(permission.MANAGE_USERS);
617
618 mContext.binder.callingUid = Process.SYSTEM_UID;
619
620 // TODO Test getDeviceOwnerName() too. To do so, we need to change
621 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
622 if (hasDeviceOwner) {
623 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
624 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
625 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
626
627 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
628 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
629 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
630 } else {
631 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
632 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
633 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
634
635 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
636 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
637 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
638 }
639
640 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
641 if (hasDeviceOwner) {
642 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
643 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
644 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
645
646 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
647 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
648 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
649 } else {
650 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
651 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
652 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
653
654 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
655 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
656 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
657 }
658
659 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
660 // Still with MANAGE_USERS.
661 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
662 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
663 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
664
665 if (hasDeviceOwner) {
666 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
667 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
668 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
669 } else {
670 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
671 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
672 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
673 }
674
675 mContext.binder.callingUid = Process.SYSTEM_UID;
676 mContext.callerPermissions.remove(permission.MANAGE_USERS);
677 // System can still call "OnAnyUser" without MANAGE_USERS.
678 if (hasDeviceOwner) {
679 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
680 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
681 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
682
683 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
684 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
685 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
686 } else {
687 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
688 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
689 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
690
691 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
692 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
693 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
694 }
695
696 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
697 // Still no MANAGE_USERS.
698 if (hasDeviceOwner) {
699 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
700 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
701 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
702 } else {
703 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
704 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
705 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
706 }
707
708 try {
709 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
710 fail();
711 } catch (SecurityException expected) {
712 }
713 try {
714 dpm.getDeviceOwnerComponentOnAnyUser();
715 fail();
716 } catch (SecurityException expected) {
717 }
718 try {
719 dpm.getDeviceOwnerUserId();
720 fail();
721 } catch (SecurityException expected) {
722 }
723 try {
724 dpm.getDeviceOwnerNameOnAnyUser();
725 fail();
726 } catch (SecurityException expected) {
727 }
728
729 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
730 // Still no MANAGE_USERS.
731 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
732 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
733 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
734
735 try {
736 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
737 fail();
738 } catch (SecurityException expected) {
739 }
740 try {
741 dpm.getDeviceOwnerComponentOnAnyUser();
742 fail();
743 } catch (SecurityException expected) {
744 }
745 try {
746 dpm.getDeviceOwnerUserId();
747 fail();
748 } catch (SecurityException expected) {
749 }
750 try {
751 dpm.getDeviceOwnerNameOnAnyUser();
752 fail();
753 } catch (SecurityException expected) {
754 }
755
756 // Restore.
757 mContext.binder.callingUid = origCallingUser;
758 mContext.callerPermissions.addAll(origPermissions);
759 }
760
761
Makoto Onukib643fb02015-09-22 15:03:44 -0700762 /**
763 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
764 */
765 public void testSetDeviceOwner_noSuchPackage() {
766 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800767 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700768 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
769 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
770
771 // Call from a process on the system user.
772 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
773
Makoto Onukib643fb02015-09-22 15:03:44 -0700774 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700775 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700776 fail("Didn't throw IllegalArgumentException");
777 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700778 assertTrue("Message was: " + expected.getMessage(),
779 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700780 }
781 }
782
783 public void testSetDeviceOwner_failures() throws Exception {
784 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
785 }
786
Makoto Onukia52562c2015-10-01 16:12:31 -0700787 public void testClearDeviceOwner() throws Exception {
788 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800789 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700790 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
791 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
792
793 // Set admin1 as a DA to the secondary user.
794 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
795
796 dpm.setActiveAdmin(admin1, /* replace =*/ false);
797
798 // Set admin 1 as the DO to the system user.
799
800 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
801 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
802 dpm.setActiveAdmin(admin1, /* replace =*/ false);
803 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
804
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000805 // Verify internal calls.
806 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
807 eq(admin1.getPackageName()));
808
Makoto Onukic8a5a552015-11-19 14:29:12 -0800809 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700810
Makoto Onuki90b89652016-01-28 14:44:18 -0800811 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
812
813 assertTrue(dpm.isAdminActive(admin1));
814 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
815
Makoto Onukia52562c2015-10-01 16:12:31 -0700816 // Set up other mocks.
817 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
818
819 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700820 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700821 eq(admin1.getPackageName()),
822 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800823
824 // But first pretend the user is locked. Then it should fail.
825 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
826 try {
827 dpm.clearDeviceOwnerApp(admin1.getPackageName());
828 fail("Didn't throw IllegalStateException");
829 } catch (IllegalStateException expected) {
830 MoreAsserts.assertContainsRegex(
831 "User must be running and unlocked", expected.getMessage());
832 }
833
834 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800835 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700836 dpm.clearDeviceOwnerApp(admin1.getPackageName());
837
838 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800839 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700840
Makoto Onuki90b89652016-01-28 14:44:18 -0800841 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
842 eq(UserHandle.USER_SYSTEM),
843 MockUtils.checkUserRestrictions(),
844 MockUtils.checkUserRestrictions()
845 );
846
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700847 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100848
849 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
850 // and once for clearing it.
851 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
852 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
853 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700854 // TODO Check other calls.
855 }
856
857 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
858 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800859 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700860 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
861 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
862
863 // Set admin1 as a DA to the secondary user.
864 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
865
866 dpm.setActiveAdmin(admin1, /* replace =*/ false);
867
868 // Set admin 1 as the DO to the system user.
869
870 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
871 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
872 dpm.setActiveAdmin(admin1, /* replace =*/ false);
873 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
874
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000875 // Verify internal calls.
876 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
877 eq(admin1.getPackageName()));
878
Makoto Onukic8a5a552015-11-19 14:29:12 -0800879 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700880
881 // Now call clear from the secondary user, which should throw.
882 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
883
884 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700885 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700886 eq(admin1.getPackageName()),
887 anyInt());
888 try {
889 dpm.clearDeviceOwnerApp(admin1.getPackageName());
890 fail("Didn't throw");
891 } catch (SecurityException e) {
892 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
893 }
894
Makoto Onukic8a5a552015-11-19 14:29:12 -0800895 // DO shouldn't be removed.
896 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700897 }
898
Makoto Onukib643fb02015-09-22 15:03:44 -0700899 public void testSetProfileOwner() throws Exception {
900 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700901
Makoto Onuki90b89652016-01-28 14:44:18 -0800902 // PO admin can't be deactivated.
903 dpm.removeActiveAdmin(admin1);
904 assertTrue(dpm.isAdminActive(admin1));
905
Makoto Onuki803d6752015-10-30 12:58:39 -0700906 // Try setting DO on the same user, which should fail.
907 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
908 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
909 try {
910 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
911 fail("IllegalStateException not thrown");
912 } catch (IllegalStateException expected) {
913 assertTrue("Message was: " + expected.getMessage(),
914 expected.getMessage().contains("already has a profile owner"));
915 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700916 }
917
Makoto Onuki90b89652016-01-28 14:44:18 -0800918 public void testClearProfileOwner() throws Exception {
919 setAsProfileOwner(admin1);
920
921 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
922
923 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
924 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
925
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800926 // First try when the user is locked, which should fail.
927 when(mContext.userManager.isUserUnlocked(anyInt()))
928 .thenReturn(false);
929 try {
930 dpm.clearProfileOwner(admin1);
931 fail("Didn't throw IllegalStateException");
932 } catch (IllegalStateException expected) {
933 MoreAsserts.assertContainsRegex(
934 "User must be running and unlocked", expected.getMessage());
935 }
936 // Clear, really.
937 when(mContext.userManager.isUserUnlocked(anyInt()))
938 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800939 dpm.clearProfileOwner(admin1);
940
941 // Check
942 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700943 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -0800944 }
945
Makoto Onukib643fb02015-09-22 15:03:44 -0700946 public void testSetProfileOwner_failures() throws Exception {
947 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
948 }
949
Makoto Onukia52562c2015-10-01 16:12:31 -0700950 public void testGetDeviceOwnerAdminLocked() throws Exception {
951 checkDeviceOwnerWithMultipleDeviceAdmins();
952 }
953
954 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
955 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
956 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
957 // make sure it gets the right component from the right user.
958
959 final int ANOTHER_USER_ID = 100;
960 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
961
962 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
963
964 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800965 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700966 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
967 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
968
969 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
970
Victor Change29cd472016-03-02 20:57:42 +0000971 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
972
Makoto Onukia52562c2015-10-01 16:12:31 -0700973 // Make sure the admin packge is installed to each user.
974 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
975 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
976
977 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
978 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
979
980 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
981
982
983 // Set active admins to the users.
984 dpm.setActiveAdmin(admin1, /* replace =*/ false);
985 dpm.setActiveAdmin(admin3, /* replace =*/ false);
986
987 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
988 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
989
990 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
991
992 // Set DO on the first non-system user.
993 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
994 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
995
Makoto Onukic8a5a552015-11-19 14:29:12 -0800996 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -0700997
998 // Then check getDeviceOwnerAdminLocked().
999 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1000 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1001 }
1002
1003 /**
1004 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001005 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1006 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001007 *
1008 * We didn't use to persist the DO component class name, but now we do, and the above method
1009 * finds the right component from a package name upon migration.
1010 */
1011 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001012 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001013 checkDeviceOwnerWithMultipleDeviceAdmins();
1014
1015 // Overwrite the device owner setting and clears the clas name.
1016 dpms.mOwners.setDeviceOwner(
1017 new ComponentName(admin2.getPackageName(), ""),
1018 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1019 dpms.mOwners.writeDeviceOwner();
1020
1021 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001022 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001023
1024 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001025 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1026 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001027 initializeDpms();
1028
1029 // Now the DO component name is a full name.
1030 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1031 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001032 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001033 }
1034
Makoto Onukib643fb02015-09-22 15:03:44 -07001035 public void testSetGetApplicationRestriction() {
1036 setAsProfileOwner(admin1);
1037
1038 {
1039 Bundle rest = new Bundle();
1040 rest.putString("KEY_STRING", "Foo1");
1041 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1042 }
1043
1044 {
1045 Bundle rest = new Bundle();
1046 rest.putString("KEY_STRING", "Foo2");
1047 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1048 }
1049
1050 {
1051 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1052 assertNotNull(returned);
1053 assertEquals(returned.size(), 1);
1054 assertEquals(returned.get("KEY_STRING"), "Foo1");
1055 }
1056
1057 {
1058 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1059 assertNotNull(returned);
1060 assertEquals(returned.size(), 1);
1061 assertEquals(returned.get("KEY_STRING"), "Foo2");
1062 }
1063
1064 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1065 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1066 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001067
Esteban Talaverabf60f722015-12-10 16:26:44 +00001068 public void testApplicationRestrictionsManagingApp() throws Exception {
1069 setAsProfileOwner(admin1);
1070
Rubin Xued1928a2016-02-11 17:23:06 +00001071 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001072 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1073 final int appRestrictionsManagerAppId = 20987;
1074 final int appRestrictionsManagerUid = UserHandle.getUid(
1075 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001076 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001077 eq(appRestrictionsManagerPackage),
1078 eq(DpmMockContext.CALLER_USER_HANDLE));
1079 mContext.binder.callingUid = appRestrictionsManagerUid;
1080
Rubin Xued1928a2016-02-11 17:23:06 +00001081 final PackageInfo pi = new PackageInfo();
1082 pi.applicationInfo = new ApplicationInfo();
1083 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1084 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1085 eq(appRestrictionsManagerPackage),
1086 anyInt(),
1087 eq(DpmMockContext.CALLER_USER_HANDLE));
1088
Esteban Talaverabf60f722015-12-10 16:26:44 +00001089 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1090 // delegated that permission yet.
1091 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1092 Bundle rest = new Bundle();
1093 rest.putString("KEY_STRING", "Foo1");
1094 try {
1095 dpm.setApplicationRestrictions(null, "pkg1", rest);
1096 fail("Didn't throw expected SecurityException");
1097 } catch (SecurityException expected) {
1098 MoreAsserts.assertContainsRegex(
1099 "caller cannot manage application restrictions", expected.getMessage());
1100 }
1101 try {
1102 dpm.getApplicationRestrictions(null, "pkg1");
1103 fail("Didn't throw expected SecurityException");
1104 } catch (SecurityException expected) {
1105 MoreAsserts.assertContainsRegex(
1106 "caller cannot manage application restrictions", expected.getMessage());
1107 }
1108
1109 // Check via the profile owner that no restrictions were set.
1110 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1111 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1112
Rubin Xued1928a2016-02-11 17:23:06 +00001113 // Check the API does not allow setting a non-existent package
1114 try {
1115 dpm.setApplicationRestrictionsManagingPackage(admin1,
1116 nonExistAppRestrictionsManagerPackage);
1117 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001118 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001119 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001120 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001121 }
1122
Esteban Talaverabf60f722015-12-10 16:26:44 +00001123 // Let appRestrictionsManagerPackage manage app restrictions
1124 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1125 assertEquals(appRestrictionsManagerPackage,
1126 dpm.getApplicationRestrictionsManagingPackage(admin1));
1127
1128 // Now that package should be able to set and retrieve app restrictions.
1129 mContext.binder.callingUid = appRestrictionsManagerUid;
1130 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1131 dpm.setApplicationRestrictions(null, "pkg1", rest);
1132 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1133 assertEquals(1, returned.size(), 1);
1134 assertEquals("Foo1", returned.get("KEY_STRING"));
1135
1136 // The same app running on a separate user shouldn't be able to manage app restrictions.
1137 mContext.binder.callingUid = UserHandle.getUid(
1138 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1139 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1140 try {
1141 dpm.setApplicationRestrictions(null, "pkg1", rest);
1142 fail("Didn't throw expected SecurityException");
1143 } catch (SecurityException expected) {
1144 MoreAsserts.assertContainsRegex(
1145 "caller cannot manage application restrictions", expected.getMessage());
1146 }
1147
1148 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1149 // too.
1150 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1151 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1152 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1153 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1154
1155 // Removing the ability for the package to manage app restrictions.
1156 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1157 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1158 mContext.binder.callingUid = appRestrictionsManagerUid;
1159 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1160 try {
1161 dpm.setApplicationRestrictions(null, "pkg1", null);
1162 fail("Didn't throw expected SecurityException");
1163 } catch (SecurityException expected) {
1164 MoreAsserts.assertContainsRegex(
1165 "caller cannot manage application restrictions", expected.getMessage());
1166 }
1167 }
1168
Makoto Onukia4f11972015-10-01 13:19:58 -07001169 public void testSetUserRestriction_asDo() throws Exception {
1170 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001171 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001172 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1173 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1174
1175 // First, set DO.
1176
1177 // Call from a process on the system user.
1178 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1179
1180 // Make sure admin1 is installed on system user.
1181 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001182
1183 // Call.
1184 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001185 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001186 UserHandle.USER_SYSTEM));
1187
Makoto Onuki068c54a2015-10-13 14:34:03 -07001188 DpmTestUtils.assertRestrictions(
1189 DpmTestUtils.newRestrictions(),
1190 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1191 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001192 DpmTestUtils.assertRestrictions(
1193 DpmTestUtils.newRestrictions(),
1194 dpm.getUserRestrictions(admin1)
1195 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001196
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001197 reset(mContext.userManagerInternal);
1198
1199 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1200 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1201 eq(UserHandle.USER_SYSTEM),
1202 MockUtils.checkUserRestrictions(),
1203 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001204 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001205 reset(mContext.userManagerInternal);
1206
Makoto Onukia4f11972015-10-01 13:19:58 -07001207 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001208 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1209 eq(UserHandle.USER_SYSTEM),
1210 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1211 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1212 );
1213 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001214
Makoto Onuki068c54a2015-10-13 14:34:03 -07001215 DpmTestUtils.assertRestrictions(
1216 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001217 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001218 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1219 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001220 DpmTestUtils.assertRestrictions(
1221 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001222 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001223 dpm.getUserRestrictions(admin1)
1224 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001225
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001226 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1227 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1228 eq(UserHandle.USER_SYSTEM),
1229 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1230 MockUtils.checkUserRestrictions()
1231 );
1232 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001233
Makoto Onuki068c54a2015-10-13 14:34:03 -07001234 DpmTestUtils.assertRestrictions(
1235 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1236 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1237 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001238 DpmTestUtils.assertRestrictions(
1239 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1240 dpm.getUserRestrictions(admin1)
1241 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001242
1243 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001244 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1245 eq(UserHandle.USER_SYSTEM),
1246 MockUtils.checkUserRestrictions(),
1247 MockUtils.checkUserRestrictions()
1248 );
1249 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001250
Makoto Onuki068c54a2015-10-13 14:34:03 -07001251 DpmTestUtils.assertRestrictions(
1252 DpmTestUtils.newRestrictions(),
1253 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1254 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001255 DpmTestUtils.assertRestrictions(
1256 DpmTestUtils.newRestrictions(),
1257 dpm.getUserRestrictions(admin1)
1258 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001259
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001260 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1261 // DO sets them, the scope is global.
1262 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1263 reset(mContext.userManagerInternal);
1264 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1265 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1266 eq(UserHandle.USER_SYSTEM),
1267 MockUtils.checkUserRestrictions(),
1268 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1269 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1270 );
1271 reset(mContext.userManagerInternal);
1272
1273 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1274 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1275
1276
1277 // More tests.
1278 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1279 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1280 eq(UserHandle.USER_SYSTEM),
1281 MockUtils.checkUserRestrictions(),
1282 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1283 );
1284 reset(mContext.userManagerInternal);
1285
1286 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1287 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1288 eq(UserHandle.USER_SYSTEM),
1289 MockUtils.checkUserRestrictions(),
1290 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1291 UserManager.DISALLOW_ADD_USER)
1292 );
1293 reset(mContext.userManagerInternal);
1294
1295 dpm.setCameraDisabled(admin1, true);
1296 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1297 eq(UserHandle.USER_SYSTEM),
1298 // DISALLOW_CAMERA will be applied to both local and global.
1299 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1300 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1301 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1302 );
1303 reset(mContext.userManagerInternal);
1304
1305 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1306 // locally.
1307 dpm.setCameraDisabled(admin1, false);
1308 reset(mContext.userManagerInternal);
1309
1310 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1311 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1312 dpm.setCameraDisabled(admin2, true);
1313
1314 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1315 eq(UserHandle.USER_SYSTEM),
1316 // DISALLOW_CAMERA will be applied to both local and global.
1317 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1318 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1319 UserManager.DISALLOW_ADD_USER)
1320 );
1321 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001322 // TODO Make sure restrictions are written to the file.
1323 }
1324
1325 public void testSetUserRestriction_asPo() {
1326 setAsProfileOwner(admin1);
1327
Makoto Onuki068c54a2015-10-13 14:34:03 -07001328 DpmTestUtils.assertRestrictions(
1329 DpmTestUtils.newRestrictions(),
1330 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1331 .ensureUserRestrictions()
1332 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001333
1334 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001335 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1336 eq(DpmMockContext.CALLER_USER_HANDLE),
1337 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1338 isNull(Bundle.class)
1339 );
1340 reset(mContext.userManagerInternal);
1341
Makoto Onukia4f11972015-10-01 13:19:58 -07001342 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001343 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1344 eq(DpmMockContext.CALLER_USER_HANDLE),
1345 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1346 UserManager.DISALLOW_OUTGOING_CALLS),
1347 isNull(Bundle.class)
1348 );
1349 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001350
Makoto Onuki068c54a2015-10-13 14:34:03 -07001351 DpmTestUtils.assertRestrictions(
1352 DpmTestUtils.newRestrictions(
1353 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1354 UserManager.DISALLOW_OUTGOING_CALLS
1355 ),
1356 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1357 .ensureUserRestrictions()
1358 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001359 DpmTestUtils.assertRestrictions(
1360 DpmTestUtils.newRestrictions(
1361 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1362 UserManager.DISALLOW_OUTGOING_CALLS
1363 ),
1364 dpm.getUserRestrictions(admin1)
1365 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001366
1367 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001368 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1369 eq(DpmMockContext.CALLER_USER_HANDLE),
1370 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1371 isNull(Bundle.class)
1372 );
1373 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001374
1375 DpmTestUtils.assertRestrictions(
1376 DpmTestUtils.newRestrictions(
1377 UserManager.DISALLOW_OUTGOING_CALLS
1378 ),
1379 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1380 .ensureUserRestrictions()
1381 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001382 DpmTestUtils.assertRestrictions(
1383 DpmTestUtils.newRestrictions(
1384 UserManager.DISALLOW_OUTGOING_CALLS
1385 ),
1386 dpm.getUserRestrictions(admin1)
1387 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001388
1389 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001390 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1391 eq(DpmMockContext.CALLER_USER_HANDLE),
1392 MockUtils.checkUserRestrictions(),
1393 isNull(Bundle.class)
1394 );
1395 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001396
Makoto Onuki068c54a2015-10-13 14:34:03 -07001397 DpmTestUtils.assertRestrictions(
1398 DpmTestUtils.newRestrictions(),
1399 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1400 .ensureUserRestrictions()
1401 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001402 DpmTestUtils.assertRestrictions(
1403 DpmTestUtils.newRestrictions(),
1404 dpm.getUserRestrictions(admin1)
1405 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001406
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001407 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1408 // though when DO sets them they'll be applied globally.
1409 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1410 reset(mContext.userManagerInternal);
1411 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1412 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1413 eq(DpmMockContext.CALLER_USER_HANDLE),
1414 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1415 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1416 isNull(Bundle.class)
1417 );
1418 reset(mContext.userManagerInternal);
1419
1420 dpm.setCameraDisabled(admin1, true);
1421 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1422 eq(DpmMockContext.CALLER_USER_HANDLE),
1423 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1424 UserManager.DISALLOW_ADJUST_VOLUME,
1425 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1426 isNull(Bundle.class)
1427 );
1428 reset(mContext.userManagerInternal);
1429
Makoto Onukia4f11972015-10-01 13:19:58 -07001430 // TODO Make sure restrictions are written to the file.
1431 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001432
1433 public void testGetMacAddress() throws Exception {
1434 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1435 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1436 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1437
1438 // In this test, change the caller user to "system".
1439 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1440
1441 // Make sure admin1 is installed on system user.
1442 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1443
1444 // Test 1. Caller doesn't have DO or DA.
1445 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001446 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001447 fail();
1448 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001449 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001450 }
1451
1452 // DO needs to be an DA.
1453 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1454 assertTrue(dpm.isAdminActive(admin1));
1455
1456 // Test 2. Caller has DA, but not DO.
1457 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001458 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001459 fail();
1460 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001461 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001462 }
1463
1464 // Test 3. Caller has PO, but not DO.
1465 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1466 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001467 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001468 fail();
1469 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001470 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001471 }
1472
1473 // Remove PO.
1474 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001475 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001476 // Test 4, Caller is DO now.
1477 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1478
1479 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001480 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001481
1482 // 4-2. Returns WifiInfo, but with the default MAC.
1483 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001484 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001485
1486 // 4-3. With a real MAC address.
1487 final WifiInfo wi = new WifiInfo();
1488 wi.setMacAddress("11:22:33:44:55:66");
1489 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001490 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001491 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001492
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001493 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001494 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1495 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1496
1497 // In this test, change the caller user to "system".
1498 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1499
1500 // Make sure admin1 is installed on system user.
1501 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1502
1503 // Set admin1 as DA.
1504 dpm.setActiveAdmin(admin1, false);
1505 assertTrue(dpm.isAdminActive(admin1));
1506 try {
1507 dpm.reboot(admin1);
1508 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1509 } catch (SecurityException expected) {
1510 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1511 }
1512
1513 // Set admin1 as PO.
1514 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1515 try {
1516 dpm.reboot(admin1);
1517 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1518 } catch (SecurityException expected) {
1519 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1520 }
1521
1522 // Remove PO and add DO.
1523 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001524 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001525 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1526
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001527 // admin1 is DO.
1528 // Set current call state of device to ringing.
1529 when(mContext.telephonyManager.getCallState())
1530 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1531 try {
1532 dpm.reboot(admin1);
1533 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1534 } catch (IllegalStateException expected) {
1535 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1536 }
1537
1538 // Set current call state of device to dialing/active.
1539 when(mContext.telephonyManager.getCallState())
1540 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1541 try {
1542 dpm.reboot(admin1);
1543 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1544 } catch (IllegalStateException expected) {
1545 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1546 }
1547
1548 // Set current call state of device to idle.
1549 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001550 dpm.reboot(admin1);
1551 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001552
1553 public void testSetGetSupportText() {
1554 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1555 dpm.setActiveAdmin(admin1, true);
1556 dpm.setActiveAdmin(admin2, true);
1557 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1558
1559 // Null default support messages.
1560 {
1561 assertNull(dpm.getLongSupportMessage(admin1));
1562 assertNull(dpm.getShortSupportMessage(admin1));
1563 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1564 assertNull(dpm.getShortSupportMessageForUser(admin1,
1565 DpmMockContext.CALLER_USER_HANDLE));
1566 assertNull(dpm.getLongSupportMessageForUser(admin1,
1567 DpmMockContext.CALLER_USER_HANDLE));
1568 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1569 }
1570
1571 // Only system can call the per user versions.
1572 {
1573 try {
1574 dpm.getShortSupportMessageForUser(admin1,
1575 DpmMockContext.CALLER_USER_HANDLE);
1576 fail("Only system should be able to call getXXXForUser versions");
1577 } catch (SecurityException expected) {
1578 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1579 }
1580 try {
1581 dpm.getLongSupportMessageForUser(admin1,
1582 DpmMockContext.CALLER_USER_HANDLE);
1583 fail("Only system should be able to call getXXXForUser versions");
1584 } catch (SecurityException expected) {
1585 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1586 }
1587 }
1588
1589 // Can't set message for admin in another uid.
1590 {
1591 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1592 try {
1593 dpm.setShortSupportMessage(admin1, "Some text");
1594 fail("Admins should only be able to change their own support text.");
1595 } catch (SecurityException expected) {
1596 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1597 }
1598 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1599 }
1600
1601 // Set/Get short returns what it sets and other admins text isn't changed.
1602 {
1603 final String supportText = "Some text to test with.";
1604 dpm.setShortSupportMessage(admin1, supportText);
1605 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1606 assertNull(dpm.getLongSupportMessage(admin1));
1607 assertNull(dpm.getShortSupportMessage(admin2));
1608
1609 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1610 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1611 DpmMockContext.CALLER_USER_HANDLE));
1612 assertNull(dpm.getShortSupportMessageForUser(admin2,
1613 DpmMockContext.CALLER_USER_HANDLE));
1614 assertNull(dpm.getLongSupportMessageForUser(admin1,
1615 DpmMockContext.CALLER_USER_HANDLE));
1616 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1617
1618 dpm.setShortSupportMessage(admin1, null);
1619 assertNull(dpm.getShortSupportMessage(admin1));
1620 }
1621
1622 // Set/Get long returns what it sets and other admins text isn't changed.
1623 {
1624 final String supportText = "Some text to test with.\nWith more text.";
1625 dpm.setLongSupportMessage(admin1, supportText);
1626 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1627 assertNull(dpm.getShortSupportMessage(admin1));
1628 assertNull(dpm.getLongSupportMessage(admin2));
1629
1630 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1631 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1632 DpmMockContext.CALLER_USER_HANDLE));
1633 assertNull(dpm.getLongSupportMessageForUser(admin2,
1634 DpmMockContext.CALLER_USER_HANDLE));
1635 assertNull(dpm.getShortSupportMessageForUser(admin1,
1636 DpmMockContext.CALLER_USER_HANDLE));
1637 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1638
1639 dpm.setLongSupportMessage(admin1, null);
1640 assertNull(dpm.getLongSupportMessage(admin1));
1641 }
1642 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001643
1644 /**
1645 * Test for:
1646 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001647 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001648 * {@link DevicePolicyManager#isAffiliatedUser}
1649 */
1650 public void testUserAffiliation() throws Exception {
1651 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1652 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1653 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1654
1655 // Check that the system user is unaffiliated.
1656 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1657 assertFalse(dpm.isAffiliatedUser());
1658
1659 // Set a device owner on the system user. Check that the system user becomes affiliated.
1660 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1661 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1662 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1663 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001664 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001665
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001666 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001667 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1668 setAsProfileOwner(admin2);
1669 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001670 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001671
1672 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1673 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001674 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001675 userAffiliationIds.add("red");
1676 userAffiliationIds.add("green");
1677 userAffiliationIds.add("blue");
1678 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001679 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001680 assertFalse(dpm.isAffiliatedUser());
1681
1682 // Have the device owner specify a set of affiliation ids that do not intersect with those
1683 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001684 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001685 deviceAffiliationIds.add("cyan");
1686 deviceAffiliationIds.add("yellow");
1687 deviceAffiliationIds.add("magenta");
1688 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1689 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001690 MoreAsserts.assertContentsInAnyOrder(
1691 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001692 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1693 assertFalse(dpm.isAffiliatedUser());
1694
1695 // Have the profile owner specify a set of affiliation ids that intersect with those
1696 // specified by the device owner. Check that the test user becomes affiliated.
1697 userAffiliationIds.add("yellow");
1698 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001699 MoreAsserts.assertContentsInAnyOrder(
1700 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001701 assertTrue(dpm.isAffiliatedUser());
1702
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001703 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
1704 dpm.setAffiliationIds(admin2, Collections.emptyList());
1705 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001706 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
Nicolas Prevot56400a42016-11-10 12:57:54 +00002186 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2187 throws Exception {
2188 setDeviceOwner();
2189
2190 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2191 .thenReturn(true);
2192 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2193 when(mContext.userManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_USER))
2194 .thenReturn(true);
2195 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2196 false /* we can't remove a managed profile*/)).thenReturn(false);
2197 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2198 true)).thenReturn(true);
2199 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2200
2201 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2202
2203 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2204 }
2205
Victor Chang3577ed22016-08-25 18:49:26 +01002206 public void testForceUpdateUserSetupComplete_permission() {
2207 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2208 try {
2209 dpm.forceUpdateUserSetupComplete();
2210 fail("Didn't throw SecurityException");
2211 } catch (SecurityException expected) {
2212 }
2213 }
2214
2215 public void testForceUpdateUserSetupComplete_systemUser() {
2216 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2217 // GIVEN calling from user 20
2218 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2219 try {
2220 dpm.forceUpdateUserSetupComplete();
2221 fail("Didn't throw SecurityException");
2222 } catch (SecurityException expected) {
2223 }
2224 }
2225
2226 public void testForceUpdateUserSetupComplete_userbuild() {
2227 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2228 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2229
2230 final int userId = UserHandle.USER_SYSTEM;
2231 // GIVEN userComplete is false in SettingsProvider
2232 setUserSetupCompleteForUser(false, userId);
2233
2234 // GIVEN userComplete is true in DPM
2235 DevicePolicyManagerService.DevicePolicyData userData =
2236 new DevicePolicyManagerService.DevicePolicyData(userId);
2237 userData.mUserSetupComplete = true;
2238 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2239
2240 // GIVEN it's user build
2241 mContext.buildMock.isDebuggable = false;
2242
2243 assertTrue(dpms.hasUserSetupCompleted());
2244
2245 dpm.forceUpdateUserSetupComplete();
2246
2247 // THEN the state in dpms is not changed
2248 assertTrue(dpms.hasUserSetupCompleted());
2249 }
2250
2251 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2252 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2253 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2254
2255 final int userId = UserHandle.USER_SYSTEM;
2256 // GIVEN userComplete is false in SettingsProvider
2257 setUserSetupCompleteForUser(false, userId);
2258
2259 // GIVEN userComplete is true in DPM
2260 DevicePolicyManagerService.DevicePolicyData userData =
2261 new DevicePolicyManagerService.DevicePolicyData(userId);
2262 userData.mUserSetupComplete = true;
2263 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2264
2265 // GIVEN it's userdebug build
2266 mContext.buildMock.isDebuggable = true;
2267
2268 assertTrue(dpms.hasUserSetupCompleted());
2269
2270 dpm.forceUpdateUserSetupComplete();
2271
2272 // THEN the state in dpms is not changed
2273 assertFalse(dpms.hasUserSetupCompleted());
2274 }
2275
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002276 private long getLastSecurityLogRetrievalTime() {
2277 final long ident = mContext.binder.clearCallingIdentity();
2278 final long lastSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
2279 mContext.binder.restoreCallingIdentity(ident);
2280 return lastSecurityLogRetrievalTime;
2281 }
2282
2283 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2284 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2285 setupDeviceOwner();
2286 when(mContext.userManager.getUserCount()).thenReturn(1);
2287 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2288 .thenReturn(true);
2289
2290 // No logs were retrieved so far.
2291 assertEquals(-1, getLastSecurityLogRetrievalTime());
2292
2293 // Enabling logging should not change the timestamp.
2294 dpm.setSecurityLoggingEnabled(admin1, true);
2295 assertEquals(-1, getLastSecurityLogRetrievalTime());
2296
2297 // Retrieving the logs should update the timestamp.
2298 final long beforeRetrieval = System.currentTimeMillis();
2299 dpm.retrieveSecurityLogs(admin1);
2300 final long firstSecurityLogRetrievalTime = getLastSecurityLogRetrievalTime();
2301 final long afterRetrieval = System.currentTimeMillis();
2302 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2303 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2304
2305 // Retrieving the pre-boot logs should update the timestamp.
2306 Thread.sleep(2);
2307 dpm.retrievePreRebootSecurityLogs(admin1);
2308 final long secondSecurityLogRetrievalTime = getLastSecurityLogRetrievalTime();
2309 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2310
2311 // Checking the timestamp again should not change it.
2312 Thread.sleep(2);
2313 assertEquals(secondSecurityLogRetrievalTime, getLastSecurityLogRetrievalTime());
2314
2315 // Retrieving the logs again should update the timestamp.
2316 dpm.retrieveSecurityLogs(admin1);
2317 final long thirdSecurityLogRetrievalTime = getLastSecurityLogRetrievalTime();
2318 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2319
2320 // Disabling logging should not change the timestamp.
2321 Thread.sleep(2);
2322 dpm.setSecurityLoggingEnabled(admin1, false);
2323 assertEquals(thirdSecurityLogRetrievalTime, getLastSecurityLogRetrievalTime());
2324
2325 // Restarting the DPMS should not lose the timestamp.
2326 initializeDpms();
2327 assertEquals(thirdSecurityLogRetrievalTime, getLastSecurityLogRetrievalTime());
2328 }
2329
2330 private long getLastBugReportRequestTime() {
2331 final long ident = mContext.binder.clearCallingIdentity();
2332 final long lastBugRequestTime = dpm.getLastBugReportRequestTime();
2333 mContext.binder.restoreCallingIdentity(ident);
2334 return lastBugRequestTime;
2335 }
2336
2337 public void testGetLastBugReportRequestTime() throws Exception {
2338 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2339 setupDeviceOwner();
2340 when(mContext.userManager.getUserCount()).thenReturn(1);
2341 mContext.packageName = admin1.getPackageName();
2342 mContext.applicationInfo = new ApplicationInfo();
2343 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2344 .thenReturn(Color.WHITE);
2345 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2346 anyObject())).thenReturn(Color.WHITE);
2347
2348 // No bug reports were requested so far.
2349 assertEquals(-1, getLastSecurityLogRetrievalTime());
2350
2351 // Requesting a bug report should update the timestamp.
2352 final long beforeRequest = System.currentTimeMillis();
2353 dpm.requestBugreport(admin1);
2354 final long bugReportRequestTime = getLastBugReportRequestTime();
2355 final long afterRequest = System.currentTimeMillis();
2356 assertTrue(bugReportRequestTime >= beforeRequest);
2357 assertTrue(bugReportRequestTime <= afterRequest);
2358
2359 // Checking the timestamp again should not change it.
2360 Thread.sleep(2);
2361 assertEquals(bugReportRequestTime, getLastBugReportRequestTime());
2362
2363 // Restarting the DPMS should not lose the timestamp.
2364 initializeDpms();
2365 assertEquals(bugReportRequestTime, getLastBugReportRequestTime());
2366 }
2367
2368 private long getLastNetworkLogRetrievalTime() {
2369 final long ident = mContext.binder.clearCallingIdentity();
2370 final long lastNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
2371 mContext.binder.restoreCallingIdentity(ident);
2372 return lastNetworkLogRetrievalTime;
2373 }
2374
2375 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2376 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2377 setupDeviceOwner();
2378 when(mContext.userManager.getUserCount()).thenReturn(1);
2379 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2380 .thenReturn(true);
2381
2382 // No logs were retrieved so far.
2383 assertEquals(-1, getLastNetworkLogRetrievalTime());
2384
2385 // Attempting to retrieve logs without enabling logging should not change the timestamp.
2386 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
2387 assertEquals(-1, getLastNetworkLogRetrievalTime());
2388
2389 // Enabling logging should not change the timestamp.
2390 dpm.setNetworkLoggingEnabled(admin1, true);
2391 assertEquals(-1, getLastNetworkLogRetrievalTime());
2392
2393 // Retrieving the logs should update the timestamp.
2394 final long beforeRetrieval = System.currentTimeMillis();
2395 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
2396 final long firstNetworkLogRetrievalTime = getLastNetworkLogRetrievalTime();
2397 final long afterRetrieval = System.currentTimeMillis();
2398 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
2399 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
2400
2401 // Checking the timestamp again should not change it.
2402 Thread.sleep(2);
2403 assertEquals(firstNetworkLogRetrievalTime, getLastNetworkLogRetrievalTime());
2404
2405 // Retrieving the logs again should update the timestamp.
2406 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
2407 final long secondNetworkLogRetrievalTime = getLastNetworkLogRetrievalTime();
2408 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
2409
2410 // Disabling logging should not change the timestamp.
2411 Thread.sleep(2);
2412 dpm.setNetworkLoggingEnabled(admin1, false);
2413 assertEquals(secondNetworkLogRetrievalTime, getLastNetworkLogRetrievalTime());
2414
2415 // Restarting the DPMS should not lose the timestamp.
2416 initializeDpms();
2417 assertEquals(secondNetworkLogRetrievalTime, getLastNetworkLogRetrievalTime());
2418 }
2419
Victor Chang3e794af2016-03-04 13:48:17 +00002420 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
2421 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
2422 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
2423 dpms.notifyChangeToContentObserver(
2424 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
2425 }
2426
2427 private void assertProvisioningAllowed(String action, boolean expected) {
2428 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
2429 dpm.isProvisioningAllowed(action));
2430 }
2431}