blob: 3d7b853e575515f5ebaf0a8c09034a96fc4b1ba3 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Makoto Onukif76b06a2015-09-22 15:03:44 -070018import android.Manifest.permission;
19import android.app.Activity;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070020import android.app.admin.DeviceAdminReceiver;
21import android.app.admin.DevicePolicyManager;
22import android.app.admin.DevicePolicyManagerInternal;
Makoto Onukif76b06a2015-09-22 15:03:44 -070023import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070024import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000025import android.content.Context;
26import android.content.Intent;
27import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000028import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070030import android.content.pm.PackageManager;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010031import android.content.res.Resources;
32import android.graphics.Color;
33import android.net.IIpConnectivityMetrics;
Tony Mak2f26b792016-11-28 17:54:51 +000034import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080035import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080036import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070037import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000038import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080039import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070040import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070041import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080042import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000043import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080044import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000045import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010046import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070047import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070048
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010049import com.android.internal.R;
Alan Treadwayafad8782016-01-19 15:15:08 +000050import com.android.server.LocalServices;
51import com.android.server.SystemService;
52
Makoto Onukib643fb02015-09-22 15:03:44 -070053import org.mockito.invocation.InvocationOnMock;
54import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070055
Makoto Onukic8a5a552015-11-19 14:29:12 -080056import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000057import java.util.Arrays;
Makoto Onukib643fb02015-09-22 15:03:44 -070058import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070059import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070060import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010061import java.util.Set;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070062
63import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070064import static org.mockito.Matchers.anyInt;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010065import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070066import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070067import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070068import static org.mockito.Matchers.isNull;
Makoto Onukib643fb02015-09-22 15:03:44 -070069import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070070import static org.mockito.Mockito.doReturn;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080071import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070072import static org.mockito.Mockito.times;
73import static org.mockito.Mockito.verify;
74import static org.mockito.Mockito.when;
75
76/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070077 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070078 *
79 m FrameworksServicesTests &&
80 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000081 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070082 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080083 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070084
85 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
86 */
Benjamin Franz6d009032016-01-25 18:56:38 +000087@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070088public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000089 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
90 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
91 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
92
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070093 private DpmMockContext mContext;
94 public DevicePolicyManager dpm;
95 public DevicePolicyManagerServiceTestable dpms;
96
97 @Override
98 protected void setUp() throws Exception {
99 super.setUp();
100
101 mContext = getContext();
102
103 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
104 .thenReturn(true);
105
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800106 // By default, pretend all users are running and unlocked.
107 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
108
Makoto Onukia52562c2015-10-01 16:12:31 -0700109 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700110
Makoto Onukid932f762015-09-29 16:53:38 -0700111 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
112 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
113 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800114 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700115
Makoto Onukib643fb02015-09-22 15:03:44 -0700116 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700117 }
118
Makoto Onukia52562c2015-10-01 16:12:31 -0700119 private void initializeDpms() {
120 // Need clearCallingIdentity() to pass permission checks.
121 final long ident = mContext.binder.clearCallingIdentity();
122 try {
123 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
124
125 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
126
127 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
128 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
129
130 dpm = new DevicePolicyManagerTestable(mContext, dpms);
131 } finally {
132 mContext.binder.restoreCallingIdentity(ident);
133 }
134 }
135
Makoto Onukib643fb02015-09-22 15:03:44 -0700136 private void setUpUserManager() {
137 // Emulate UserManager.set/getApplicationRestriction().
138 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
139
140 // UM.setApplicationRestrictions() will save to appRestrictions.
141 doAnswer(new Answer<Void>() {
142 @Override
143 public Void answer(InvocationOnMock invocation) throws Throwable {
144 String pkg = (String) invocation.getArguments()[0];
145 Bundle bundle = (Bundle) invocation.getArguments()[1];
146 UserHandle user = (UserHandle) invocation.getArguments()[2];
147
148 appRestrictions.put(Pair.create(pkg, user), bundle);
149
150 return null;
151 }
152 }).when(mContext.userManager).setApplicationRestrictions(
153 anyString(), any(Bundle.class), any(UserHandle.class));
154
155 // UM.getApplicationRestrictions() will read from appRestrictions.
156 doAnswer(new Answer<Bundle>() {
157 @Override
158 public Bundle answer(InvocationOnMock invocation) throws Throwable {
159 String pkg = (String) invocation.getArguments()[0];
160 UserHandle user = (UserHandle) invocation.getArguments()[1];
161
162 return appRestrictions.get(Pair.create(pkg, user));
163 }
164 }).when(mContext.userManager).getApplicationRestrictions(
165 anyString(), any(UserHandle.class));
166
Makoto Onukid932f762015-09-29 16:53:38 -0700167 // Add the first secondary user.
168 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700169 }
170
171 private void setAsProfileOwner(ComponentName admin) {
172 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
173 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
174
Makoto Onukia4f11972015-10-01 13:19:58 -0700175 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700176 dpm.setActiveAdmin(admin, /* replace =*/ false);
177
178 // Fire!
179 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
180
181 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700182 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700183 }
184
185 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700186 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
187 .thenReturn(false);
188
189 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
190 new DevicePolicyManagerServiceTestable(mContext, dataDir);
191
192 // If the device has no DPMS feature, it shouldn't register the local service.
193 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
194 }
195
196 /**
197 * Caller doesn't have proper permissions.
198 */
199 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700200 // 1. Failure cases.
201
202 // Caller doesn't have MANAGE_DEVICE_ADMINS.
203 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700204 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700205 fail("Didn't throw SecurityException");
206 } catch (SecurityException expected) {
207 }
208
209 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
210 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
211 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700212 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700213 fail("Didn't throw SecurityException");
214 } catch (SecurityException expected) {
215 }
216 }
217
Makoto Onukif76b06a2015-09-22 15:03:44 -0700218 /**
219 * Test for:
220 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800221 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700222 * {@link DevicePolicyManager#isAdminActive}
223 * {@link DevicePolicyManager#isAdminActiveAsUser}
224 * {@link DevicePolicyManager#getActiveAdmins}
225 * {@link DevicePolicyManager#getActiveAdminsAsUser}
226 */
227 public void testSetActiveAdmin() throws Exception {
228 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700229 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
230
Makoto Onukif76b06a2015-09-22 15:03:44 -0700231 // 2. Call the API.
232 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700233
234 // 3. Verify internal calls.
235
236 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700237 verify(mContext.spiedContext).sendBroadcastAsUser(
238 MockUtils.checkIntentAction(
239 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
240 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
241 verify(mContext.spiedContext).sendBroadcastAsUser(
242 MockUtils.checkIntentAction(
243 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700244 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
245
Makoto Onukif76b06a2015-09-22 15:03:44 -0700246 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
247 eq(admin1.getPackageName()),
248 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
249 eq(PackageManager.DONT_KILL_APP),
250 eq(DpmMockContext.CALLER_USER_HANDLE),
251 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700252
253 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700254
255 // Make sure it's active admin1.
256 assertTrue(dpm.isAdminActive(admin1));
257 assertFalse(dpm.isAdminActive(admin2));
258 assertFalse(dpm.isAdminActive(admin3));
259
260 // But not admin1 for a different user.
261
262 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
263 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
264 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
265
266 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
267 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
268
269 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
270
271 // Next, add one more admin.
272 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700273 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
274 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700275
276 dpm.setActiveAdmin(admin2, /* replace =*/ false);
277
278 // Now we have two admins.
279 assertTrue(dpm.isAdminActive(admin1));
280 assertTrue(dpm.isAdminActive(admin2));
281 assertFalse(dpm.isAdminActive(admin3));
282
283 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
284 // again. (times(1) because it was previously called for admin1)
285 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
286 eq(admin1.getPackageName()),
287 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
288 eq(PackageManager.DONT_KILL_APP),
289 eq(DpmMockContext.CALLER_USER_HANDLE),
290 anyString());
291
292 // 4. Add the same admin1 again without replace, which should throw.
293 try {
294 dpm.setActiveAdmin(admin1, /* replace =*/ false);
295 fail("Didn't throw");
296 } catch (IllegalArgumentException expected) {
297 }
298
299 // 5. Add the same admin1 again with replace, which should succeed.
300 dpm.setActiveAdmin(admin1, /* replace =*/ true);
301
302 // TODO make sure it's replaced.
303
304 // 6. Test getActiveAdmins()
305 List<ComponentName> admins = dpm.getActiveAdmins();
306 assertEquals(2, admins.size());
307 assertEquals(admin1, admins.get(0));
308 assertEquals(admin2, admins.get(1));
309
310 // Another user has no admins.
311 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
312
313 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
314 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
315
316 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
317 }
318
Makoto Onukid932f762015-09-29 16:53:38 -0700319 public void testSetActiveAdmin_multiUsers() throws Exception {
320
321 final int ANOTHER_USER_ID = 100;
322 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
323
324 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
325
326 // Set up pacakge manager for the other user.
327 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700328
329 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
330
331 dpm.setActiveAdmin(admin1, /* replace =*/ false);
332
333 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
334 dpm.setActiveAdmin(admin2, /* replace =*/ false);
335
336
337 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
338 assertTrue(dpm.isAdminActive(admin1));
339 assertFalse(dpm.isAdminActive(admin2));
340
341 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
342 assertFalse(dpm.isAdminActive(admin1));
343 assertTrue(dpm.isAdminActive(admin2));
344 }
345
Makoto Onukif76b06a2015-09-22 15:03:44 -0700346 /**
347 * Test for:
348 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800349 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700350 */
351 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
352 // 1. Make sure the caller has proper permissions.
353 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
354
355 dpm.setActiveAdmin(admin1, /* replace =*/ false);
356 assertTrue(dpm.isAdminActive(admin1));
357
358 // Add the same admin1 again without replace, which should throw.
359 try {
360 dpm.setActiveAdmin(admin1, /* replace =*/ false);
361 fail("Didn't throw");
362 } catch (IllegalArgumentException expected) {
363 }
364 }
365
366 /**
367 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800368 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
369 * BIND_DEVICE_ADMIN.
370 */
371 public void testSetActiveAdmin_permissionCheck() throws Exception {
372 // 1. Make sure the caller has proper permissions.
373 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
374
375 try {
376 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
377 fail();
378 } catch (IllegalArgumentException expected) {
379 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
380 }
381 assertFalse(dpm.isAdminActive(adminNoPerm));
382
383 // Change the target API level to MNC. Now it can be set as DA.
384 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
385 VERSION_CODES.M);
386 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
387 assertTrue(dpm.isAdminActive(adminNoPerm));
388
389 // TODO Test the "load from the file" case where DA will still be loaded even without
390 // BIND_DEVICE_ADMIN and target API is N.
391 }
392
393 /**
394 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700395 * {@link DevicePolicyManager#removeActiveAdmin}
396 */
397 public void testRemoveActiveAdmin_SecurityException() {
398 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
399
400 // Add admin.
401
402 dpm.setActiveAdmin(admin1, /* replace =*/ false);
403
404 assertTrue(dpm.isAdminActive(admin1));
405
406 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
407
408 // Directly call the DPMS method with a different userid, which should fail.
409 try {
410 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
411 fail("Didn't throw SecurityException");
412 } catch (SecurityException expected) {
413 }
414
415 // Try to remove active admin with a different caller userid should fail too, without
416 // having MANAGE_DEVICE_ADMINS.
417 mContext.callerPermissions.clear();
418
Makoto Onukid932f762015-09-29 16:53:38 -0700419 // Change the caller, and call into DPMS directly with a different user-id.
420
Makoto Onukif76b06a2015-09-22 15:03:44 -0700421 mContext.binder.callingUid = 1234567;
422 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700423 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700424 fail("Didn't throw SecurityException");
425 } catch (SecurityException expected) {
426 }
427 }
428
429 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800430 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
431 * (because we can't send the remove broadcast).
432 */
433 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
434 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
435
436 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
437
438 // Add admin.
439
440 dpm.setActiveAdmin(admin1, /* replace =*/ false);
441
442 assertTrue(dpm.isAdminActive(admin1));
443
444 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
445
446 // 1. User not unlocked.
447 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
448 .thenReturn(false);
449 try {
450 dpm.removeActiveAdmin(admin1);
451 fail("Didn't throw IllegalStateException");
452 } catch (IllegalStateException expected) {
453 MoreAsserts.assertContainsRegex(
454 "User must be running and unlocked", expected.getMessage());
455 }
456
457 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
458
459 // 2. User unlocked.
460 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
461 .thenReturn(true);
462
463 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700464 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800465 }
466
467 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700468 * Test for:
469 * {@link DevicePolicyManager#removeActiveAdmin}
470 */
Makoto Onukid932f762015-09-29 16:53:38 -0700471 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700472 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
473
474 // Add admin1.
475
476 dpm.setActiveAdmin(admin1, /* replace =*/ false);
477
478 assertTrue(dpm.isAdminActive(admin1));
479 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
480
481 // Different user, but should work, because caller has proper permissions.
482 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700483
484 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700485 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700486
487 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700488 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700489
490 // TODO DO Still can't be removed in this case.
491 }
492
493 /**
494 * Test for:
495 * {@link DevicePolicyManager#removeActiveAdmin}
496 */
497 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
498 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
499 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
500
501 // Add admin1.
502
503 dpm.setActiveAdmin(admin1, /* replace =*/ false);
504
505 assertTrue(dpm.isAdminActive(admin1));
506 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
507
508 // Broadcast from saveSettingsLocked().
509 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
510 MockUtils.checkIntentAction(
511 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
512 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
513
514 // Remove. No permissions, but same user, so it'll work.
515 mContext.callerPermissions.clear();
516 dpm.removeActiveAdmin(admin1);
517
Makoto Onukif76b06a2015-09-22 15:03:44 -0700518 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
519 MockUtils.checkIntentAction(
520 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
521 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
522 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700523 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700524 eq(dpms.mHandler),
525 eq(Activity.RESULT_OK),
526 isNull(String.class),
527 isNull(Bundle.class));
528
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700529 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700530
531 // Again broadcast from saveSettingsLocked().
532 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
533 MockUtils.checkIntentAction(
534 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
535 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
536
537 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700538 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700539
540 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000541 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700542 */
543 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000544 setDeviceOwner();
545
546 // Try to set a profile owner on the same user, which should fail.
547 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
548 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
549 try {
550 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
551 fail("IllegalStateException not thrown");
552 } catch (IllegalStateException expected) {
553 assertTrue("Message was: " + expected.getMessage(),
554 expected.getMessage().contains("already has a device owner"));
555 }
556
557 // DO admin can't be deactivated.
558 dpm.removeActiveAdmin(admin1);
559 assertTrue(dpm.isAdminActive(admin1));
560
561 // TODO Test getDeviceOwnerName() too. To do so, we need to change
562 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
563 }
564
565 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700566 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800567 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700568 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
569 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
570
Makoto Onukid932f762015-09-29 16:53:38 -0700571 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700572 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
573
Makoto Onukid932f762015-09-29 16:53:38 -0700574 // Make sure admin1 is installed on system user.
575 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700576
Makoto Onukic8a5a552015-11-19 14:29:12 -0800577 // Check various get APIs.
578 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
579
Makoto Onukib643fb02015-09-22 15:03:44 -0700580 // DO needs to be an DA.
581 dpm.setActiveAdmin(admin1, /* replace =*/ false);
582
583 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700584 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700585
Makoto Onukic8a5a552015-11-19 14:29:12 -0800586 // getDeviceOwnerComponent should return the admin1 component.
587 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
588 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
589
590 // Check various get APIs.
591 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
592
593 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
594 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
595 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
596 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
597
598 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
599
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000600 // Verify internal calls.
601 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
602 eq(admin1.getPackageName()));
603
Makoto Onukib643fb02015-09-22 15:03:44 -0700604 // TODO We should check if the caller has called clearCallerIdentity().
605 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
606 eq(UserHandle.USER_SYSTEM), eq(false));
607
608 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
609 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
610 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
611
Makoto Onukic8a5a552015-11-19 14:29:12 -0800612 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700613 }
614
Makoto Onukic8a5a552015-11-19 14:29:12 -0800615 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
616 final int origCallingUser = mContext.binder.callingUid;
617 final List origPermissions = new ArrayList(mContext.callerPermissions);
618 mContext.callerPermissions.clear();
619
620 mContext.callerPermissions.add(permission.MANAGE_USERS);
621
622 mContext.binder.callingUid = Process.SYSTEM_UID;
623
624 // TODO Test getDeviceOwnerName() too. To do so, we need to change
625 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
626 if (hasDeviceOwner) {
627 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
628 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
629 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
630
631 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
632 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
633 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
634 } else {
635 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
636 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
637 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
638
639 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
640 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
641 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
642 }
643
644 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
645 if (hasDeviceOwner) {
646 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
647 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
648 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
649
650 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
651 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
652 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
653 } else {
654 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
655 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
656 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
657
658 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
659 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
660 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
661 }
662
663 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
664 // Still with MANAGE_USERS.
665 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
666 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
667 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
668
669 if (hasDeviceOwner) {
670 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
671 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
672 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
673 } else {
674 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
675 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
676 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
677 }
678
679 mContext.binder.callingUid = Process.SYSTEM_UID;
680 mContext.callerPermissions.remove(permission.MANAGE_USERS);
681 // System can still call "OnAnyUser" without MANAGE_USERS.
682 if (hasDeviceOwner) {
683 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
684 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
685 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
686
687 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
688 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
689 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
690 } else {
691 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
692 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
693 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
694
695 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
696 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
697 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
698 }
699
700 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
701 // Still no MANAGE_USERS.
702 if (hasDeviceOwner) {
703 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
704 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
705 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
706 } else {
707 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
708 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
709 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
710 }
711
712 try {
713 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
714 fail();
715 } catch (SecurityException expected) {
716 }
717 try {
718 dpm.getDeviceOwnerComponentOnAnyUser();
719 fail();
720 } catch (SecurityException expected) {
721 }
722 try {
723 dpm.getDeviceOwnerUserId();
724 fail();
725 } catch (SecurityException expected) {
726 }
727 try {
728 dpm.getDeviceOwnerNameOnAnyUser();
729 fail();
730 } catch (SecurityException expected) {
731 }
732
733 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
734 // Still no MANAGE_USERS.
735 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
736 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
737 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
738
739 try {
740 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
741 fail();
742 } catch (SecurityException expected) {
743 }
744 try {
745 dpm.getDeviceOwnerComponentOnAnyUser();
746 fail();
747 } catch (SecurityException expected) {
748 }
749 try {
750 dpm.getDeviceOwnerUserId();
751 fail();
752 } catch (SecurityException expected) {
753 }
754 try {
755 dpm.getDeviceOwnerNameOnAnyUser();
756 fail();
757 } catch (SecurityException expected) {
758 }
759
760 // Restore.
761 mContext.binder.callingUid = origCallingUser;
762 mContext.callerPermissions.addAll(origPermissions);
763 }
764
765
Makoto Onukib643fb02015-09-22 15:03:44 -0700766 /**
767 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
768 */
769 public void testSetDeviceOwner_noSuchPackage() {
770 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800771 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700772 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
773 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
774
775 // Call from a process on the system user.
776 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
777
Makoto Onukib643fb02015-09-22 15:03:44 -0700778 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700779 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700780 fail("Didn't throw IllegalArgumentException");
781 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700782 assertTrue("Message was: " + expected.getMessage(),
783 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700784 }
785 }
786
787 public void testSetDeviceOwner_failures() throws Exception {
788 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
789 }
790
Makoto Onukia52562c2015-10-01 16:12:31 -0700791 public void testClearDeviceOwner() throws Exception {
792 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800793 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700794 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
795 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
796
797 // Set admin1 as a DA to the secondary user.
798 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
799
800 dpm.setActiveAdmin(admin1, /* replace =*/ false);
801
802 // Set admin 1 as the DO to the system user.
803
804 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
805 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
806 dpm.setActiveAdmin(admin1, /* replace =*/ false);
807 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
808
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000809 // Verify internal calls.
810 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
811 eq(admin1.getPackageName()));
812
Makoto Onukic8a5a552015-11-19 14:29:12 -0800813 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700814
Makoto Onuki90b89652016-01-28 14:44:18 -0800815 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
816
817 assertTrue(dpm.isAdminActive(admin1));
818 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
819
Makoto Onukia52562c2015-10-01 16:12:31 -0700820 // Set up other mocks.
821 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
822
823 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700824 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700825 eq(admin1.getPackageName()),
826 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800827
828 // But first pretend the user is locked. Then it should fail.
829 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
830 try {
831 dpm.clearDeviceOwnerApp(admin1.getPackageName());
832 fail("Didn't throw IllegalStateException");
833 } catch (IllegalStateException expected) {
834 MoreAsserts.assertContainsRegex(
835 "User must be running and unlocked", expected.getMessage());
836 }
837
838 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800839 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700840 dpm.clearDeviceOwnerApp(admin1.getPackageName());
841
842 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800843 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700844
Makoto Onuki90b89652016-01-28 14:44:18 -0800845 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
846 eq(UserHandle.USER_SYSTEM),
847 MockUtils.checkUserRestrictions(),
848 MockUtils.checkUserRestrictions()
849 );
850
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700851 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100852
853 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
854 // and once for clearing it.
855 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
856 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
857 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700858 // TODO Check other calls.
859 }
860
861 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
862 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800863 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700864 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
865 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
866
867 // Set admin1 as a DA to the secondary user.
868 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
869
870 dpm.setActiveAdmin(admin1, /* replace =*/ false);
871
872 // Set admin 1 as the DO to the system user.
873
874 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
875 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
876 dpm.setActiveAdmin(admin1, /* replace =*/ false);
877 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
878
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000879 // Verify internal calls.
880 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
881 eq(admin1.getPackageName()));
882
Makoto Onukic8a5a552015-11-19 14:29:12 -0800883 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700884
885 // Now call clear from the secondary user, which should throw.
886 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
887
888 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700889 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700890 eq(admin1.getPackageName()),
891 anyInt());
892 try {
893 dpm.clearDeviceOwnerApp(admin1.getPackageName());
894 fail("Didn't throw");
895 } catch (SecurityException e) {
896 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
897 }
898
Makoto Onukic8a5a552015-11-19 14:29:12 -0800899 // DO shouldn't be removed.
900 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700901 }
902
Makoto Onukib643fb02015-09-22 15:03:44 -0700903 public void testSetProfileOwner() throws Exception {
904 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700905
Makoto Onuki90b89652016-01-28 14:44:18 -0800906 // PO admin can't be deactivated.
907 dpm.removeActiveAdmin(admin1);
908 assertTrue(dpm.isAdminActive(admin1));
909
Makoto Onuki803d6752015-10-30 12:58:39 -0700910 // Try setting DO on the same user, which should fail.
911 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
912 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
913 try {
914 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
915 fail("IllegalStateException not thrown");
916 } catch (IllegalStateException expected) {
917 assertTrue("Message was: " + expected.getMessage(),
918 expected.getMessage().contains("already has a profile owner"));
919 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700920 }
921
Makoto Onuki90b89652016-01-28 14:44:18 -0800922 public void testClearProfileOwner() throws Exception {
923 setAsProfileOwner(admin1);
924
925 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
926
927 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
928 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
929
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800930 // First try when the user is locked, which should fail.
931 when(mContext.userManager.isUserUnlocked(anyInt()))
932 .thenReturn(false);
933 try {
934 dpm.clearProfileOwner(admin1);
935 fail("Didn't throw IllegalStateException");
936 } catch (IllegalStateException expected) {
937 MoreAsserts.assertContainsRegex(
938 "User must be running and unlocked", expected.getMessage());
939 }
940 // Clear, really.
941 when(mContext.userManager.isUserUnlocked(anyInt()))
942 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800943 dpm.clearProfileOwner(admin1);
944
945 // Check
946 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700947 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -0800948 }
949
Makoto Onukib643fb02015-09-22 15:03:44 -0700950 public void testSetProfileOwner_failures() throws Exception {
951 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
952 }
953
Makoto Onukia52562c2015-10-01 16:12:31 -0700954 public void testGetDeviceOwnerAdminLocked() throws Exception {
955 checkDeviceOwnerWithMultipleDeviceAdmins();
956 }
957
958 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
959 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
960 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
961 // make sure it gets the right component from the right user.
962
963 final int ANOTHER_USER_ID = 100;
964 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
965
966 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
967
968 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800969 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700970 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
971 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
972
973 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
974
Victor Change29cd472016-03-02 20:57:42 +0000975 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
976
Makoto Onukia52562c2015-10-01 16:12:31 -0700977 // Make sure the admin packge is installed to each user.
978 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
979 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
980
981 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
982 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
983
984 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
985
986
987 // Set active admins to the users.
988 dpm.setActiveAdmin(admin1, /* replace =*/ false);
989 dpm.setActiveAdmin(admin3, /* replace =*/ false);
990
991 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
992 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
993
994 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
995
996 // Set DO on the first non-system user.
997 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
998 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
999
Makoto Onukic8a5a552015-11-19 14:29:12 -08001000 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001001
1002 // Then check getDeviceOwnerAdminLocked().
1003 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1004 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1005 }
1006
1007 /**
1008 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001009 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1010 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001011 *
1012 * We didn't use to persist the DO component class name, but now we do, and the above method
1013 * finds the right component from a package name upon migration.
1014 */
1015 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001016 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001017 checkDeviceOwnerWithMultipleDeviceAdmins();
1018
1019 // Overwrite the device owner setting and clears the clas name.
1020 dpms.mOwners.setDeviceOwner(
1021 new ComponentName(admin2.getPackageName(), ""),
1022 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1023 dpms.mOwners.writeDeviceOwner();
1024
1025 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001026 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001027
1028 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001029 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1030 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001031 initializeDpms();
1032
1033 // Now the DO component name is a full name.
1034 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1035 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001036 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001037 }
1038
Makoto Onukib643fb02015-09-22 15:03:44 -07001039 public void testSetGetApplicationRestriction() {
1040 setAsProfileOwner(admin1);
1041
1042 {
1043 Bundle rest = new Bundle();
1044 rest.putString("KEY_STRING", "Foo1");
1045 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1046 }
1047
1048 {
1049 Bundle rest = new Bundle();
1050 rest.putString("KEY_STRING", "Foo2");
1051 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1052 }
1053
1054 {
1055 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1056 assertNotNull(returned);
1057 assertEquals(returned.size(), 1);
1058 assertEquals(returned.get("KEY_STRING"), "Foo1");
1059 }
1060
1061 {
1062 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1063 assertNotNull(returned);
1064 assertEquals(returned.size(), 1);
1065 assertEquals(returned.get("KEY_STRING"), "Foo2");
1066 }
1067
1068 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1069 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1070 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001071
Esteban Talaverabf60f722015-12-10 16:26:44 +00001072 public void testApplicationRestrictionsManagingApp() throws Exception {
1073 setAsProfileOwner(admin1);
1074
Rubin Xued1928a2016-02-11 17:23:06 +00001075 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001076 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1077 final int appRestrictionsManagerAppId = 20987;
1078 final int appRestrictionsManagerUid = UserHandle.getUid(
1079 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001080 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001081 eq(appRestrictionsManagerPackage),
1082 eq(DpmMockContext.CALLER_USER_HANDLE));
1083 mContext.binder.callingUid = appRestrictionsManagerUid;
1084
Rubin Xued1928a2016-02-11 17:23:06 +00001085 final PackageInfo pi = new PackageInfo();
1086 pi.applicationInfo = new ApplicationInfo();
1087 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1088 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1089 eq(appRestrictionsManagerPackage),
1090 anyInt(),
1091 eq(DpmMockContext.CALLER_USER_HANDLE));
1092
Esteban Talaverabf60f722015-12-10 16:26:44 +00001093 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1094 // delegated that permission yet.
1095 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1096 Bundle rest = new Bundle();
1097 rest.putString("KEY_STRING", "Foo1");
1098 try {
1099 dpm.setApplicationRestrictions(null, "pkg1", rest);
1100 fail("Didn't throw expected SecurityException");
1101 } catch (SecurityException expected) {
1102 MoreAsserts.assertContainsRegex(
1103 "caller cannot manage application restrictions", expected.getMessage());
1104 }
1105 try {
1106 dpm.getApplicationRestrictions(null, "pkg1");
1107 fail("Didn't throw expected SecurityException");
1108 } catch (SecurityException expected) {
1109 MoreAsserts.assertContainsRegex(
1110 "caller cannot manage application restrictions", expected.getMessage());
1111 }
1112
1113 // Check via the profile owner that no restrictions were set.
1114 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1115 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1116
Rubin Xued1928a2016-02-11 17:23:06 +00001117 // Check the API does not allow setting a non-existent package
1118 try {
1119 dpm.setApplicationRestrictionsManagingPackage(admin1,
1120 nonExistAppRestrictionsManagerPackage);
1121 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001122 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001123 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001124 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001125 }
1126
Esteban Talaverabf60f722015-12-10 16:26:44 +00001127 // Let appRestrictionsManagerPackage manage app restrictions
1128 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1129 assertEquals(appRestrictionsManagerPackage,
1130 dpm.getApplicationRestrictionsManagingPackage(admin1));
1131
1132 // Now that package should be able to set and retrieve app restrictions.
1133 mContext.binder.callingUid = appRestrictionsManagerUid;
1134 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1135 dpm.setApplicationRestrictions(null, "pkg1", rest);
1136 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1137 assertEquals(1, returned.size(), 1);
1138 assertEquals("Foo1", returned.get("KEY_STRING"));
1139
1140 // The same app running on a separate user shouldn't be able to manage app restrictions.
1141 mContext.binder.callingUid = UserHandle.getUid(
1142 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1143 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1144 try {
1145 dpm.setApplicationRestrictions(null, "pkg1", rest);
1146 fail("Didn't throw expected SecurityException");
1147 } catch (SecurityException expected) {
1148 MoreAsserts.assertContainsRegex(
1149 "caller cannot manage application restrictions", expected.getMessage());
1150 }
1151
1152 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1153 // too.
1154 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1155 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1156 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1157 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1158
1159 // Removing the ability for the package to manage app restrictions.
1160 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1161 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1162 mContext.binder.callingUid = appRestrictionsManagerUid;
1163 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1164 try {
1165 dpm.setApplicationRestrictions(null, "pkg1", null);
1166 fail("Didn't throw expected SecurityException");
1167 } catch (SecurityException expected) {
1168 MoreAsserts.assertContainsRegex(
1169 "caller cannot manage application restrictions", expected.getMessage());
1170 }
1171 }
1172
Makoto Onukia4f11972015-10-01 13:19:58 -07001173 public void testSetUserRestriction_asDo() throws Exception {
1174 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001175 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001176 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1177 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1178
1179 // First, set DO.
1180
1181 // Call from a process on the system user.
1182 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1183
1184 // Make sure admin1 is installed on system user.
1185 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001186
1187 // Call.
1188 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001189 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001190 UserHandle.USER_SYSTEM));
1191
Makoto Onuki068c54a2015-10-13 14:34:03 -07001192 DpmTestUtils.assertRestrictions(
1193 DpmTestUtils.newRestrictions(),
1194 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1195 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001196 DpmTestUtils.assertRestrictions(
1197 DpmTestUtils.newRestrictions(),
1198 dpm.getUserRestrictions(admin1)
1199 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001200
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001201 reset(mContext.userManagerInternal);
1202
1203 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1204 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1205 eq(UserHandle.USER_SYSTEM),
1206 MockUtils.checkUserRestrictions(),
1207 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001208 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001209 reset(mContext.userManagerInternal);
1210
Makoto Onukia4f11972015-10-01 13:19:58 -07001211 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001212 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1213 eq(UserHandle.USER_SYSTEM),
1214 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1215 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1216 );
1217 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001218
Makoto Onuki068c54a2015-10-13 14:34:03 -07001219 DpmTestUtils.assertRestrictions(
1220 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001221 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001222 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1223 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001224 DpmTestUtils.assertRestrictions(
1225 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001226 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001227 dpm.getUserRestrictions(admin1)
1228 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001229
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001230 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1231 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1232 eq(UserHandle.USER_SYSTEM),
1233 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1234 MockUtils.checkUserRestrictions()
1235 );
1236 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001237
Makoto Onuki068c54a2015-10-13 14:34:03 -07001238 DpmTestUtils.assertRestrictions(
1239 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1240 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1241 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001242 DpmTestUtils.assertRestrictions(
1243 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1244 dpm.getUserRestrictions(admin1)
1245 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001246
1247 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001248 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1249 eq(UserHandle.USER_SYSTEM),
1250 MockUtils.checkUserRestrictions(),
1251 MockUtils.checkUserRestrictions()
1252 );
1253 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001254
Makoto Onuki068c54a2015-10-13 14:34:03 -07001255 DpmTestUtils.assertRestrictions(
1256 DpmTestUtils.newRestrictions(),
1257 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1258 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001259 DpmTestUtils.assertRestrictions(
1260 DpmTestUtils.newRestrictions(),
1261 dpm.getUserRestrictions(admin1)
1262 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001263
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001264 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1265 // DO sets them, the scope is global.
1266 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1267 reset(mContext.userManagerInternal);
1268 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1269 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1270 eq(UserHandle.USER_SYSTEM),
1271 MockUtils.checkUserRestrictions(),
1272 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1273 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1274 );
1275 reset(mContext.userManagerInternal);
1276
1277 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1278 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1279
1280
1281 // More tests.
1282 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1283 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1284 eq(UserHandle.USER_SYSTEM),
1285 MockUtils.checkUserRestrictions(),
1286 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1287 );
1288 reset(mContext.userManagerInternal);
1289
1290 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1291 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1292 eq(UserHandle.USER_SYSTEM),
1293 MockUtils.checkUserRestrictions(),
1294 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1295 UserManager.DISALLOW_ADD_USER)
1296 );
1297 reset(mContext.userManagerInternal);
1298
1299 dpm.setCameraDisabled(admin1, true);
1300 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1301 eq(UserHandle.USER_SYSTEM),
1302 // DISALLOW_CAMERA will be applied to both local and global.
1303 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1304 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1305 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1306 );
1307 reset(mContext.userManagerInternal);
1308
1309 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1310 // locally.
1311 dpm.setCameraDisabled(admin1, false);
1312 reset(mContext.userManagerInternal);
1313
1314 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1315 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1316 dpm.setCameraDisabled(admin2, true);
1317
1318 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1319 eq(UserHandle.USER_SYSTEM),
1320 // DISALLOW_CAMERA will be applied to both local and global.
1321 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1322 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1323 UserManager.DISALLOW_ADD_USER)
1324 );
1325 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001326 // TODO Make sure restrictions are written to the file.
1327 }
1328
1329 public void testSetUserRestriction_asPo() {
1330 setAsProfileOwner(admin1);
1331
Makoto Onuki068c54a2015-10-13 14:34:03 -07001332 DpmTestUtils.assertRestrictions(
1333 DpmTestUtils.newRestrictions(),
1334 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1335 .ensureUserRestrictions()
1336 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001337
1338 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001339 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1340 eq(DpmMockContext.CALLER_USER_HANDLE),
1341 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1342 isNull(Bundle.class)
1343 );
1344 reset(mContext.userManagerInternal);
1345
Makoto Onukia4f11972015-10-01 13:19:58 -07001346 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001347 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1348 eq(DpmMockContext.CALLER_USER_HANDLE),
1349 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1350 UserManager.DISALLOW_OUTGOING_CALLS),
1351 isNull(Bundle.class)
1352 );
1353 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001354
Makoto Onuki068c54a2015-10-13 14:34:03 -07001355 DpmTestUtils.assertRestrictions(
1356 DpmTestUtils.newRestrictions(
1357 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1358 UserManager.DISALLOW_OUTGOING_CALLS
1359 ),
1360 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1361 .ensureUserRestrictions()
1362 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001363 DpmTestUtils.assertRestrictions(
1364 DpmTestUtils.newRestrictions(
1365 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1366 UserManager.DISALLOW_OUTGOING_CALLS
1367 ),
1368 dpm.getUserRestrictions(admin1)
1369 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001370
1371 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001372 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1373 eq(DpmMockContext.CALLER_USER_HANDLE),
1374 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1375 isNull(Bundle.class)
1376 );
1377 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001378
1379 DpmTestUtils.assertRestrictions(
1380 DpmTestUtils.newRestrictions(
1381 UserManager.DISALLOW_OUTGOING_CALLS
1382 ),
1383 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1384 .ensureUserRestrictions()
1385 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001386 DpmTestUtils.assertRestrictions(
1387 DpmTestUtils.newRestrictions(
1388 UserManager.DISALLOW_OUTGOING_CALLS
1389 ),
1390 dpm.getUserRestrictions(admin1)
1391 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001392
1393 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001394 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1395 eq(DpmMockContext.CALLER_USER_HANDLE),
1396 MockUtils.checkUserRestrictions(),
1397 isNull(Bundle.class)
1398 );
1399 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001400
Makoto Onuki068c54a2015-10-13 14:34:03 -07001401 DpmTestUtils.assertRestrictions(
1402 DpmTestUtils.newRestrictions(),
1403 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1404 .ensureUserRestrictions()
1405 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001406 DpmTestUtils.assertRestrictions(
1407 DpmTestUtils.newRestrictions(),
1408 dpm.getUserRestrictions(admin1)
1409 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001410
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001411 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1412 // though when DO sets them they'll be applied globally.
1413 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1414 reset(mContext.userManagerInternal);
1415 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1416 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1417 eq(DpmMockContext.CALLER_USER_HANDLE),
1418 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1419 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1420 isNull(Bundle.class)
1421 );
1422 reset(mContext.userManagerInternal);
1423
1424 dpm.setCameraDisabled(admin1, true);
1425 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1426 eq(DpmMockContext.CALLER_USER_HANDLE),
1427 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1428 UserManager.DISALLOW_ADJUST_VOLUME,
1429 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1430 isNull(Bundle.class)
1431 );
1432 reset(mContext.userManagerInternal);
1433
Makoto Onukia4f11972015-10-01 13:19:58 -07001434 // TODO Make sure restrictions are written to the file.
1435 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001436
1437 public void testGetMacAddress() throws Exception {
1438 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1439 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1440 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1441
1442 // In this test, change the caller user to "system".
1443 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1444
1445 // Make sure admin1 is installed on system user.
1446 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1447
1448 // Test 1. Caller doesn't have DO or DA.
1449 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001450 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001451 fail();
1452 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001453 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001454 }
1455
1456 // DO needs to be an DA.
1457 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1458 assertTrue(dpm.isAdminActive(admin1));
1459
1460 // Test 2. Caller has DA, but not DO.
1461 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001462 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001463 fail();
1464 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001465 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001466 }
1467
1468 // Test 3. Caller has PO, but not DO.
1469 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1470 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001471 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001472 fail();
1473 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001474 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001475 }
1476
1477 // Remove PO.
1478 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001479 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001480 // Test 4, Caller is DO now.
1481 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1482
1483 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001484 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001485
1486 // 4-2. Returns WifiInfo, but with the default MAC.
1487 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001488 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001489
1490 // 4-3. With a real MAC address.
1491 final WifiInfo wi = new WifiInfo();
1492 wi.setMacAddress("11:22:33:44:55:66");
1493 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001494 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001495 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001496
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001497 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001498 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1499 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1500
1501 // In this test, change the caller user to "system".
1502 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1503
1504 // Make sure admin1 is installed on system user.
1505 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1506
1507 // Set admin1 as DA.
1508 dpm.setActiveAdmin(admin1, false);
1509 assertTrue(dpm.isAdminActive(admin1));
1510 try {
1511 dpm.reboot(admin1);
1512 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1513 } catch (SecurityException expected) {
1514 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1515 }
1516
1517 // Set admin1 as PO.
1518 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1519 try {
1520 dpm.reboot(admin1);
1521 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1522 } catch (SecurityException expected) {
1523 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1524 }
1525
1526 // Remove PO and add DO.
1527 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001528 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001529 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1530
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001531 // admin1 is DO.
1532 // Set current call state of device to ringing.
1533 when(mContext.telephonyManager.getCallState())
1534 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1535 try {
1536 dpm.reboot(admin1);
1537 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1538 } catch (IllegalStateException expected) {
1539 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1540 }
1541
1542 // Set current call state of device to dialing/active.
1543 when(mContext.telephonyManager.getCallState())
1544 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1545 try {
1546 dpm.reboot(admin1);
1547 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1548 } catch (IllegalStateException expected) {
1549 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1550 }
1551
1552 // Set current call state of device to idle.
1553 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001554 dpm.reboot(admin1);
1555 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001556
1557 public void testSetGetSupportText() {
1558 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1559 dpm.setActiveAdmin(admin1, true);
1560 dpm.setActiveAdmin(admin2, true);
1561 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1562
1563 // Null default support messages.
1564 {
1565 assertNull(dpm.getLongSupportMessage(admin1));
1566 assertNull(dpm.getShortSupportMessage(admin1));
1567 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1568 assertNull(dpm.getShortSupportMessageForUser(admin1,
1569 DpmMockContext.CALLER_USER_HANDLE));
1570 assertNull(dpm.getLongSupportMessageForUser(admin1,
1571 DpmMockContext.CALLER_USER_HANDLE));
1572 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1573 }
1574
1575 // Only system can call the per user versions.
1576 {
1577 try {
1578 dpm.getShortSupportMessageForUser(admin1,
1579 DpmMockContext.CALLER_USER_HANDLE);
1580 fail("Only system should be able to call getXXXForUser versions");
1581 } catch (SecurityException expected) {
1582 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1583 }
1584 try {
1585 dpm.getLongSupportMessageForUser(admin1,
1586 DpmMockContext.CALLER_USER_HANDLE);
1587 fail("Only system should be able to call getXXXForUser versions");
1588 } catch (SecurityException expected) {
1589 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1590 }
1591 }
1592
1593 // Can't set message for admin in another uid.
1594 {
1595 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1596 try {
1597 dpm.setShortSupportMessage(admin1, "Some text");
1598 fail("Admins should only be able to change their own support text.");
1599 } catch (SecurityException expected) {
1600 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1601 }
1602 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1603 }
1604
1605 // Set/Get short returns what it sets and other admins text isn't changed.
1606 {
1607 final String supportText = "Some text to test with.";
1608 dpm.setShortSupportMessage(admin1, supportText);
1609 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1610 assertNull(dpm.getLongSupportMessage(admin1));
1611 assertNull(dpm.getShortSupportMessage(admin2));
1612
1613 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1614 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1615 DpmMockContext.CALLER_USER_HANDLE));
1616 assertNull(dpm.getShortSupportMessageForUser(admin2,
1617 DpmMockContext.CALLER_USER_HANDLE));
1618 assertNull(dpm.getLongSupportMessageForUser(admin1,
1619 DpmMockContext.CALLER_USER_HANDLE));
1620 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1621
1622 dpm.setShortSupportMessage(admin1, null);
1623 assertNull(dpm.getShortSupportMessage(admin1));
1624 }
1625
1626 // Set/Get long returns what it sets and other admins text isn't changed.
1627 {
1628 final String supportText = "Some text to test with.\nWith more text.";
1629 dpm.setLongSupportMessage(admin1, supportText);
1630 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1631 assertNull(dpm.getShortSupportMessage(admin1));
1632 assertNull(dpm.getLongSupportMessage(admin2));
1633
1634 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1635 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1636 DpmMockContext.CALLER_USER_HANDLE));
1637 assertNull(dpm.getLongSupportMessageForUser(admin2,
1638 DpmMockContext.CALLER_USER_HANDLE));
1639 assertNull(dpm.getShortSupportMessageForUser(admin1,
1640 DpmMockContext.CALLER_USER_HANDLE));
1641 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1642
1643 dpm.setLongSupportMessage(admin1, null);
1644 assertNull(dpm.getLongSupportMessage(admin1));
1645 }
1646 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001647
1648 /**
1649 * Test for:
1650 * {@link DevicePolicyManager#setAffiliationIds}
1651 * {@link DevicePolicyManager#isAffiliatedUser}
1652 */
1653 public void testUserAffiliation() throws Exception {
1654 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1655 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1656 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1657
1658 // Check that the system user is unaffiliated.
1659 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1660 assertFalse(dpm.isAffiliatedUser());
1661
1662 // Set a device owner on the system user. Check that the system user becomes affiliated.
1663 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1664 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1665 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1666 assertTrue(dpm.isAffiliatedUser());
1667
1668 // Install a profile owner whose package name matches the device owner on a test user. Check
1669 // that the test user is unaffiliated.
1670 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1671 setAsProfileOwner(admin2);
1672 assertFalse(dpm.isAffiliatedUser());
1673
1674 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1675 // unaffiliated.
1676 final Set<String> userAffiliationIds = new ArraySet<>();
1677 userAffiliationIds.add("red");
1678 userAffiliationIds.add("green");
1679 userAffiliationIds.add("blue");
1680 dpm.setAffiliationIds(admin2, userAffiliationIds);
1681 assertFalse(dpm.isAffiliatedUser());
1682
1683 // Have the device owner specify a set of affiliation ids that do not intersect with those
1684 // specified by the profile owner. Check that the test user remains unaffiliated.
1685 final Set<String> deviceAffiliationIds = new ArraySet<>();
1686 deviceAffiliationIds.add("cyan");
1687 deviceAffiliationIds.add("yellow");
1688 deviceAffiliationIds.add("magenta");
1689 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1690 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
1691 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1692 assertFalse(dpm.isAffiliatedUser());
1693
1694 // Have the profile owner specify a set of affiliation ids that intersect with those
1695 // specified by the device owner. Check that the test user becomes affiliated.
1696 userAffiliationIds.add("yellow");
1697 dpm.setAffiliationIds(admin2, userAffiliationIds);
1698 assertTrue(dpm.isAffiliatedUser());
1699
1700 // Change the profile owner to one whose package name does not match the device owner. Check
1701 // that the test user is not affiliated anymore.
1702 dpm.clearProfileOwner(admin2);
1703 final ComponentName admin = new ComponentName("test", "test");
Makoto Onuki184db602016-02-17 15:35:01 -08001704
1705 setUpPackageManagerForFakeAdmin(admin, DpmMockContext.CALLER_UID,
1706 /* enabledSetting =*/ PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
1707 /* appTargetSdk = */ null, admin2);
1708
1709 dpm.setActiveAdmin(admin, /* refreshing =*/ true, DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001710 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1711 assertFalse(dpm.isAffiliatedUser());
1712
1713 // Check that the system user remains affiliated.
1714 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1715 assertTrue(dpm.isAffiliatedUser());
1716 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001717
1718 public void testGetUserProvisioningState_defaultResult() {
1719 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1720 }
1721
1722 public void testSetUserProvisioningState_permission() throws Exception {
1723 setupProfileOwner();
1724 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1725
1726 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1727 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1728 }
1729
1730 public void testSetUserProvisioningState_unprivileged() throws Exception {
1731 setupProfileOwner();
1732 try {
1733 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1734 DpmMockContext.CALLER_USER_HANDLE);
1735 fail("Expected SecurityException");
1736 } catch (SecurityException expected) {
1737 }
1738 }
1739
1740 public void testSetUserProvisioningState_noManagement() {
1741 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1742 try {
1743 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1744 DpmMockContext.CALLER_USER_HANDLE);
1745 fail("IllegalStateException expected");
1746 } catch (IllegalStateException e) {
1747 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1748 e.getMessage());
1749 }
1750 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1751 }
1752
1753 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1754 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1755 setupDeviceOwner();
1756 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1757
1758 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1759 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1760 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1761 }
1762
1763 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1764 throws Exception {
1765 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1766 setupDeviceOwner();
1767 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1768
1769 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1770 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1771 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1772 }
1773
1774 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1775 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1776 setupDeviceOwner();
1777 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1778
1779 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1780 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1781 }
1782
1783 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1784 throws Exception {
1785 setupProfileOwner();
1786 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1787
1788 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1789 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1790 DevicePolicyManager.STATE_USER_UNMANAGED);
1791 }
1792
1793 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1794 throws Exception {
1795 setupProfileOwner();
1796 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1797
1798 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1799 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1800 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1801 }
1802
1803 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1804 setupProfileOwner();
1805 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1806
1807 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1808 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1809 }
1810
1811 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
1812 setupProfileOwner();
1813 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1814
1815 try {
1816 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1817 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1818 DevicePolicyManager.STATE_USER_UNMANAGED);
1819 fail("Expected IllegalStateException");
1820 } catch (IllegalStateException e) {
1821 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1822 e.getMessage());
1823 }
1824 }
1825
1826 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
1827 throws Exception {
1828 setupProfileOwner();
1829 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1830
1831 try {
1832 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1833 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1834 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
1835 fail("Expected IllegalStateException");
1836 } catch (IllegalStateException e) {
1837 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1838 e.getMessage());
1839 }
1840 }
1841
1842 private void exerciseUserProvisioningTransitions(int userId, int... states) {
1843 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1844 for (int state : states) {
1845 dpm.setUserProvisioningState(state, userId);
1846 assertEquals(state, dpm.getUserProvisioningState());
1847 }
1848 }
1849
1850 private void setupProfileOwner() throws Exception {
1851 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1852
1853 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1854 dpm.setActiveAdmin(admin1, false);
1855 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
1856
1857 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1858 }
1859
1860 private void setupDeviceOwner() throws Exception {
1861 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1862
1863 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1864 dpm.setActiveAdmin(admin1, false);
1865 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1866
1867 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1868 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001869
1870 public void testSetMaximumTimeToLock() {
1871 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1872
1873 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1874 dpm.setActiveAdmin(admin2, /* replace =*/ false);
1875
1876 reset(mMockContext.powerManagerInternal);
1877 reset(mMockContext.settings);
1878
1879 dpm.setMaximumTimeToLock(admin1, 0);
1880 verifyScreenTimeoutCall(null, false);
1881 reset(mMockContext.powerManagerInternal);
1882 reset(mMockContext.settings);
1883
1884 dpm.setMaximumTimeToLock(admin1, 1);
1885 verifyScreenTimeoutCall(1, true);
1886 reset(mMockContext.powerManagerInternal);
1887 reset(mMockContext.settings);
1888
1889 dpm.setMaximumTimeToLock(admin2, 10);
1890 verifyScreenTimeoutCall(null, false);
1891 reset(mMockContext.powerManagerInternal);
1892 reset(mMockContext.settings);
1893
1894 dpm.setMaximumTimeToLock(admin1, 5);
1895 verifyScreenTimeoutCall(5, true);
1896 reset(mMockContext.powerManagerInternal);
1897 reset(mMockContext.settings);
1898
1899 dpm.setMaximumTimeToLock(admin2, 4);
1900 verifyScreenTimeoutCall(4, true);
1901 reset(mMockContext.powerManagerInternal);
1902 reset(mMockContext.settings);
1903
1904 dpm.setMaximumTimeToLock(admin1, 0);
1905 reset(mMockContext.powerManagerInternal);
1906 reset(mMockContext.settings);
1907
1908 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
1909 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1910 reset(mMockContext.powerManagerInternal);
1911 reset(mMockContext.settings);
1912
1913 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
1914 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1915 reset(mMockContext.powerManagerInternal);
1916 reset(mMockContext.settings);
1917
1918 dpm.setMaximumTimeToLock(admin2, 10);
1919 verifyScreenTimeoutCall(10, true);
1920 reset(mMockContext.powerManagerInternal);
1921 reset(mMockContext.settings);
1922
1923 // There's no restriction; shold be set to MAX.
1924 dpm.setMaximumTimeToLock(admin2, 0);
1925 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
1926 }
1927
Michal Karpinski943aabd2016-10-06 11:09:25 +01001928 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
1929 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1930 setupDeviceOwner();
1931 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1932
1933 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
1934 final long ONE_MINUTE = 60 * 1000;
1935
1936 // aggregation should be the default if unset by any admin
1937 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1938 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1939
1940 // admin not participating by default
1941 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1942
1943 //clamping from the top
1944 dpm.setRequiredStrongAuthTimeout(admin1,
1945 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1946 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
1947 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1948 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1949 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1950
1951 // 0 means default
1952 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1953 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1954 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1955 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1956
1957 // clamping from the bottom
1958 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
1959 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1960 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1961
1962 // value within range
1963 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1964 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1965 + ONE_MINUTE);
1966 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1967 + ONE_MINUTE);
1968
1969 // reset to default
1970 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1971 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1972 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1973 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1974
1975 // negative value
1976 try {
1977 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
1978 fail("Didn't throw IllegalArgumentException");
1979 } catch (IllegalArgumentException iae) {
1980 }
1981 }
1982
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001983 private void verifyScreenTimeoutCall(Integer expectedTimeout,
1984 boolean shouldStayOnWhilePluggedInBeCleared) {
1985 if (expectedTimeout == null) {
1986 verify(mMockContext.powerManagerInternal, times(0))
1987 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
1988 } else {
1989 verify(mMockContext.powerManagerInternal, times(1))
1990 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
1991 }
1992 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
1993 // UnfinishedVerificationException.
1994 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001995
Victor Chang3e794af2016-03-04 13:48:17 +00001996 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
1997 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
1998 .thenReturn(false);
1999 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2000 .thenReturn(false);
2001 initializeDpms();
2002 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2003 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2004 .thenReturn(true);
2005 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2006
2007 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2008
2009 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2010 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2011 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2012 false);
2013 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2014 }
2015
2016 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2017 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2018 .thenReturn(false);
2019 initializeDpms();
2020 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2021 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2022 .thenReturn(true);
2023 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2024
2025 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2026
2027 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2028 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2029 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2030 false);
2031 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2032
2033 // Test again when split user is on
2034 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2035 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2036 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2037 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2038 true);
2039 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2040 }
2041
2042 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2043 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2044 .thenReturn(true);
2045 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2046 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2047 .thenReturn(true);
2048 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2049
2050 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2051
2052 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2053 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2054 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2055 false /* because of non-split user */);
2056 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2057 false /* because of non-split user */);
2058 }
2059
2060 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2061 throws Exception {
2062 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2063 .thenReturn(true);
2064 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2065 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2066 .thenReturn(true);
2067 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2068
2069 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2070
2071 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2072 false/* because of completed device setup */);
2073 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2074 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2075 false/* because of non-split user */);
2076 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2077 false/* because of non-split user */);
2078 }
2079
2080 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2081 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2082 .thenReturn(true);
2083 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2084 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2085 .thenReturn(false);
2086 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2087
2088 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2089
2090 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2091 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2092 false /* because canAddMoreManagedProfiles returns false */);
2093 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2094 true);
2095 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2096 false/* because calling uid is system user */);
2097
2098 }
2099
2100 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2101 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2102 .thenReturn(true);
2103 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2104 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2105 .thenReturn(false);
2106 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2107
2108 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2109
2110 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2111 true/* it's undefined behavior. Can be changed into false in the future */);
2112 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2113 false /* because canAddMoreManagedProfiles returns false */);
2114 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2115 true/* it's undefined behavior. Can be changed into false in the future */);
2116 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2117 false/* because calling uid is system user */);
2118 }
2119
2120 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2121 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2122 .thenReturn(true);
2123 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2124 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2125 true)).thenReturn(true);
2126 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2127
2128 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2129
2130 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2131 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2132 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2133 true);
2134 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
2135
2136 }
2137
2138 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2139 throws Exception {
2140 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2141 .thenReturn(true);
2142 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2143 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2144 true)).thenReturn(true);
2145 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2146
2147 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2148
2149 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2150 true/* it's undefined behavior. Can be changed into false in the future */);
2151 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2152 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2153 true/* it's undefined behavior. Can be changed into false in the future */);
2154 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2155 false/* because user setup completed */);
2156 }
2157
2158 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2159 throws Exception {
2160 setDeviceOwner();
2161
2162 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2163 .thenReturn(true);
2164 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2165 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2166 .thenReturn(false);
2167 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2168
2169 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2170
2171 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2172 false /* can't provision managed profile on system user */);
2173 }
2174
2175 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2176 throws Exception {
2177 setDeviceOwner();
2178
2179 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2180 .thenReturn(true);
2181 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2182 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2183 true)).thenReturn(true);
2184 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2185
2186 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2187
2188 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2189 }
2190
Nicolas Prevot56400a42016-11-10 12:57:54 +00002191 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2192 throws Exception {
2193 setDeviceOwner();
2194
2195 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2196 .thenReturn(true);
2197 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2198 when(mContext.userManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_USER))
2199 .thenReturn(true);
2200 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2201 false /* we can't remove a managed profile*/)).thenReturn(false);
2202 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2203 true)).thenReturn(true);
2204 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2205
2206 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2207
2208 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2209 }
2210
Victor Chang3577ed22016-08-25 18:49:26 +01002211 public void testForceUpdateUserSetupComplete_permission() {
2212 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2213 try {
2214 dpm.forceUpdateUserSetupComplete();
2215 fail("Didn't throw SecurityException");
2216 } catch (SecurityException expected) {
2217 }
2218 }
2219
2220 public void testForceUpdateUserSetupComplete_systemUser() {
2221 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2222 // GIVEN calling from user 20
2223 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2224 try {
2225 dpm.forceUpdateUserSetupComplete();
2226 fail("Didn't throw SecurityException");
2227 } catch (SecurityException expected) {
2228 }
2229 }
2230
2231 public void testForceUpdateUserSetupComplete_userbuild() {
2232 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2233 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2234
2235 final int userId = UserHandle.USER_SYSTEM;
2236 // GIVEN userComplete is false in SettingsProvider
2237 setUserSetupCompleteForUser(false, userId);
2238
2239 // GIVEN userComplete is true in DPM
2240 DevicePolicyManagerService.DevicePolicyData userData =
2241 new DevicePolicyManagerService.DevicePolicyData(userId);
2242 userData.mUserSetupComplete = true;
2243 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2244
2245 // GIVEN it's user build
2246 mContext.buildMock.isDebuggable = false;
2247
2248 assertTrue(dpms.hasUserSetupCompleted());
2249
2250 dpm.forceUpdateUserSetupComplete();
2251
2252 // THEN the state in dpms is not changed
2253 assertTrue(dpms.hasUserSetupCompleted());
2254 }
2255
2256 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2257 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2258 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2259
2260 final int userId = UserHandle.USER_SYSTEM;
2261 // GIVEN userComplete is false in SettingsProvider
2262 setUserSetupCompleteForUser(false, userId);
2263
2264 // GIVEN userComplete is true in DPM
2265 DevicePolicyManagerService.DevicePolicyData userData =
2266 new DevicePolicyManagerService.DevicePolicyData(userId);
2267 userData.mUserSetupComplete = true;
2268 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2269
2270 // GIVEN it's userdebug build
2271 mContext.buildMock.isDebuggable = true;
2272
2273 assertTrue(dpms.hasUserSetupCompleted());
2274
2275 dpm.forceUpdateUserSetupComplete();
2276
2277 // THEN the state in dpms is not changed
2278 assertFalse(dpms.hasUserSetupCompleted());
2279 }
2280
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002281 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002282 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002283 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2284 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2285 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2286 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002287 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002288 }
2289
2290 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2291 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2292 setupDeviceOwner();
2293 when(mContext.userManager.getUserCount()).thenReturn(1);
2294 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2295 .thenReturn(true);
2296
2297 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002298 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002299
2300 // Enabling logging should not change the timestamp.
2301 dpm.setSecurityLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002302 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002303
2304 // Retrieving the logs should update the timestamp.
2305 final long beforeRetrieval = System.currentTimeMillis();
2306 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002307 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002308 final long afterRetrieval = System.currentTimeMillis();
2309 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2310 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2311
2312 // Retrieving the pre-boot logs should update the timestamp.
2313 Thread.sleep(2);
2314 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002315 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002316 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2317
2318 // Checking the timestamp again should not change it.
2319 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002320 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002321
2322 // Retrieving the logs again should update the timestamp.
2323 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002324 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002325 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2326
2327 // Disabling logging should not change the timestamp.
2328 Thread.sleep(2);
2329 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002330 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002331
2332 // Restarting the DPMS should not lose the timestamp.
2333 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002334 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002335
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002336 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2337 mContext.binder.callingUid = 1234567;
2338 mContext.callerPermissions.add(permission.MANAGE_USERS);
2339 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2340 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2341
2342 // System can retrieve the timestamp.
2343 mContext.binder.clearCallingIdentity();
2344 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2345
2346 // Removing the device owner should clear the timestamp.
2347 clearDeviceOwner();
2348 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002349 }
2350
2351 public void testGetLastBugReportRequestTime() throws Exception {
2352 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2353 setupDeviceOwner();
2354 when(mContext.userManager.getUserCount()).thenReturn(1);
2355 mContext.packageName = admin1.getPackageName();
2356 mContext.applicationInfo = new ApplicationInfo();
2357 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2358 .thenReturn(Color.WHITE);
2359 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2360 anyObject())).thenReturn(Color.WHITE);
2361
2362 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002363 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002364
2365 // Requesting a bug report should update the timestamp.
2366 final long beforeRequest = System.currentTimeMillis();
2367 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002368 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002369 final long afterRequest = System.currentTimeMillis();
2370 assertTrue(bugReportRequestTime >= beforeRequest);
2371 assertTrue(bugReportRequestTime <= afterRequest);
2372
2373 // Checking the timestamp again should not change it.
2374 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002375 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002376
2377 // Restarting the DPMS should not lose the timestamp.
2378 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002379 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002380
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002381 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2382 mContext.binder.callingUid = 1234567;
2383 mContext.callerPermissions.add(permission.MANAGE_USERS);
2384 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2385 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2386
2387 // System can retrieve the timestamp.
2388 mContext.binder.clearCallingIdentity();
2389 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2390
2391 // Removing the device owner should clear the timestamp.
2392 clearDeviceOwner();
2393 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002394 }
2395
2396 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2397 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2398 setupDeviceOwner();
2399 when(mContext.userManager.getUserCount()).thenReturn(1);
2400 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2401 .thenReturn(true);
2402
2403 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002404 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002405
2406 // Attempting to retrieve logs without enabling logging should not change the timestamp.
2407 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002408 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002409
2410 // Enabling logging should not change the timestamp.
2411 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002412 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002413
2414 // Retrieving the logs should update the timestamp.
2415 final long beforeRetrieval = System.currentTimeMillis();
2416 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002417 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002418 final long afterRetrieval = System.currentTimeMillis();
2419 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
2420 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
2421
2422 // Checking the timestamp again should not change it.
2423 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002424 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002425
2426 // Retrieving the logs again should update the timestamp.
2427 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002428 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002429 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
2430
2431 // Disabling logging should not change the timestamp.
2432 Thread.sleep(2);
2433 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002434 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002435
2436 // Restarting the DPMS should not lose the timestamp.
2437 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002438 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2439
2440 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2441 mContext.binder.callingUid = 1234567;
2442 mContext.callerPermissions.add(permission.MANAGE_USERS);
2443 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2444 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2445
2446 // System can retrieve the timestamp.
2447 mContext.binder.clearCallingIdentity();
2448 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2449
2450 // Removing the device owner should clear the timestamp.
2451 clearDeviceOwner();
2452 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002453 }
2454
Tony Mak2f26b792016-11-28 17:54:51 +00002455 public void testGetBindDeviceAdminTargetUsers() throws Exception {
2456 // Setup device owner.
2457 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2458 setupDeviceOwner();
2459
2460 // Only device owner is setup, the result list should be empty.
2461 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2462 MoreAsserts.assertEmpty(targetUsers);
2463
2464 // Setup a managed profile managed by the same admin.
2465 final int MANAGED_PROFILE_USER_ID = 15;
2466 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2467 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2468
2469 // Add a secondary user, it should never talk with.
2470 final int ANOTHER_USER_ID = 36;
2471 mContext.addUser(ANOTHER_USER_ID, 0);
2472
2473 // Calling from device owner admin, the result list should just contain the managed
2474 // profile user id.
2475 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2476 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
2477
2478 // Calling from managed profile admin, the result list should just contain the system
2479 // user id.
2480 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2481 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2482 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
2483 }
2484
2485 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
2486 // Setup a device owner.
2487 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2488 setupDeviceOwner();
2489
2490 // Set up a managed profile managed by different package.
2491 final int MANAGED_PROFILE_USER_ID = 15;
2492 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2493 final ComponentName adminDifferentPackage =
2494 new ComponentName("another.package", "whatever.class");
2495 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
2496
2497 // Calling from device owner admin, we should get zero bind device admin target users as
2498 // their packages are different.
2499 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2500 MoreAsserts.assertEmpty(targetUsers);
2501
2502 // Calling from managed profile admin, we should still get zero target users for the same
2503 // reason.
2504 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2505 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
2506 MoreAsserts.assertEmpty(targetUsers);
2507 }
2508
Victor Chang3e794af2016-03-04 13:48:17 +00002509 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
2510 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
2511 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
2512 dpms.notifyChangeToContentObserver(
2513 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
2514 }
2515
2516 private void assertProvisioningAllowed(String action, boolean expected) {
2517 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
2518 dpm.isProvisioningAllowed(action));
2519 }
Tony Mak2f26b792016-11-28 17:54:51 +00002520
2521 /**
2522 * Setup a managed profile with the specified admin and its uid.
2523 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
2524 * @param adminUid uid of the admin package.
2525 * @param copyFromAdmin package information for {@code admin} will be built based on this
2526 * component's information.
2527 */
2528 private void addManagedProfile(
2529 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
2530 final int userId = UserHandle.getUserId(adminUid);
2531 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
2532 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2533 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
2534 dpm.setActiveAdmin(admin, false, userId);
2535 assertTrue(dpm.setProfileOwner(admin, null, userId));
2536 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2537 }
Victor Chang3e794af2016-03-04 13:48:17 +00002538}