blob: f797f3114565b49f2bea58c0d28a556c0d1bba30 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov6a40f092016-10-25 15:46:51 +010018import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
19import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
20import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
21
Makoto Onukif76b06a2015-09-22 15:03:44 -070022import android.Manifest.permission;
23import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000024import android.app.Notification;
25import android.app.NotificationManager;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070026import android.app.admin.DeviceAdminReceiver;
27import android.app.admin.DevicePolicyManager;
28import android.app.admin.DevicePolicyManagerInternal;
Makoto Onukif76b06a2015-09-22 15:03:44 -070029import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070030import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000031import android.content.Context;
32import android.content.Intent;
33import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000034import android.content.pm.ApplicationInfo;
35import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070036import android.content.pm.PackageManager;
Robin Leeabaa0692017-02-20 20:54:22 +000037import android.content.pm.StringParceledListSlice;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010038import android.content.res.Resources;
39import android.graphics.Color;
40import android.net.IIpConnectivityMetrics;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +010041import android.net.Uri;
Tony Mak2f26b792016-11-28 17:54:51 +000042import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080043import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080044import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070045import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000046import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080047import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070048import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070049import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010050import android.os.UserManagerInternal;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080051import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010052import android.security.IKeyChainService;
53import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000054import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080055import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000056import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010057import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070058import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070059
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010060import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000061import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000062import com.android.server.LocalServices;
63import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000064import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000065
Robin Lee7f5c91c2017-02-08 21:27:02 +000066import org.hamcrest.BaseMatcher;
67import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070068import org.mockito.invocation.InvocationOnMock;
69import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070070
Makoto Onukic8a5a552015-11-19 14:29:12 -080071import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000072import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000073import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070074import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070075import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070076import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010077import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000078import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070079
Edman Anjosf9946772016-11-28 16:35:15 +010080import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
81import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
82
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070083import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070084import static org.mockito.Matchers.anyInt;
Michal Karpinskid084ca52017-01-18 15:54:18 +000085import static org.mockito.Matchers.anyLong;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010086import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070087import static org.mockito.Matchers.anyString;
Robin Lee7f5c91c2017-02-08 21:27:02 +000088import static org.mockito.Matchers.argThat;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070089import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070090import static org.mockito.Matchers.isNull;
Esteban Talavera548a04b2016-12-20 15:22:30 +000091import static org.mockito.Mockito.atLeast;
Makoto Onukib643fb02015-09-22 15:03:44 -070092import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070093import static org.mockito.Mockito.doReturn;
Robin Lee7f5c91c2017-02-08 21:27:02 +000094import static org.mockito.Mockito.mock;
Robin Leed2a73ed2016-12-19 09:07:16 +000095import static org.mockito.Mockito.never;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080096import static org.mockito.Mockito.reset;
Robin Lee7f5c91c2017-02-08 21:27:02 +000097import static org.mockito.Mockito.timeout;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098import static org.mockito.Mockito.times;
99import static org.mockito.Mockito.verify;
Esteban Talaverab88f42b2017-01-24 16:47:16 +0000100import static org.mockito.Mockito.verifyZeroInteractions;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700101import static org.mockito.Mockito.when;
102
103/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700104 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000105 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106 m FrameworksServicesTests &&
107 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000108 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700109 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800110 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111
112 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000113 *
114 * , or:
115 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000117@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000119 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
120 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
121 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
122
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700123 private DpmMockContext mContext;
124 public DevicePolicyManager dpm;
125 public DevicePolicyManagerServiceTestable dpms;
126
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100127 /*
128 * The CA cert below is the content of cacert.pem as generated by:
129 *
130 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
131 */
132 private static final String TEST_CA =
133 "-----BEGIN CERTIFICATE-----\n" +
134 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
135 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
136 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
137 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
138 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
139 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
140 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
141 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
142 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
143 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
144 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
145 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
146 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
147 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
148 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
149 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
150 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
151 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
152 "wQ==\n" +
153 "-----END CERTIFICATE-----\n";
154
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700155 @Override
156 protected void setUp() throws Exception {
157 super.setUp();
158
159 mContext = getContext();
160
161 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
162 .thenReturn(true);
163
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800164 // By default, pretend all users are running and unlocked.
165 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
166
Makoto Onukia52562c2015-10-01 16:12:31 -0700167 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700168
Makoto Onukid932f762015-09-29 16:53:38 -0700169 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
170 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
171 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800172 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700173
Makoto Onukib643fb02015-09-22 15:03:44 -0700174 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700175 }
176
Makoto Onukia52562c2015-10-01 16:12:31 -0700177 private void initializeDpms() {
178 // Need clearCallingIdentity() to pass permission checks.
179 final long ident = mContext.binder.clearCallingIdentity();
180 try {
181 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
182
183 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
184
185 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
186 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
187
188 dpm = new DevicePolicyManagerTestable(mContext, dpms);
189 } finally {
190 mContext.binder.restoreCallingIdentity(ident);
191 }
192 }
193
Makoto Onukib643fb02015-09-22 15:03:44 -0700194 private void setUpUserManager() {
195 // Emulate UserManager.set/getApplicationRestriction().
196 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
197
198 // UM.setApplicationRestrictions() will save to appRestrictions.
199 doAnswer(new Answer<Void>() {
200 @Override
201 public Void answer(InvocationOnMock invocation) throws Throwable {
202 String pkg = (String) invocation.getArguments()[0];
203 Bundle bundle = (Bundle) invocation.getArguments()[1];
204 UserHandle user = (UserHandle) invocation.getArguments()[2];
205
206 appRestrictions.put(Pair.create(pkg, user), bundle);
207
208 return null;
209 }
210 }).when(mContext.userManager).setApplicationRestrictions(
211 anyString(), any(Bundle.class), any(UserHandle.class));
212
213 // UM.getApplicationRestrictions() will read from appRestrictions.
214 doAnswer(new Answer<Bundle>() {
215 @Override
216 public Bundle answer(InvocationOnMock invocation) throws Throwable {
217 String pkg = (String) invocation.getArguments()[0];
218 UserHandle user = (UserHandle) invocation.getArguments()[1];
219
220 return appRestrictions.get(Pair.create(pkg, user));
221 }
222 }).when(mContext.userManager).getApplicationRestrictions(
223 anyString(), any(UserHandle.class));
224
Makoto Onukid932f762015-09-29 16:53:38 -0700225 // Add the first secondary user.
226 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700227 }
228
229 private void setAsProfileOwner(ComponentName admin) {
230 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
231 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
232
Makoto Onukia4f11972015-10-01 13:19:58 -0700233 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700234 dpm.setActiveAdmin(admin, /* replace =*/ false);
235
236 // Fire!
237 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
238
239 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700240 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700241 }
242
243 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700244 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
245 .thenReturn(false);
246
247 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
248 new DevicePolicyManagerServiceTestable(mContext, dataDir);
249
250 // If the device has no DPMS feature, it shouldn't register the local service.
251 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
252 }
253
254 /**
255 * Caller doesn't have proper permissions.
256 */
257 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700258 // 1. Failure cases.
259
260 // Caller doesn't have MANAGE_DEVICE_ADMINS.
261 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700262 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700263 fail("Didn't throw SecurityException");
264 } catch (SecurityException expected) {
265 }
266
267 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
268 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
269 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700270 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700271 fail("Didn't throw SecurityException");
272 } catch (SecurityException expected) {
273 }
274 }
275
Makoto Onukif76b06a2015-09-22 15:03:44 -0700276 /**
277 * Test for:
278 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800279 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700280 * {@link DevicePolicyManager#isAdminActive}
281 * {@link DevicePolicyManager#isAdminActiveAsUser}
282 * {@link DevicePolicyManager#getActiveAdmins}
283 * {@link DevicePolicyManager#getActiveAdminsAsUser}
284 */
285 public void testSetActiveAdmin() throws Exception {
286 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700287 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
288
Makoto Onukif76b06a2015-09-22 15:03:44 -0700289 // 2. Call the API.
290 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700291
292 // 3. Verify internal calls.
293
294 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700295 verify(mContext.spiedContext).sendBroadcastAsUser(
296 MockUtils.checkIntentAction(
297 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
298 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
299 verify(mContext.spiedContext).sendBroadcastAsUser(
300 MockUtils.checkIntentAction(
301 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700302 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
303
Makoto Onukif76b06a2015-09-22 15:03:44 -0700304 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
305 eq(admin1.getPackageName()),
306 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
307 eq(PackageManager.DONT_KILL_APP),
308 eq(DpmMockContext.CALLER_USER_HANDLE),
309 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700310
311 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700312
313 // Make sure it's active admin1.
314 assertTrue(dpm.isAdminActive(admin1));
315 assertFalse(dpm.isAdminActive(admin2));
316 assertFalse(dpm.isAdminActive(admin3));
317
318 // But not admin1 for a different user.
319
320 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
321 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
322 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
323
324 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
325 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
326
327 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
328
329 // Next, add one more admin.
330 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700331 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
332 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700333
334 dpm.setActiveAdmin(admin2, /* replace =*/ false);
335
336 // Now we have two admins.
337 assertTrue(dpm.isAdminActive(admin1));
338 assertTrue(dpm.isAdminActive(admin2));
339 assertFalse(dpm.isAdminActive(admin3));
340
341 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
342 // again. (times(1) because it was previously called for admin1)
343 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
344 eq(admin1.getPackageName()),
345 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
346 eq(PackageManager.DONT_KILL_APP),
347 eq(DpmMockContext.CALLER_USER_HANDLE),
348 anyString());
349
350 // 4. Add the same admin1 again without replace, which should throw.
351 try {
352 dpm.setActiveAdmin(admin1, /* replace =*/ false);
353 fail("Didn't throw");
354 } catch (IllegalArgumentException expected) {
355 }
356
357 // 5. Add the same admin1 again with replace, which should succeed.
358 dpm.setActiveAdmin(admin1, /* replace =*/ true);
359
360 // TODO make sure it's replaced.
361
362 // 6. Test getActiveAdmins()
363 List<ComponentName> admins = dpm.getActiveAdmins();
364 assertEquals(2, admins.size());
365 assertEquals(admin1, admins.get(0));
366 assertEquals(admin2, admins.get(1));
367
368 // Another user has no admins.
369 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
370
371 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
372 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
373
374 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
375 }
376
Makoto Onukid932f762015-09-29 16:53:38 -0700377 public void testSetActiveAdmin_multiUsers() throws Exception {
378
379 final int ANOTHER_USER_ID = 100;
380 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
381
382 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
383
384 // Set up pacakge manager for the other user.
385 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700386
387 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
388
389 dpm.setActiveAdmin(admin1, /* replace =*/ false);
390
391 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
392 dpm.setActiveAdmin(admin2, /* replace =*/ false);
393
394
395 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
396 assertTrue(dpm.isAdminActive(admin1));
397 assertFalse(dpm.isAdminActive(admin2));
398
399 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
400 assertFalse(dpm.isAdminActive(admin1));
401 assertTrue(dpm.isAdminActive(admin2));
402 }
403
Makoto Onukif76b06a2015-09-22 15:03:44 -0700404 /**
405 * Test for:
406 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800407 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700408 */
409 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
410 // 1. Make sure the caller has proper permissions.
411 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
412
413 dpm.setActiveAdmin(admin1, /* replace =*/ false);
414 assertTrue(dpm.isAdminActive(admin1));
415
416 // Add the same admin1 again without replace, which should throw.
417 try {
418 dpm.setActiveAdmin(admin1, /* replace =*/ false);
419 fail("Didn't throw");
420 } catch (IllegalArgumentException expected) {
421 }
422 }
423
424 /**
425 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800426 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
427 * BIND_DEVICE_ADMIN.
428 */
429 public void testSetActiveAdmin_permissionCheck() throws Exception {
430 // 1. Make sure the caller has proper permissions.
431 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
432
433 try {
434 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
435 fail();
436 } catch (IllegalArgumentException expected) {
437 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
438 }
439 assertFalse(dpm.isAdminActive(adminNoPerm));
440
441 // Change the target API level to MNC. Now it can be set as DA.
442 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
443 VERSION_CODES.M);
444 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
445 assertTrue(dpm.isAdminActive(adminNoPerm));
446
447 // TODO Test the "load from the file" case where DA will still be loaded even without
448 // BIND_DEVICE_ADMIN and target API is N.
449 }
450
451 /**
452 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700453 * {@link DevicePolicyManager#removeActiveAdmin}
454 */
455 public void testRemoveActiveAdmin_SecurityException() {
456 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
457
458 // Add admin.
459
460 dpm.setActiveAdmin(admin1, /* replace =*/ false);
461
462 assertTrue(dpm.isAdminActive(admin1));
463
464 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
465
466 // Directly call the DPMS method with a different userid, which should fail.
467 try {
468 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
469 fail("Didn't throw SecurityException");
470 } catch (SecurityException expected) {
471 }
472
473 // Try to remove active admin with a different caller userid should fail too, without
474 // having MANAGE_DEVICE_ADMINS.
475 mContext.callerPermissions.clear();
476
Makoto Onukid932f762015-09-29 16:53:38 -0700477 // Change the caller, and call into DPMS directly with a different user-id.
478
Makoto Onukif76b06a2015-09-22 15:03:44 -0700479 mContext.binder.callingUid = 1234567;
480 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700481 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700482 fail("Didn't throw SecurityException");
483 } catch (SecurityException expected) {
484 }
485 }
486
487 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800488 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
489 * (because we can't send the remove broadcast).
490 */
491 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
492 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
493
494 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
495
496 // Add admin.
497
498 dpm.setActiveAdmin(admin1, /* replace =*/ false);
499
500 assertTrue(dpm.isAdminActive(admin1));
501
502 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
503
504 // 1. User not unlocked.
505 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
506 .thenReturn(false);
507 try {
508 dpm.removeActiveAdmin(admin1);
509 fail("Didn't throw IllegalStateException");
510 } catch (IllegalStateException expected) {
511 MoreAsserts.assertContainsRegex(
512 "User must be running and unlocked", expected.getMessage());
513 }
514
515 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
516
517 // 2. User unlocked.
518 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
519 .thenReturn(true);
520
521 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700522 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800523 }
524
525 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700526 * Test for:
527 * {@link DevicePolicyManager#removeActiveAdmin}
528 */
Makoto Onukid932f762015-09-29 16:53:38 -0700529 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700530 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
531
532 // Add admin1.
533
534 dpm.setActiveAdmin(admin1, /* replace =*/ false);
535
536 assertTrue(dpm.isAdminActive(admin1));
537 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
538
539 // Different user, but should work, because caller has proper permissions.
540 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700541
542 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700543 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700544
545 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700546 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700547
548 // TODO DO Still can't be removed in this case.
549 }
550
551 /**
552 * Test for:
553 * {@link DevicePolicyManager#removeActiveAdmin}
554 */
555 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
556 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
557 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
558
559 // Add admin1.
560
561 dpm.setActiveAdmin(admin1, /* replace =*/ false);
562
563 assertTrue(dpm.isAdminActive(admin1));
564 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
565
566 // Broadcast from saveSettingsLocked().
567 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
568 MockUtils.checkIntentAction(
569 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
570 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
571
572 // Remove. No permissions, but same user, so it'll work.
573 mContext.callerPermissions.clear();
574 dpm.removeActiveAdmin(admin1);
575
Makoto Onukif76b06a2015-09-22 15:03:44 -0700576 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
577 MockUtils.checkIntentAction(
578 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
579 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
580 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700581 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700582 eq(dpms.mHandler),
583 eq(Activity.RESULT_OK),
584 isNull(String.class),
585 isNull(Bundle.class));
586
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700587 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700588
589 // Again broadcast from saveSettingsLocked().
590 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
591 MockUtils.checkIntentAction(
592 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
593 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
594
595 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700596 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700597
598 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000599 * Test for: @{link DevicePolicyManager#setActivePasswordState}
600 *
601 * Validates that when the password for a user changes, the notification broadcast intent
602 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
603 * addition to ones in the original user.
604 */
605 public void testSetActivePasswordState_sendToProfiles() throws Exception {
606 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
607
608 final int MANAGED_PROFILE_USER_ID = 78;
609 final int MANAGED_PROFILE_ADMIN_UID =
610 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
611
612 // Setup device owner.
613 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
614 mContext.packageName = admin1.getPackageName();
615 setupDeviceOwner();
616
617 // Add a managed profile belonging to the system user.
618 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
619
620 // Change the parent user's password.
621 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
622
623 // Both the device owner and the managed profile owner should receive this broadcast.
624 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
625 intent.setComponent(admin1);
626 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
627
628 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
629 MockUtils.checkIntent(intent),
630 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
631 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
632 MockUtils.checkIntent(intent),
633 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
634 }
635
636 /**
637 * Test for: @{link DevicePolicyManager#setActivePasswordState}
638 *
639 * Validates that when the password for a managed profile changes, the notification broadcast
640 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
641 * its parent.
642 */
643 public void testSetActivePasswordState_notSentToParent() throws Exception {
644 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
645
646 final int MANAGED_PROFILE_USER_ID = 78;
647 final int MANAGED_PROFILE_ADMIN_UID =
648 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
649
650 // Setup device owner.
651 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
652 mContext.packageName = admin1.getPackageName();
653 doReturn(true).when(mContext.lockPatternUtils)
654 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
655 setupDeviceOwner();
656
657 // Add a managed profile belonging to the system user.
658 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
659
660 // Change the profile's password.
661 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
662
663 // Both the device owner and the managed profile owner should receive this broadcast.
664 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
665 intent.setComponent(admin1);
666 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
667
668 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
669 MockUtils.checkIntent(intent),
670 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
671 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
672 MockUtils.checkIntent(intent),
673 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
674 }
675 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000676 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700677 */
678 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000679 setDeviceOwner();
680
681 // Try to set a profile owner on the same user, which should fail.
682 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
683 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
684 try {
685 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
686 fail("IllegalStateException not thrown");
687 } catch (IllegalStateException expected) {
688 assertTrue("Message was: " + expected.getMessage(),
689 expected.getMessage().contains("already has a device owner"));
690 }
691
692 // DO admin can't be deactivated.
693 dpm.removeActiveAdmin(admin1);
694 assertTrue(dpm.isAdminActive(admin1));
695
696 // TODO Test getDeviceOwnerName() too. To do so, we need to change
697 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
698 }
699
700 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700701 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800702 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700703 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
704 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
705
Makoto Onukid932f762015-09-29 16:53:38 -0700706 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700707 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
708
Makoto Onukid932f762015-09-29 16:53:38 -0700709 // Make sure admin1 is installed on system user.
710 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700711
Makoto Onukic8a5a552015-11-19 14:29:12 -0800712 // Check various get APIs.
713 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
714
Makoto Onukib643fb02015-09-22 15:03:44 -0700715 // DO needs to be an DA.
716 dpm.setActiveAdmin(admin1, /* replace =*/ false);
717
718 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700719 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700720
Makoto Onukic8a5a552015-11-19 14:29:12 -0800721 // getDeviceOwnerComponent should return the admin1 component.
722 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
723 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
724
725 // Check various get APIs.
726 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
727
728 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
729 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
730 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
731 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
732
733 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
734
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000735 // Verify internal calls.
736 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
737 eq(admin1.getPackageName()));
738
Makoto Onukib643fb02015-09-22 15:03:44 -0700739 // TODO We should check if the caller has called clearCallerIdentity().
740 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
741 eq(UserHandle.USER_SYSTEM), eq(false));
742
743 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
744 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
745 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
746
Makoto Onukic8a5a552015-11-19 14:29:12 -0800747 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700748 }
749
Makoto Onukic8a5a552015-11-19 14:29:12 -0800750 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
751 final int origCallingUser = mContext.binder.callingUid;
752 final List origPermissions = new ArrayList(mContext.callerPermissions);
753 mContext.callerPermissions.clear();
754
755 mContext.callerPermissions.add(permission.MANAGE_USERS);
756
757 mContext.binder.callingUid = Process.SYSTEM_UID;
758
759 // TODO Test getDeviceOwnerName() too. To do so, we need to change
760 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
761 if (hasDeviceOwner) {
762 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
763 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
764 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
765
766 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
767 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
768 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
769 } else {
770 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
771 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
772 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
773
774 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
775 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
776 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
777 }
778
779 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
780 if (hasDeviceOwner) {
781 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
782 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
783 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
784
785 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
786 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
787 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
788 } else {
789 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
790 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
791 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
792
793 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
794 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
795 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
796 }
797
798 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
799 // Still with MANAGE_USERS.
800 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
801 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
802 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
803
804 if (hasDeviceOwner) {
805 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
806 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
807 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
808 } else {
809 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
810 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
811 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
812 }
813
814 mContext.binder.callingUid = Process.SYSTEM_UID;
815 mContext.callerPermissions.remove(permission.MANAGE_USERS);
816 // System can still call "OnAnyUser" without MANAGE_USERS.
817 if (hasDeviceOwner) {
818 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
819 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
820 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
821
822 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
823 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
824 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
825 } else {
826 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
827 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
828 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
829
830 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
831 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
832 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
833 }
834
835 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
836 // Still no MANAGE_USERS.
837 if (hasDeviceOwner) {
838 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
839 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
840 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
841 } else {
842 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
843 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
844 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
845 }
846
847 try {
848 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
849 fail();
850 } catch (SecurityException expected) {
851 }
852 try {
853 dpm.getDeviceOwnerComponentOnAnyUser();
854 fail();
855 } catch (SecurityException expected) {
856 }
857 try {
858 dpm.getDeviceOwnerUserId();
859 fail();
860 } catch (SecurityException expected) {
861 }
862 try {
863 dpm.getDeviceOwnerNameOnAnyUser();
864 fail();
865 } catch (SecurityException expected) {
866 }
867
868 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
869 // Still no MANAGE_USERS.
870 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
871 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
872 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
873
874 try {
875 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
876 fail();
877 } catch (SecurityException expected) {
878 }
879 try {
880 dpm.getDeviceOwnerComponentOnAnyUser();
881 fail();
882 } catch (SecurityException expected) {
883 }
884 try {
885 dpm.getDeviceOwnerUserId();
886 fail();
887 } catch (SecurityException expected) {
888 }
889 try {
890 dpm.getDeviceOwnerNameOnAnyUser();
891 fail();
892 } catch (SecurityException expected) {
893 }
894
895 // Restore.
896 mContext.binder.callingUid = origCallingUser;
897 mContext.callerPermissions.addAll(origPermissions);
898 }
899
900
Makoto Onukib643fb02015-09-22 15:03:44 -0700901 /**
902 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
903 */
904 public void testSetDeviceOwner_noSuchPackage() {
905 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800906 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700907 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
908 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
909
910 // Call from a process on the system user.
911 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
912
Makoto Onukib643fb02015-09-22 15:03:44 -0700913 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700914 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700915 fail("Didn't throw IllegalArgumentException");
916 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700917 assertTrue("Message was: " + expected.getMessage(),
918 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700919 }
920 }
921
922 public void testSetDeviceOwner_failures() throws Exception {
923 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
924 }
925
Makoto Onukia52562c2015-10-01 16:12:31 -0700926 public void testClearDeviceOwner() throws Exception {
927 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800928 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700929 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
930 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
931
932 // Set admin1 as a DA to the secondary user.
933 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
934
935 dpm.setActiveAdmin(admin1, /* replace =*/ false);
936
937 // Set admin 1 as the DO to the system user.
938
939 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
940 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
941 dpm.setActiveAdmin(admin1, /* replace =*/ false);
942 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
943
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000944 // Verify internal calls.
945 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
946 eq(admin1.getPackageName()));
947
Makoto Onukic8a5a552015-11-19 14:29:12 -0800948 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700949
Makoto Onuki90b89652016-01-28 14:44:18 -0800950 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Victor Chang348f6962017-01-30 16:19:13 +0000951 when(mContext.userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
952 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800953
954 assertTrue(dpm.isAdminActive(admin1));
955 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
956
Makoto Onukia52562c2015-10-01 16:12:31 -0700957 // Set up other mocks.
958 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
959
960 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700961 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700962 eq(admin1.getPackageName()),
963 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800964
965 // But first pretend the user is locked. Then it should fail.
966 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
967 try {
968 dpm.clearDeviceOwnerApp(admin1.getPackageName());
969 fail("Didn't throw IllegalStateException");
970 } catch (IllegalStateException expected) {
971 MoreAsserts.assertContainsRegex(
972 "User must be running and unlocked", expected.getMessage());
973 }
974
975 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800976 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700977 dpm.clearDeviceOwnerApp(admin1.getPackageName());
978
979 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800980 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700981
Victor Chang348f6962017-01-30 16:19:13 +0000982 verify(mContext.userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
983 eq(false),
984 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
985
Makoto Onuki90b89652016-01-28 14:44:18 -0800986 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
987 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100988 eq(null),
989 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800990
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700991 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100992
993 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
994 // and once for clearing it.
995 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
996 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
997 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700998 // TODO Check other calls.
999 }
1000
1001 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1002 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001003 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001004 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1005 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1006
1007 // Set admin1 as a DA to the secondary user.
1008 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1009
1010 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1011
1012 // Set admin 1 as the DO to the system user.
1013
1014 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1015 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1016 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1017 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1018
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001019 // Verify internal calls.
1020 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
1021 eq(admin1.getPackageName()));
1022
Makoto Onukic8a5a552015-11-19 14:29:12 -08001023 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001024
1025 // Now call clear from the secondary user, which should throw.
1026 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1027
1028 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001029 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001030 eq(admin1.getPackageName()),
1031 anyInt());
1032 try {
1033 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1034 fail("Didn't throw");
1035 } catch (SecurityException e) {
1036 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
1037 }
1038
Makoto Onukic8a5a552015-11-19 14:29:12 -08001039 // DO shouldn't be removed.
1040 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001041 }
1042
Makoto Onukib643fb02015-09-22 15:03:44 -07001043 public void testSetProfileOwner() throws Exception {
1044 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001045
Makoto Onuki90b89652016-01-28 14:44:18 -08001046 // PO admin can't be deactivated.
1047 dpm.removeActiveAdmin(admin1);
1048 assertTrue(dpm.isAdminActive(admin1));
1049
Makoto Onuki803d6752015-10-30 12:58:39 -07001050 // Try setting DO on the same user, which should fail.
1051 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1052 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1053 try {
1054 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1055 fail("IllegalStateException not thrown");
1056 } catch (IllegalStateException expected) {
1057 assertTrue("Message was: " + expected.getMessage(),
1058 expected.getMessage().contains("already has a profile owner"));
1059 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001060 }
1061
Makoto Onuki90b89652016-01-28 14:44:18 -08001062 public void testClearProfileOwner() throws Exception {
1063 setAsProfileOwner(admin1);
1064
1065 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1066
1067 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1068 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1069
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001070 // First try when the user is locked, which should fail.
1071 when(mContext.userManager.isUserUnlocked(anyInt()))
1072 .thenReturn(false);
1073 try {
1074 dpm.clearProfileOwner(admin1);
1075 fail("Didn't throw IllegalStateException");
1076 } catch (IllegalStateException expected) {
1077 MoreAsserts.assertContainsRegex(
1078 "User must be running and unlocked", expected.getMessage());
1079 }
1080 // Clear, really.
1081 when(mContext.userManager.isUserUnlocked(anyInt()))
1082 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001083 dpm.clearProfileOwner(admin1);
1084
1085 // Check
1086 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001087 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001088 }
1089
Makoto Onukib643fb02015-09-22 15:03:44 -07001090 public void testSetProfileOwner_failures() throws Exception {
1091 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1092 }
1093
Makoto Onukia52562c2015-10-01 16:12:31 -07001094 public void testGetDeviceOwnerAdminLocked() throws Exception {
1095 checkDeviceOwnerWithMultipleDeviceAdmins();
1096 }
1097
1098 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1099 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1100 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1101 // make sure it gets the right component from the right user.
1102
1103 final int ANOTHER_USER_ID = 100;
1104 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1105
1106 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1107
1108 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001109 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001110 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1111 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1112
1113 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1114
Victor Change29cd472016-03-02 20:57:42 +00001115 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1116
Makoto Onukia52562c2015-10-01 16:12:31 -07001117 // Make sure the admin packge is installed to each user.
1118 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1119 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1120
1121 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1122 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1123
1124 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1125
1126
1127 // Set active admins to the users.
1128 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1129 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1130
1131 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1132 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1133
1134 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1135
1136 // Set DO on the first non-system user.
1137 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1138 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1139
Makoto Onukic8a5a552015-11-19 14:29:12 -08001140 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001141
1142 // Then check getDeviceOwnerAdminLocked().
1143 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1144 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1145 }
1146
1147 /**
1148 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001149 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1150 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001151 *
1152 * We didn't use to persist the DO component class name, but now we do, and the above method
1153 * finds the right component from a package name upon migration.
1154 */
1155 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001156 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001157 checkDeviceOwnerWithMultipleDeviceAdmins();
1158
1159 // Overwrite the device owner setting and clears the clas name.
1160 dpms.mOwners.setDeviceOwner(
1161 new ComponentName(admin2.getPackageName(), ""),
1162 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1163 dpms.mOwners.writeDeviceOwner();
1164
1165 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001166 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001167
1168 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001169 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1170 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001171 initializeDpms();
1172
1173 // Now the DO component name is a full name.
1174 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1175 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001176 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001177 }
1178
Makoto Onukib643fb02015-09-22 15:03:44 -07001179 public void testSetGetApplicationRestriction() {
1180 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001181 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001182
1183 {
1184 Bundle rest = new Bundle();
1185 rest.putString("KEY_STRING", "Foo1");
1186 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1187 }
1188
1189 {
1190 Bundle rest = new Bundle();
1191 rest.putString("KEY_STRING", "Foo2");
1192 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1193 }
1194
1195 {
1196 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1197 assertNotNull(returned);
1198 assertEquals(returned.size(), 1);
1199 assertEquals(returned.get("KEY_STRING"), "Foo1");
1200 }
1201
1202 {
1203 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1204 assertNotNull(returned);
1205 assertEquals(returned.size(), 1);
1206 assertEquals(returned.get("KEY_STRING"), "Foo2");
1207 }
1208
1209 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1210 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1211 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001212
Edman Anjosf9946772016-11-28 16:35:15 +01001213 /**
1214 * Setup a package in the package manager mock. Useful for faking installed applications.
1215 *
1216 * @param packageName the name of the package to be setup
1217 * @param appId the application ID to be given to the package
1218 * @return the UID of the package as known by the mock package manager
1219 */
1220 private int setupPackageInPackageManager(final String packageName, final int appId)
1221 throws Exception {
1222 // Make the PackageManager return the package instead of throwing a NameNotFoundException
1223 final PackageInfo pi = new PackageInfo();
1224 pi.applicationInfo = new ApplicationInfo();
1225 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1226 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1227 eq(packageName),
1228 anyInt(),
1229 eq(DpmMockContext.CALLER_USER_HANDLE));
1230 // Setup application UID with the PackageManager
1231 final int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, appId);
1232 doReturn(uid).when(mContext.packageManager).getPackageUidAsUser(
1233 eq(packageName),
1234 eq(DpmMockContext.CALLER_USER_HANDLE));
1235 // Associate packageName to uid
1236 doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid));
1237 doReturn(new String[]{packageName})
1238 .when(mContext.ipackageManager).getPackagesForUid(eq(uid));
1239 return uid;
1240 }
1241
Robin Lee7f5c91c2017-02-08 21:27:02 +00001242 public void testCertificateDisclosure() throws Exception {
1243 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1244 final UserHandle user = UserHandle.of(userId);
1245
1246 mContext.applicationInfo = new ApplicationInfo();
1247 mContext.callerPermissions.add(permission.MANAGE_USERS);
1248 mContext.packageName = "com.android.frameworks.servicestests";
1249 mContext.userContexts.put(user, mContext);
1250 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1251
Robin Leeabaa0692017-02-20 20:54:22 +00001252 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1253 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001254
1255 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1256 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1257
1258 // Given that we have exactly one certificate installed,
1259 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
1260 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001261 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001262 // a notification should not be shown.
1263 verify(mContext.notificationManager, timeout(1000))
1264 .cancelAsUser(anyString(), anyInt(), eq(user));
1265
1266 // Given that we have four certificates installed,
1267 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
1268 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001269 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1270 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001271 // a notification should be shown saying that there are two certificates left to approve.
1272 verify(mContext.notificationManager, timeout(1000))
1273 .notifyAsUser(anyString(), anyInt(), argThat(
1274 new BaseMatcher<Notification>() {
1275 @Override
1276 public boolean matches(Object item) {
1277 final Notification noti = (Notification) item;
1278 return TEST_STRING.equals(
1279 noti.extras.getString(Notification.EXTRA_TITLE));
1280 }
1281 @Override
1282 public void describeTo(Description description) {
1283 description.appendText(
1284 "Notification{title=\"" + TEST_STRING + "\"}");
1285 }
1286 }), eq(user));
1287 }
1288
Edman Anjosf9946772016-11-28 16:35:15 +01001289 /**
1290 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1291 * privileges can acually be exercised by a delegate are not covered here.
1292 */
1293 public void testDelegation() throws Exception {
1294 setAsProfileOwner(admin1);
1295
1296 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1297
1298 // Given two packages
1299 final String CERT_DELEGATE = "com.delegate.certs";
1300 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1301 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1302 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1303 20989);
1304
1305 // On delegation
1306 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1307 mContext.packageName = admin1.getPackageName();
1308 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1309 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1310
1311 // DPMS correctly stores and retrieves the delegates
1312 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1313 assertEquals(2, policy.mDelegationMap.size());
1314 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1315 DELEGATION_CERT_INSTALL);
1316 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1317 DELEGATION_CERT_INSTALL);
1318 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1319 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1320 DELEGATION_APP_RESTRICTIONS);
1321 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1322 DELEGATION_APP_RESTRICTIONS);
1323 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1324
1325 // On calling install certificate APIs from an unauthorized process
1326 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1327 mContext.packageName = RESTRICTIONS_DELEGATE;
1328
1329 // DPMS throws a SecurityException
1330 try {
1331 dpm.installCaCert(null, null);
1332 fail("Didn't throw SecurityException on unauthorized access");
1333 } catch (SecurityException expected) {
1334 }
1335
1336 // On calling install certificate APIs from an authorized process
1337 mContext.binder.callingUid = CERT_DELEGATE_UID;
1338 mContext.packageName = CERT_DELEGATE;
1339
1340 // DPMS executes without a SecurityException
1341 try {
1342 dpm.installCaCert(null, null);
1343 } catch (SecurityException unexpected) {
1344 fail("Threw SecurityException on authorized access");
1345 } catch (NullPointerException expected) {
1346 }
1347
1348 // On removing a delegate
1349 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1350 mContext.packageName = admin1.getPackageName();
1351 dpm.setCertInstallerPackage(admin1, null);
1352
1353 // DPMS does not allow access to ex-delegate
1354 mContext.binder.callingUid = CERT_DELEGATE_UID;
1355 mContext.packageName = CERT_DELEGATE;
1356 try {
1357 dpm.installCaCert(null, null);
1358 fail("Didn't throw SecurityException on unauthorized access");
1359 } catch (SecurityException expected) {
1360 }
1361
1362 // But still allows access to other existing delegates
1363 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1364 mContext.packageName = RESTRICTIONS_DELEGATE;
1365 try {
1366 dpm.getApplicationRestrictions(null, "pkg");
1367 } catch (SecurityException expected) {
1368 fail("Threw SecurityException on authorized access");
1369 }
1370 }
1371
Esteban Talaverabf60f722015-12-10 16:26:44 +00001372 public void testApplicationRestrictionsManagingApp() throws Exception {
1373 setAsProfileOwner(admin1);
1374
Rubin Xued1928a2016-02-11 17:23:06 +00001375 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001376 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1377 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001378 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1379 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001380
Esteban Talaverabf60f722015-12-10 16:26:44 +00001381 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1382 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001383 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1384 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001385 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1386 Bundle rest = new Bundle();
1387 rest.putString("KEY_STRING", "Foo1");
1388 try {
1389 dpm.setApplicationRestrictions(null, "pkg1", rest);
1390 fail("Didn't throw expected SecurityException");
1391 } catch (SecurityException expected) {
1392 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001393 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1394 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001395 }
1396 try {
1397 dpm.getApplicationRestrictions(null, "pkg1");
1398 fail("Didn't throw expected SecurityException");
1399 } catch (SecurityException expected) {
1400 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001401 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1402 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001403 }
1404
1405 // Check via the profile owner that no restrictions were set.
1406 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001407 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001408 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1409
Rubin Xued1928a2016-02-11 17:23:06 +00001410 // Check the API does not allow setting a non-existent package
1411 try {
1412 dpm.setApplicationRestrictionsManagingPackage(admin1,
1413 nonExistAppRestrictionsManagerPackage);
1414 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001415 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001416 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001417 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001418 }
1419
Esteban Talaverabf60f722015-12-10 16:26:44 +00001420 // Let appRestrictionsManagerPackage manage app restrictions
1421 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1422 assertEquals(appRestrictionsManagerPackage,
1423 dpm.getApplicationRestrictionsManagingPackage(admin1));
1424
1425 // Now that package should be able to set and retrieve app restrictions.
1426 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001427 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001428 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1429 dpm.setApplicationRestrictions(null, "pkg1", rest);
1430 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1431 assertEquals(1, returned.size(), 1);
1432 assertEquals("Foo1", returned.get("KEY_STRING"));
1433
1434 // The same app running on a separate user shouldn't be able to manage app restrictions.
1435 mContext.binder.callingUid = UserHandle.getUid(
1436 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1437 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1438 try {
1439 dpm.setApplicationRestrictions(null, "pkg1", rest);
1440 fail("Didn't throw expected SecurityException");
1441 } catch (SecurityException expected) {
1442 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001443 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1444 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001445 }
1446
1447 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1448 // too.
1449 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001450 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001451 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1452 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1453 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1454
1455 // Removing the ability for the package to manage app restrictions.
1456 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1457 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1458 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001459 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001460 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1461 try {
1462 dpm.setApplicationRestrictions(null, "pkg1", null);
1463 fail("Didn't throw expected SecurityException");
1464 } catch (SecurityException expected) {
1465 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001466 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1467 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001468 }
1469 }
1470
Makoto Onukia4f11972015-10-01 13:19:58 -07001471 public void testSetUserRestriction_asDo() throws Exception {
1472 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001473 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001474 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1475 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1476
1477 // First, set DO.
1478
1479 // Call from a process on the system user.
1480 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1481
1482 // Make sure admin1 is installed on system user.
1483 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001484
1485 // Call.
1486 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001487 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001488 UserHandle.USER_SYSTEM));
1489
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001490 // Check that the user restrictions that are enabled by default are set. Then unset them.
1491 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001492 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001493 DpmTestUtils.assertRestrictions(
1494 DpmTestUtils.newRestrictions(defaultRestrictions),
1495 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1496 );
1497 DpmTestUtils.assertRestrictions(
1498 DpmTestUtils.newRestrictions(defaultRestrictions),
1499 dpm.getUserRestrictions(admin1)
1500 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001501 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1502 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001503 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001504 eq(true) /* isDeviceOwner */,
1505 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001506 );
1507 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001508
1509 for (String restriction : defaultRestrictions) {
1510 dpm.clearUserRestriction(admin1, restriction);
1511 }
1512
Esteban Talavera548a04b2016-12-20 15:22:30 +00001513 assertNoDeviceOwnerRestrictions();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001514 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001515
1516 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1517 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1518 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001519 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1520 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001521 reset(mContext.userManagerInternal);
1522
Makoto Onukia4f11972015-10-01 13:19:58 -07001523 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001524 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1525 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001526 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1527 UserManager.DISALLOW_ADD_USER),
1528 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001529 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001530
Makoto Onuki068c54a2015-10-13 14:34:03 -07001531 DpmTestUtils.assertRestrictions(
1532 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001533 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001534 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1535 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001536 DpmTestUtils.assertRestrictions(
1537 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001538 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001539 dpm.getUserRestrictions(admin1)
1540 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001541
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001542 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1543 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1544 eq(UserHandle.USER_SYSTEM),
1545 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001546 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001547 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001548
Makoto Onuki068c54a2015-10-13 14:34:03 -07001549 DpmTestUtils.assertRestrictions(
1550 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1551 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1552 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001553 DpmTestUtils.assertRestrictions(
1554 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1555 dpm.getUserRestrictions(admin1)
1556 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001557
1558 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001559 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1560 eq(UserHandle.USER_SYSTEM),
1561 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001562 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001563 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001564
Esteban Talavera548a04b2016-12-20 15:22:30 +00001565 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001566
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001567 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1568 // DO sets them, the scope is global.
1569 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1570 reset(mContext.userManagerInternal);
1571 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1572 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1573 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001574 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001575 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1576 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001577 reset(mContext.userManagerInternal);
1578
1579 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1580 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov6a40f092016-10-25 15:46:51 +01001581 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001582
1583 // More tests.
1584 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1585 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1586 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001587 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1588 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001589 reset(mContext.userManagerInternal);
1590
1591 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1592 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1593 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001594 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001595 UserManager.DISALLOW_ADD_USER),
1596 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001597 reset(mContext.userManagerInternal);
1598
1599 dpm.setCameraDisabled(admin1, true);
1600 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1601 eq(UserHandle.USER_SYSTEM),
1602 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001603 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001604 UserManager.DISALLOW_ADD_USER),
1605 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001606 reset(mContext.userManagerInternal);
1607
1608 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1609 // locally.
1610 dpm.setCameraDisabled(admin1, false);
1611 reset(mContext.userManagerInternal);
1612
1613 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1614 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1615 dpm.setCameraDisabled(admin2, true);
1616
1617 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1618 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001619 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001620 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001621 UserManager.DISALLOW_ADD_USER),
1622 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001623 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001624 // TODO Make sure restrictions are written to the file.
1625 }
1626
1627 public void testSetUserRestriction_asPo() {
1628 setAsProfileOwner(admin1);
1629
Makoto Onuki068c54a2015-10-13 14:34:03 -07001630 DpmTestUtils.assertRestrictions(
1631 DpmTestUtils.newRestrictions(),
1632 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1633 .ensureUserRestrictions()
1634 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001635
1636 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001637 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1638 eq(DpmMockContext.CALLER_USER_HANDLE),
1639 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001640 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001641 reset(mContext.userManagerInternal);
1642
Makoto Onukia4f11972015-10-01 13:19:58 -07001643 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001644 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1645 eq(DpmMockContext.CALLER_USER_HANDLE),
1646 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1647 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001648 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001650
Makoto Onuki068c54a2015-10-13 14:34:03 -07001651 DpmTestUtils.assertRestrictions(
1652 DpmTestUtils.newRestrictions(
1653 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1654 UserManager.DISALLOW_OUTGOING_CALLS
1655 ),
1656 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1657 .ensureUserRestrictions()
1658 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001659 DpmTestUtils.assertRestrictions(
1660 DpmTestUtils.newRestrictions(
1661 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1662 UserManager.DISALLOW_OUTGOING_CALLS
1663 ),
1664 dpm.getUserRestrictions(admin1)
1665 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001666
1667 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001668 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1669 eq(DpmMockContext.CALLER_USER_HANDLE),
1670 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001671 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001672 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001673
1674 DpmTestUtils.assertRestrictions(
1675 DpmTestUtils.newRestrictions(
1676 UserManager.DISALLOW_OUTGOING_CALLS
1677 ),
1678 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1679 .ensureUserRestrictions()
1680 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001681 DpmTestUtils.assertRestrictions(
1682 DpmTestUtils.newRestrictions(
1683 UserManager.DISALLOW_OUTGOING_CALLS
1684 ),
1685 dpm.getUserRestrictions(admin1)
1686 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001687
1688 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1690 eq(DpmMockContext.CALLER_USER_HANDLE),
1691 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001692 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001693 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001694
Makoto Onuki068c54a2015-10-13 14:34:03 -07001695 DpmTestUtils.assertRestrictions(
1696 DpmTestUtils.newRestrictions(),
1697 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1698 .ensureUserRestrictions()
1699 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001700 DpmTestUtils.assertRestrictions(
1701 DpmTestUtils.newRestrictions(),
1702 dpm.getUserRestrictions(admin1)
1703 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001704
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001705 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1706 // though when DO sets them they'll be applied globally.
1707 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1708 reset(mContext.userManagerInternal);
1709 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1710 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1711 eq(DpmMockContext.CALLER_USER_HANDLE),
1712 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1713 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001714 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715 reset(mContext.userManagerInternal);
1716
1717 dpm.setCameraDisabled(admin1, true);
1718 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1719 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001720 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001721 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001722 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001723 reset(mContext.userManagerInternal);
1724
Makoto Onukia4f11972015-10-01 13:19:58 -07001725 // TODO Make sure restrictions are written to the file.
1726 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001727
Esteban Talavera548a04b2016-12-20 15:22:30 +00001728
1729 public void testDefaultEnabledUserRestrictions() throws Exception {
1730 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1731 mContext.callerPermissions.add(permission.MANAGE_USERS);
1732 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1733 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1734
1735 // First, set DO.
1736
1737 // Call from a process on the system user.
1738 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1739
1740 // Make sure admin1 is installed on system user.
1741 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1742
1743 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1744 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1745 UserHandle.USER_SYSTEM));
1746
1747 // Check that the user restrictions that are enabled by default are set. Then unset them.
1748 String[] defaultRestrictions = UserRestrictionsUtils
1749 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1750 assertTrue(defaultRestrictions.length > 0);
1751 DpmTestUtils.assertRestrictions(
1752 DpmTestUtils.newRestrictions(defaultRestrictions),
1753 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1754 );
1755 DpmTestUtils.assertRestrictions(
1756 DpmTestUtils.newRestrictions(defaultRestrictions),
1757 dpm.getUserRestrictions(admin1)
1758 );
1759 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1760 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001761 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001762 eq(true) /* isDeviceOwner */,
1763 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001764 );
1765 reset(mContext.userManagerInternal);
1766
1767 for (String restriction : defaultRestrictions) {
1768 dpm.clearUserRestriction(admin1, restriction);
1769 }
1770
1771 assertNoDeviceOwnerRestrictions();
1772
1773 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1774 reset(mContext.userManagerInternal);
1775 initializeDpms();
1776 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1777 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1778
1779 assertNoDeviceOwnerRestrictions();
1780
1781 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1782 // is set as it wasn't enabled during setDeviceOwner.
1783 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1784 assertFalse(UserRestrictionsUtils
1785 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1786 UserRestrictionsUtils
1787 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1788 try {
1789 reset(mContext.userManagerInternal);
1790 initializeDpms();
1791 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1792 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1793
1794 DpmTestUtils.assertRestrictions(
1795 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1796 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1797 );
1798 DpmTestUtils.assertRestrictions(
1799 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1800 dpm.getUserRestrictions(admin1)
1801 );
1802 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1803 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001804 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001805 eq(true) /* isDeviceOwner */,
1806 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001807 );
1808 reset(mContext.userManagerInternal);
1809
1810 // Remove the restriction.
1811 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1812
1813 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1814 initializeDpms();
1815 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1816 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1817 assertNoDeviceOwnerRestrictions();
1818 } finally {
1819 UserRestrictionsUtils
1820 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1821 }
1822 }
1823
1824 private void assertNoDeviceOwnerRestrictions() {
1825 DpmTestUtils.assertRestrictions(
1826 DpmTestUtils.newRestrictions(),
1827 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1828 );
1829 DpmTestUtils.assertRestrictions(
1830 DpmTestUtils.newRestrictions(),
1831 dpm.getUserRestrictions(admin1)
1832 );
1833 }
1834
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001835 public void testGetMacAddress() throws Exception {
1836 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1837 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1838 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1839
1840 // In this test, change the caller user to "system".
1841 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1842
1843 // Make sure admin1 is installed on system user.
1844 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1845
1846 // Test 1. Caller doesn't have DO or DA.
1847 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001848 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001849 fail();
1850 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001851 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001852 }
1853
1854 // DO needs to be an DA.
1855 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1856 assertTrue(dpm.isAdminActive(admin1));
1857
1858 // Test 2. Caller has DA, but not DO.
1859 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001860 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001861 fail();
1862 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001863 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001864 }
1865
1866 // Test 3. Caller has PO, but not DO.
1867 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1868 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001869 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001870 fail();
1871 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001872 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001873 }
1874
1875 // Remove PO.
1876 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001877 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001878 // Test 4, Caller is DO now.
1879 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1880
1881 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001882 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001883
1884 // 4-2. Returns WifiInfo, but with the default MAC.
1885 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001886 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001887
1888 // 4-3. With a real MAC address.
1889 final WifiInfo wi = new WifiInfo();
1890 wi.setMacAddress("11:22:33:44:55:66");
1891 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001892 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001893 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001894
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001895 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001896 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1897 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1898
1899 // In this test, change the caller user to "system".
1900 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1901
1902 // Make sure admin1 is installed on system user.
1903 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1904
1905 // Set admin1 as DA.
1906 dpm.setActiveAdmin(admin1, false);
1907 assertTrue(dpm.isAdminActive(admin1));
1908 try {
1909 dpm.reboot(admin1);
1910 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1911 } catch (SecurityException expected) {
1912 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1913 }
1914
1915 // Set admin1 as PO.
1916 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1917 try {
1918 dpm.reboot(admin1);
1919 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1920 } catch (SecurityException expected) {
1921 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1922 }
1923
1924 // Remove PO and add DO.
1925 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001926 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001927 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1928
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001929 // admin1 is DO.
1930 // Set current call state of device to ringing.
1931 when(mContext.telephonyManager.getCallState())
1932 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1933 try {
1934 dpm.reboot(admin1);
1935 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1936 } catch (IllegalStateException expected) {
1937 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1938 }
1939
1940 // Set current call state of device to dialing/active.
1941 when(mContext.telephonyManager.getCallState())
1942 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1943 try {
1944 dpm.reboot(admin1);
1945 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1946 } catch (IllegalStateException expected) {
1947 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1948 }
1949
1950 // Set current call state of device to idle.
1951 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001952 dpm.reboot(admin1);
1953 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001954
1955 public void testSetGetSupportText() {
1956 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1957 dpm.setActiveAdmin(admin1, true);
1958 dpm.setActiveAdmin(admin2, true);
1959 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1960
1961 // Null default support messages.
1962 {
1963 assertNull(dpm.getLongSupportMessage(admin1));
1964 assertNull(dpm.getShortSupportMessage(admin1));
1965 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1966 assertNull(dpm.getShortSupportMessageForUser(admin1,
1967 DpmMockContext.CALLER_USER_HANDLE));
1968 assertNull(dpm.getLongSupportMessageForUser(admin1,
1969 DpmMockContext.CALLER_USER_HANDLE));
1970 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1971 }
1972
1973 // Only system can call the per user versions.
1974 {
1975 try {
1976 dpm.getShortSupportMessageForUser(admin1,
1977 DpmMockContext.CALLER_USER_HANDLE);
1978 fail("Only system should be able to call getXXXForUser versions");
1979 } catch (SecurityException expected) {
1980 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1981 }
1982 try {
1983 dpm.getLongSupportMessageForUser(admin1,
1984 DpmMockContext.CALLER_USER_HANDLE);
1985 fail("Only system should be able to call getXXXForUser versions");
1986 } catch (SecurityException expected) {
1987 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1988 }
1989 }
1990
1991 // Can't set message for admin in another uid.
1992 {
1993 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1994 try {
1995 dpm.setShortSupportMessage(admin1, "Some text");
1996 fail("Admins should only be able to change their own support text.");
1997 } catch (SecurityException expected) {
1998 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1999 }
2000 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2001 }
2002
2003 // Set/Get short returns what it sets and other admins text isn't changed.
2004 {
2005 final String supportText = "Some text to test with.";
2006 dpm.setShortSupportMessage(admin1, supportText);
2007 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2008 assertNull(dpm.getLongSupportMessage(admin1));
2009 assertNull(dpm.getShortSupportMessage(admin2));
2010
2011 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2012 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2013 DpmMockContext.CALLER_USER_HANDLE));
2014 assertNull(dpm.getShortSupportMessageForUser(admin2,
2015 DpmMockContext.CALLER_USER_HANDLE));
2016 assertNull(dpm.getLongSupportMessageForUser(admin1,
2017 DpmMockContext.CALLER_USER_HANDLE));
2018 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2019
2020 dpm.setShortSupportMessage(admin1, null);
2021 assertNull(dpm.getShortSupportMessage(admin1));
2022 }
2023
2024 // Set/Get long returns what it sets and other admins text isn't changed.
2025 {
2026 final String supportText = "Some text to test with.\nWith more text.";
2027 dpm.setLongSupportMessage(admin1, supportText);
2028 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2029 assertNull(dpm.getShortSupportMessage(admin1));
2030 assertNull(dpm.getLongSupportMessage(admin2));
2031
2032 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2033 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2034 DpmMockContext.CALLER_USER_HANDLE));
2035 assertNull(dpm.getLongSupportMessageForUser(admin2,
2036 DpmMockContext.CALLER_USER_HANDLE));
2037 assertNull(dpm.getShortSupportMessageForUser(admin1,
2038 DpmMockContext.CALLER_USER_HANDLE));
2039 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2040
2041 dpm.setLongSupportMessage(admin1, null);
2042 assertNull(dpm.getLongSupportMessage(admin1));
2043 }
2044 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002045
phweiss73145f42017-01-17 19:06:38 +01002046 public void testCreateAdminSupportIntent() throws Exception {
2047 // Setup device owner.
2048 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2049 setupDeviceOwner();
2050
2051 // Nonexisting permission returns null
2052 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2053 assertNull(intent);
2054
2055 // Existing permission that is not set returns null
2056 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2057 assertNull(intent);
2058
2059 // Existing permission that is not set by device/profile owner returns null
2060 when(mContext.userManager.hasUserRestriction(
2061 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2062 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2063 .thenReturn(true);
2064 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2065 assertNull(intent);
2066
2067 // Permission that is set by device owner returns correct intent
2068 when(mContext.userManager.getUserRestrictionSource(
2069 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2070 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2071 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2072 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2073 assertNotNull(intent);
2074 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2075 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2076 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2077 assertEquals(admin1,
2078 (ComponentName) intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
2079 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2080 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2081
2082 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2083 // user restrictions
2084
2085 // Camera is not disabled
2086 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2087 assertNull(intent);
2088
2089 // Camera is disabled
2090 dpm.setCameraDisabled(admin1, true);
2091 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2092 assertNotNull(intent);
2093 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2094 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2095
2096 // Screen capture is not disabled
2097 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2098 assertNull(intent);
2099
2100 // Screen capture is disabled
2101 dpm.setScreenCaptureDisabled(admin1, true);
2102 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2103 assertNotNull(intent);
2104 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2105 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2106
2107 // Same checks for different user
2108 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2109 // Camera should be disabled by device owner
2110 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2111 assertNotNull(intent);
2112 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2113 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2114 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2115 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2116 // ScreenCapture should not be disabled by device owner
2117 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2118 assertNull(intent);
2119 }
2120
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002121 /**
2122 * Test for:
2123 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002124 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002125 * {@link DevicePolicyManager#isAffiliatedUser}
2126 */
2127 public void testUserAffiliation() throws Exception {
2128 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2129 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2130 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2131
2132 // Check that the system user is unaffiliated.
2133 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2134 assertFalse(dpm.isAffiliatedUser());
2135
2136 // Set a device owner on the system user. Check that the system user becomes affiliated.
2137 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2138 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2139 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2140 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002141 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002142
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002143 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002144 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2145 setAsProfileOwner(admin2);
2146 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002147 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002148
2149 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2150 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002151 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002152 userAffiliationIds.add("red");
2153 userAffiliationIds.add("green");
2154 userAffiliationIds.add("blue");
2155 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002156 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002157 assertFalse(dpm.isAffiliatedUser());
2158
2159 // Have the device owner specify a set of affiliation ids that do not intersect with those
2160 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002161 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002162 deviceAffiliationIds.add("cyan");
2163 deviceAffiliationIds.add("yellow");
2164 deviceAffiliationIds.add("magenta");
2165 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2166 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002167 MoreAsserts.assertContentsInAnyOrder(
2168 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002169 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2170 assertFalse(dpm.isAffiliatedUser());
2171
2172 // Have the profile owner specify a set of affiliation ids that intersect with those
2173 // specified by the device owner. Check that the test user becomes affiliated.
2174 userAffiliationIds.add("yellow");
2175 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002176 MoreAsserts.assertContentsInAnyOrder(
2177 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002178 assertTrue(dpm.isAffiliatedUser());
2179
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002180 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
2181 dpm.setAffiliationIds(admin2, Collections.emptyList());
2182 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002183 assertFalse(dpm.isAffiliatedUser());
2184
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002185 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2186 dpm.setAffiliationIds(admin2, userAffiliationIds);
2187 assertTrue(dpm.isAffiliatedUser());
2188 dpm.clearProfileOwner(admin2);
2189 assertFalse(dpm.isAffiliatedUser());
2190
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002191 // Check that the system user remains affiliated.
2192 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2193 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002194
2195 // Clear the device owner - the user becomes unaffiliated.
2196 clearDeviceOwner();
2197 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002198 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002199
2200 public void testGetUserProvisioningState_defaultResult() {
2201 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2202 }
2203
2204 public void testSetUserProvisioningState_permission() throws Exception {
2205 setupProfileOwner();
2206 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2207
2208 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2209 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2210 }
2211
2212 public void testSetUserProvisioningState_unprivileged() throws Exception {
2213 setupProfileOwner();
2214 try {
2215 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2216 DpmMockContext.CALLER_USER_HANDLE);
2217 fail("Expected SecurityException");
2218 } catch (SecurityException expected) {
2219 }
2220 }
2221
2222 public void testSetUserProvisioningState_noManagement() {
2223 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2224 try {
2225 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2226 DpmMockContext.CALLER_USER_HANDLE);
2227 fail("IllegalStateException expected");
2228 } catch (IllegalStateException e) {
2229 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
2230 e.getMessage());
2231 }
2232 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2233 }
2234
2235 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2236 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2237 setupDeviceOwner();
2238 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2239
2240 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2241 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2242 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2243 }
2244
2245 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2246 throws Exception {
2247 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2248 setupDeviceOwner();
2249 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2250
2251 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2252 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2253 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2254 }
2255
2256 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2257 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2258 setupDeviceOwner();
2259 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2260
2261 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2262 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2263 }
2264
2265 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2266 throws Exception {
2267 setupProfileOwner();
2268 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2269
2270 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2271 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2272 DevicePolicyManager.STATE_USER_UNMANAGED);
2273 }
2274
2275 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2276 throws Exception {
2277 setupProfileOwner();
2278 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2279
2280 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2281 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2282 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2283 }
2284
2285 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2286 setupProfileOwner();
2287 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2288
2289 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2290 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2291 }
2292
2293 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2294 setupProfileOwner();
2295 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2296
2297 try {
2298 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2299 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2300 DevicePolicyManager.STATE_USER_UNMANAGED);
2301 fail("Expected IllegalStateException");
2302 } catch (IllegalStateException e) {
2303 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2304 e.getMessage());
2305 }
2306 }
2307
2308 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2309 throws Exception {
2310 setupProfileOwner();
2311 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2312
2313 try {
2314 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2315 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2316 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2317 fail("Expected IllegalStateException");
2318 } catch (IllegalStateException e) {
2319 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2320 e.getMessage());
2321 }
2322 }
2323
2324 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2325 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2326 for (int state : states) {
2327 dpm.setUserProvisioningState(state, userId);
2328 assertEquals(state, dpm.getUserProvisioningState());
2329 }
2330 }
2331
2332 private void setupProfileOwner() throws Exception {
2333 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2334
2335 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2336 dpm.setActiveAdmin(admin1, false);
2337 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2338
2339 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2340 }
2341
2342 private void setupDeviceOwner() throws Exception {
2343 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2344
2345 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2346 dpm.setActiveAdmin(admin1, false);
2347 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2348
2349 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2350 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002351
2352 public void testSetMaximumTimeToLock() {
2353 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2354
2355 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2356 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2357
2358 reset(mMockContext.powerManagerInternal);
2359 reset(mMockContext.settings);
2360
2361 dpm.setMaximumTimeToLock(admin1, 0);
2362 verifyScreenTimeoutCall(null, false);
2363 reset(mMockContext.powerManagerInternal);
2364 reset(mMockContext.settings);
2365
2366 dpm.setMaximumTimeToLock(admin1, 1);
2367 verifyScreenTimeoutCall(1, true);
2368 reset(mMockContext.powerManagerInternal);
2369 reset(mMockContext.settings);
2370
2371 dpm.setMaximumTimeToLock(admin2, 10);
2372 verifyScreenTimeoutCall(null, false);
2373 reset(mMockContext.powerManagerInternal);
2374 reset(mMockContext.settings);
2375
2376 dpm.setMaximumTimeToLock(admin1, 5);
2377 verifyScreenTimeoutCall(5, true);
2378 reset(mMockContext.powerManagerInternal);
2379 reset(mMockContext.settings);
2380
2381 dpm.setMaximumTimeToLock(admin2, 4);
2382 verifyScreenTimeoutCall(4, true);
2383 reset(mMockContext.powerManagerInternal);
2384 reset(mMockContext.settings);
2385
2386 dpm.setMaximumTimeToLock(admin1, 0);
2387 reset(mMockContext.powerManagerInternal);
2388 reset(mMockContext.settings);
2389
2390 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2391 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2392 reset(mMockContext.powerManagerInternal);
2393 reset(mMockContext.settings);
2394
2395 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2396 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2397 reset(mMockContext.powerManagerInternal);
2398 reset(mMockContext.settings);
2399
2400 dpm.setMaximumTimeToLock(admin2, 10);
2401 verifyScreenTimeoutCall(10, true);
2402 reset(mMockContext.powerManagerInternal);
2403 reset(mMockContext.settings);
2404
2405 // There's no restriction; shold be set to MAX.
2406 dpm.setMaximumTimeToLock(admin2, 0);
2407 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2408 }
2409
Michal Karpinski943aabd2016-10-06 11:09:25 +01002410 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2411 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2412 setupDeviceOwner();
2413 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2414
Michal Karpinskid084ca52017-01-18 15:54:18 +00002415 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2416 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2417 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2418 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2419 - ONE_MINUTE;
2420
2421 // verify that the minimum timeout cannot be modified on user builds (system property is
2422 // not being read)
2423 mContext.buildMock.isDebuggable = false;
2424
2425 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2426 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2427 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2428
2429 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2430
2431 // restore to the debuggable build state
2432 mContext.buildMock.isDebuggable = true;
2433
2434 // Always return the default (second arg) when getting system property for long type
2435 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2436 new Answer<Long>() {
2437 @Override
2438 public Long answer(InvocationOnMock invocation) throws Throwable {
2439 return (Long) invocation.getArguments()[1];
2440 }
2441 }
2442 );
2443
2444 // reset to default (0 means the admin is not participating, so default should be returned)
2445 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002446
2447 // aggregation should be the default if unset by any admin
2448 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2449 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2450
2451 // admin not participating by default
2452 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2453
2454 //clamping from the top
2455 dpm.setRequiredStrongAuthTimeout(admin1,
2456 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2457 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2458 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2459 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2460 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2461
Michal Karpinskid084ca52017-01-18 15:54:18 +00002462 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002463 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2464 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2465 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2466 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2467
2468 // clamping from the bottom
2469 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2470 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2471 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2472
Michal Karpinskid084ca52017-01-18 15:54:18 +00002473 // values within range
2474 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2475 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2476 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2477
2478 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2479 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2480 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002481
2482 // reset to default
2483 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2484 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2485 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2486 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2487
2488 // negative value
2489 try {
2490 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2491 fail("Didn't throw IllegalArgumentException");
2492 } catch (IllegalArgumentException iae) {
2493 }
2494 }
2495
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002496 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2497 boolean shouldStayOnWhilePluggedInBeCleared) {
2498 if (expectedTimeout == null) {
2499 verify(mMockContext.powerManagerInternal, times(0))
2500 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2501 } else {
2502 verify(mMockContext.powerManagerInternal, times(1))
2503 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2504 }
2505 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2506 // UnfinishedVerificationException.
2507 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002508
Esteban Talavera01576862016-12-15 11:16:44 +00002509 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002510 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2511 .thenReturn(false);
2512 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2513 .thenReturn(false);
2514 initializeDpms();
2515 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2516 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2517 .thenReturn(true);
2518 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2519
2520 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002521 }
Victor Chang3e794af2016-03-04 13:48:17 +00002522
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002523 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2524 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002525 mContext.packageName = admin1.getPackageName();
2526 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002527 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2528 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2529 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2530 false);
2531 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2532 }
2533
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002534 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2535 setup_DeviceAdminFeatureOff();
2536 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2537 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2538 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2539 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2540 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2541 assertCheckProvisioningPreCondition(
2542 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2543 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2544 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2545 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2546 }
2547
Esteban Talavera01576862016-12-15 11:16:44 +00002548 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002549 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2550 .thenReturn(false);
2551 initializeDpms();
2552 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2553 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2554 .thenReturn(true);
2555 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2556
2557 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002558 }
Victor Chang3e794af2016-03-04 13:48:17 +00002559
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002560 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2561 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002562 mContext.packageName = admin1.getPackageName();
2563 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002564 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2565 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2566 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2567 false);
2568 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2569
2570 // Test again when split user is on
2571 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2572 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2573 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2574 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2575 true);
2576 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2577 }
2578
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002579 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2580 setup_ManagedProfileFeatureOff();
2581 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2582 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2583 DevicePolicyManager.CODE_OK);
2584 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2585 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2586 assertCheckProvisioningPreCondition(
2587 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2588 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2589 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2590 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2591
2592 // Test again when split user is on
2593 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2594 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2595 DevicePolicyManager.CODE_OK);
2596 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2597 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2598 assertCheckProvisioningPreCondition(
2599 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2600 DevicePolicyManager.CODE_OK);
2601 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2602 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2603 }
2604
Esteban Talavera01576862016-12-15 11:16:44 +00002605 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002606 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2607 .thenReturn(true);
2608 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2609 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2610 .thenReturn(true);
2611 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2612
2613 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002614 }
Victor Chang3e794af2016-03-04 13:48:17 +00002615
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002616 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2617 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002618 mContext.packageName = admin1.getPackageName();
2619 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002620 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2621 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2622 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2623 false /* because of non-split user */);
2624 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2625 false /* because of non-split user */);
2626 }
2627
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002628 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002629 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002630 setup_nonSplitUser_firstBoot_primaryUser();
2631 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2632 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2633 DevicePolicyManager.CODE_OK);
2634 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2635 DevicePolicyManager.CODE_OK);
2636 assertCheckProvisioningPreCondition(
2637 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2638 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2639 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2640 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2641 }
2642
Esteban Talavera01576862016-12-15 11:16:44 +00002643 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002644 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2645 .thenReturn(true);
2646 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2647 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2648 .thenReturn(true);
2649 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2650
2651 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002652 }
Victor Chang3e794af2016-03-04 13:48:17 +00002653
Nicolas Prevot45d29072017-01-18 16:11:19 +00002654 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2655 setDeviceOwner();
2656 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2657 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2658 }
2659
2660 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2661 setup_nonSplitUser_withDo_primaryUser();
2662 final int MANAGED_PROFILE_USER_ID = 18;
2663 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2664 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2665 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2666 false /* we can't remove a managed profile */)).thenReturn(false);
2667 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2668 true)).thenReturn(true);
2669 }
2670
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002671 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2672 throws Exception {
2673 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002674 mContext.packageName = admin1.getPackageName();
2675 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002676 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2677 false/* because of completed device setup */);
2678 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2679 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2680 false/* because of non-split user */);
2681 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2682 false/* because of non-split user */);
2683 }
2684
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002685 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2686 throws Exception {
2687 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2688 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2689 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2690 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2691 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2692 DevicePolicyManager.CODE_OK);
2693 assertCheckProvisioningPreCondition(
2694 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2695 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2696 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2697 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2698 }
2699
Nicolas Prevot45d29072017-01-18 16:11:19 +00002700 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2701 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002702 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002703 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2704
2705 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2706 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002707 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002708
2709 // COMP mode is allowed.
2710 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2711 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002712 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002713
Nicolas Prevot45d29072017-01-18 16:11:19 +00002714 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002715 assertCheckProvisioningPreCondition(
2716 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002717 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002718 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002719 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2720 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2721 }
Esteban Talavera01576862016-12-15 11:16:44 +00002722
Nicolas Prevot45d29072017-01-18 16:11:19 +00002723 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2724 setup_nonSplitUser_withDo_primaryUser();
2725 mContext.packageName = admin1.getPackageName();
2726 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2727 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2728 // other packages should be forbidden.
Esteban Talavera01576862016-12-15 11:16:44 +00002729 when(mContext.userManager.hasUserRestriction(
2730 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2731 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2732 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002733 when(mContext.userManager.getUserRestrictionSource(
2734 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2735 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2736 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2737 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2738 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002739 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002740 assertCheckProvisioningPreCondition(
2741 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002742 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002743 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002744 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2745 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2746 }
Esteban Talavera01576862016-12-15 11:16:44 +00002747
Nicolas Prevot45d29072017-01-18 16:11:19 +00002748 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2749 throws Exception {
2750 setup_nonSplitUser_withDo_primaryUser();
2751 mContext.packageName = admin1.getPackageName();
2752 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002753 // The DO should not be allowed to initiate provisioning if the restriction is set by
2754 // another entity.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002755 when(mContext.userManager.hasUserRestriction(
2756 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2757 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2758 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002759 when(mContext.userManager.getUserRestrictionSource(
2760 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2761 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2762 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2763 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2764 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002765 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2766
2767 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002768 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002769 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002770 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002771 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2772 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2773 }
2774
2775 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2776 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2777 mContext.packageName = admin1.getPackageName();
2778 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2779
2780 // We can delete the managed profile to create a new one, so provisioning is allowed.
2781 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2782 DevicePolicyManager.CODE_OK);
2783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2784 assertCheckProvisioningPreCondition(
2785 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2786 DpmMockContext.ANOTHER_PACKAGE_NAME,
2787 DevicePolicyManager.CODE_OK);
2788 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2789 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2790 }
2791
2792 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2793 throws Exception {
2794 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2795 mContext.packageName = admin1.getPackageName();
2796 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2797 when(mContext.userManager.hasUserRestriction(
2798 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2799 eq(UserHandle.SYSTEM)))
2800 .thenReturn(true);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002801 when(mContext.userManager.getUserRestrictionSource(
2802 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2803 eq(UserHandle.SYSTEM)))
2804 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002805
2806 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002807 assertCheckProvisioningPreCondition(
2808 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2809 DpmMockContext.ANOTHER_PACKAGE_NAME,
2810 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2811 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2812 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002813
2814 // But the device owner can still do it because it has set the restriction itself.
2815 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2816 DevicePolicyManager.CODE_OK);
2817 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002818 }
2819
2820 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002821 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2822 .thenReturn(true);
2823 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2824 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2825 .thenReturn(false);
2826 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2827
2828 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002829 }
Victor Chang3e794af2016-03-04 13:48:17 +00002830
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002831 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2832 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002833 mContext.packageName = admin1.getPackageName();
2834 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002835 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2836 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2837 false /* because canAddMoreManagedProfiles returns false */);
2838 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2839 true);
2840 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2841 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002842 }
2843
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002844 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2845 throws Exception {
2846 setup_splitUser_firstBoot_systemUser();
2847 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2848 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2849 DevicePolicyManager.CODE_OK);
2850 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002851 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002852 assertCheckProvisioningPreCondition(
2853 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2854 DevicePolicyManager.CODE_OK);
2855 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2856 DevicePolicyManager.CODE_SYSTEM_USER);
2857 }
2858
Esteban Talavera01576862016-12-15 11:16:44 +00002859 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002860 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2861 .thenReturn(true);
2862 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2863 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2864 .thenReturn(false);
2865 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2866
2867 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002868 }
Victor Chang3e794af2016-03-04 13:48:17 +00002869
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002870 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2871 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002872 mContext.packageName = admin1.getPackageName();
2873 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002874 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2875 true/* it's undefined behavior. Can be changed into false in the future */);
2876 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2877 false /* because canAddMoreManagedProfiles returns false */);
2878 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2879 true/* it's undefined behavior. Can be changed into false in the future */);
2880 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2881 false/* because calling uid is system user */);
2882 }
2883
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002884 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2885 throws Exception {
2886 setup_splitUser_afterDeviceSetup_systemUser();
2887 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2888 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2889 DevicePolicyManager.CODE_OK);
2890 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002891 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002892 assertCheckProvisioningPreCondition(
2893 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2894 DevicePolicyManager.CODE_OK);
2895 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2896 DevicePolicyManager.CODE_SYSTEM_USER);
2897 }
2898
Esteban Talavera01576862016-12-15 11:16:44 +00002899 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002900 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2901 .thenReturn(true);
2902 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2903 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2904 true)).thenReturn(true);
2905 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2906
2907 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002908 }
Victor Chang3e794af2016-03-04 13:48:17 +00002909
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002910 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2911 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002912 mContext.packageName = admin1.getPackageName();
2913 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002914 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2915 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2916 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2917 true);
2918 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002919 }
2920
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002921 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002922 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002923 setup_splitUser_firstBoot_primaryUser();
2924 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2925 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2926 DevicePolicyManager.CODE_OK);
2927 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2928 DevicePolicyManager.CODE_OK);
2929 assertCheckProvisioningPreCondition(
2930 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2931 DevicePolicyManager.CODE_OK);
2932 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2933 DevicePolicyManager.CODE_OK);
2934 }
2935
Esteban Talavera01576862016-12-15 11:16:44 +00002936 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002937 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2938 .thenReturn(true);
2939 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2940 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2941 true)).thenReturn(true);
2942 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2943
2944 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002945 }
Victor Chang3e794af2016-03-04 13:48:17 +00002946
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002947 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2948 throws Exception {
2949 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002950 mContext.packageName = admin1.getPackageName();
2951 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002952 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2953 true/* it's undefined behavior. Can be changed into false in the future */);
2954 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2955 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2956 true/* it's undefined behavior. Can be changed into false in the future */);
2957 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2958 false/* because user setup completed */);
2959 }
2960
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002961 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002962 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002963 setup_splitUser_afterDeviceSetup_primaryUser();
2964 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2965 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2966 DevicePolicyManager.CODE_OK);
2967 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2968 DevicePolicyManager.CODE_OK);
2969 assertCheckProvisioningPreCondition(
2970 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2971 DevicePolicyManager.CODE_OK);
2972 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2973 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2974 }
2975
Esteban Talavera01576862016-12-15 11:16:44 +00002976 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002977 setDeviceOwner();
2978
2979 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2980 .thenReturn(true);
2981 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2982 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2983 .thenReturn(false);
2984 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2985
2986 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002987 }
Victor Chang3e794af2016-03-04 13:48:17 +00002988
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002989 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2990 throws Exception {
2991 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002992 mContext.packageName = admin1.getPackageName();
2993 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002994 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2995 false /* can't provision managed profile on system user */);
2996 }
2997
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002998 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002999 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003000 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3001 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3002 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3003 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3004 }
3005
3006 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003007 setDeviceOwner();
3008
3009 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3010 .thenReturn(true);
3011 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
3012 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3013 true)).thenReturn(true);
3014 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3015
3016 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003017 }
Victor Chang3e794af2016-03-04 13:48:17 +00003018
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003019 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3020 throws Exception {
3021 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003022 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3023 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003024 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3025 }
3026
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003027 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003028 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003029 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3030 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003031
3032 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003033 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3034 DevicePolicyManager.CODE_OK);
3035 }
3036
3037 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003038 setDeviceOwner();
3039
3040 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3041 .thenReturn(true);
3042 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003043 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003044 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3045 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003046 .thenReturn(true);
3047 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003048 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003049 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3050 true)).thenReturn(true);
3051 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3052
3053 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003054 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003055
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003056 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3057 throws Exception {
3058 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003059 mContext.packageName = admin1.getPackageName();
3060 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003061 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3062 }
3063
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003064 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3065 throws Exception {
3066 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3067 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3068 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3069 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3070 }
3071
3072 public void testCheckProvisioningPreCondition_permission() {
3073 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3074 try {
Esteban Talavera01576862016-12-15 11:16:44 +00003075 dpm.checkProvisioningPreCondition(
3076 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003077 fail("Didn't throw SecurityException");
3078 } catch (SecurityException expected) {
3079 }
3080 }
3081
Victor Chang3577ed22016-08-25 18:49:26 +01003082 public void testForceUpdateUserSetupComplete_permission() {
3083 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3084 try {
3085 dpm.forceUpdateUserSetupComplete();
3086 fail("Didn't throw SecurityException");
3087 } catch (SecurityException expected) {
3088 }
3089 }
3090
3091 public void testForceUpdateUserSetupComplete_systemUser() {
3092 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3093 // GIVEN calling from user 20
3094 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3095 try {
3096 dpm.forceUpdateUserSetupComplete();
3097 fail("Didn't throw SecurityException");
3098 } catch (SecurityException expected) {
3099 }
3100 }
3101
3102 public void testForceUpdateUserSetupComplete_userbuild() {
3103 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3104 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3105
3106 final int userId = UserHandle.USER_SYSTEM;
3107 // GIVEN userComplete is false in SettingsProvider
3108 setUserSetupCompleteForUser(false, userId);
3109
3110 // GIVEN userComplete is true in DPM
3111 DevicePolicyManagerService.DevicePolicyData userData =
3112 new DevicePolicyManagerService.DevicePolicyData(userId);
3113 userData.mUserSetupComplete = true;
3114 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3115
3116 // GIVEN it's user build
3117 mContext.buildMock.isDebuggable = false;
3118
3119 assertTrue(dpms.hasUserSetupCompleted());
3120
3121 dpm.forceUpdateUserSetupComplete();
3122
3123 // THEN the state in dpms is not changed
3124 assertTrue(dpms.hasUserSetupCompleted());
3125 }
3126
3127 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3128 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3129 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3130
3131 final int userId = UserHandle.USER_SYSTEM;
3132 // GIVEN userComplete is false in SettingsProvider
3133 setUserSetupCompleteForUser(false, userId);
3134
3135 // GIVEN userComplete is true in DPM
3136 DevicePolicyManagerService.DevicePolicyData userData =
3137 new DevicePolicyManagerService.DevicePolicyData(userId);
3138 userData.mUserSetupComplete = true;
3139 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3140
3141 // GIVEN it's userdebug build
3142 mContext.buildMock.isDebuggable = true;
3143
3144 assertTrue(dpms.hasUserSetupCompleted());
3145
3146 dpm.forceUpdateUserSetupComplete();
3147
3148 // THEN the state in dpms is not changed
3149 assertFalse(dpms.hasUserSetupCompleted());
3150 }
3151
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003152 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003153 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003154 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3155 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
3156 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
3157 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003158 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003159 }
3160
3161 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3162 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3163 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003164
3165 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3166 // feature is disabled because there are non-affiliated secondary users.
3167 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003168 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3169 .thenReturn(true);
3170
3171 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003172 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003173
3174 // Enabling logging should not change the timestamp.
3175 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003176 verify(mContext.settings)
3177 .securityLogSetLoggingEnabledProperty(true);
3178 when(mContext.settings.securityLogGetLoggingEnabledProperty())
3179 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003180 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003181
3182 // Retrieving the logs should update the timestamp.
3183 final long beforeRetrieval = System.currentTimeMillis();
3184 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003185 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003186 final long afterRetrieval = System.currentTimeMillis();
3187 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3188 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3189
3190 // Retrieving the pre-boot logs should update the timestamp.
3191 Thread.sleep(2);
3192 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003193 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003194 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3195
3196 // Checking the timestamp again should not change it.
3197 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003198 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003199
3200 // Retrieving the logs again should update the timestamp.
3201 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003202 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003203 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3204
3205 // Disabling logging should not change the timestamp.
3206 Thread.sleep(2);
3207 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003208 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003209
3210 // Restarting the DPMS should not lose the timestamp.
3211 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003212 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003213
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003214 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3215 mContext.binder.callingUid = 1234567;
3216 mContext.callerPermissions.add(permission.MANAGE_USERS);
3217 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3218 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3219
3220 // System can retrieve the timestamp.
3221 mContext.binder.clearCallingIdentity();
3222 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3223
3224 // Removing the device owner should clear the timestamp.
3225 clearDeviceOwner();
3226 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003227 }
3228
3229 public void testGetLastBugReportRequestTime() throws Exception {
3230 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3231 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003232
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003233 mContext.packageName = admin1.getPackageName();
3234 mContext.applicationInfo = new ApplicationInfo();
3235 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3236 .thenReturn(Color.WHITE);
3237 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3238 anyObject())).thenReturn(Color.WHITE);
3239
Esteban Talaverad36dd152016-12-15 08:51:45 +00003240 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3241 // feature is disabled because there are non-affiliated secondary users.
3242 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3243
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003244 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003245 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003246
3247 // Requesting a bug report should update the timestamp.
3248 final long beforeRequest = System.currentTimeMillis();
3249 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003250 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003251 final long afterRequest = System.currentTimeMillis();
3252 assertTrue(bugReportRequestTime >= beforeRequest);
3253 assertTrue(bugReportRequestTime <= afterRequest);
3254
3255 // Checking the timestamp again should not change it.
3256 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003257 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003258
3259 // Restarting the DPMS should not lose the timestamp.
3260 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003261 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003262
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003263 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3264 mContext.binder.callingUid = 1234567;
3265 mContext.callerPermissions.add(permission.MANAGE_USERS);
3266 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3267 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3268
3269 // System can retrieve the timestamp.
3270 mContext.binder.clearCallingIdentity();
3271 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3272
3273 // Removing the device owner should clear the timestamp.
3274 clearDeviceOwner();
3275 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003276 }
3277
3278 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3279 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3280 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003281 mContext.packageName = admin1.getPackageName();
3282 mContext.applicationInfo = new ApplicationInfo();
3283 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3284 .thenReturn(Color.WHITE);
3285 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3286 anyObject())).thenReturn(Color.WHITE);
3287
3288 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3289 // feature is disabled because there are non-affiliated secondary users.
3290 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003291 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3292 .thenReturn(true);
3293
3294 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003295 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003296
3297 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3298 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003299 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003300
3301 // Enabling logging should not change the timestamp.
3302 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003303 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003304
3305 // Retrieving the logs should update the timestamp.
3306 final long beforeRetrieval = System.currentTimeMillis();
3307 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003308 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003309 final long afterRetrieval = System.currentTimeMillis();
3310 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3311 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3312
3313 // Checking the timestamp again should not change it.
3314 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003315 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003316
3317 // Retrieving the logs again should update the timestamp.
3318 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003319 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003320 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3321
3322 // Disabling logging should not change the timestamp.
3323 Thread.sleep(2);
3324 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003325 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003326
3327 // Restarting the DPMS should not lose the timestamp.
3328 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003329 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3330
3331 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3332 mContext.binder.callingUid = 1234567;
3333 mContext.callerPermissions.add(permission.MANAGE_USERS);
3334 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3335 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3336
3337 // System can retrieve the timestamp.
3338 mContext.binder.clearCallingIdentity();
3339 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3340
3341 // Removing the device owner should clear the timestamp.
3342 clearDeviceOwner();
3343 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003344 }
3345
Tony Mak2f26b792016-11-28 17:54:51 +00003346 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3347 // Setup device owner.
3348 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3349 setupDeviceOwner();
3350
3351 // Only device owner is setup, the result list should be empty.
3352 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3353 MoreAsserts.assertEmpty(targetUsers);
3354
3355 // Setup a managed profile managed by the same admin.
3356 final int MANAGED_PROFILE_USER_ID = 15;
3357 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3358 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3359
3360 // Add a secondary user, it should never talk with.
3361 final int ANOTHER_USER_ID = 36;
3362 mContext.addUser(ANOTHER_USER_ID, 0);
3363
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003364 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3365 // other.
3366 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3367 MoreAsserts.assertEmpty(targetUsers);
3368
3369 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3370 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3371 MoreAsserts.assertEmpty(targetUsers);
3372
3373 // Setting affiliation ids
3374 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3375 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3376 dpm.setAffiliationIds(admin1, userAffiliationIds);
3377
3378 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3379 dpm.setAffiliationIds(admin1, userAffiliationIds);
3380
Tony Mak2f26b792016-11-28 17:54:51 +00003381 // Calling from device owner admin, the result list should just contain the managed
3382 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003383 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003384 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3385 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3386
3387 // Calling from managed profile admin, the result list should just contain the system
3388 // user id.
3389 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3390 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3391 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003392
3393 // Changing affiliation ids in one
3394 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3395
3396 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3397 // to each other.
3398 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3399 MoreAsserts.assertEmpty(targetUsers);
3400
3401 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3402 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3403 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003404 }
3405
3406 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3407 // Setup a device owner.
3408 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3409 setupDeviceOwner();
3410
3411 // Set up a managed profile managed by different package.
3412 final int MANAGED_PROFILE_USER_ID = 15;
3413 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3414 final ComponentName adminDifferentPackage =
3415 new ComponentName("another.package", "whatever.class");
3416 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3417
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003418 // Setting affiliation ids
3419 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3420 dpm.setAffiliationIds(admin1, userAffiliationIds);
3421
3422 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3423 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3424
Tony Mak2f26b792016-11-28 17:54:51 +00003425 // Calling from device owner admin, we should get zero bind device admin target users as
3426 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003427 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003428 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3429 MoreAsserts.assertEmpty(targetUsers);
3430
3431 // Calling from managed profile admin, we should still get zero target users for the same
3432 // reason.
3433 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3434 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3435 MoreAsserts.assertEmpty(targetUsers);
3436 }
3437
Esteban Talaverabdcada92017-02-01 14:20:06 +00003438 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3439 // Setup a device owner.
3440 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3441 setupDeviceOwner();
3442 // Lock task packages are updated when loading user data.
3443 verify(mContext.iactivityManager)
3444 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3445
3446 // Set up a managed profile managed by different package (package name shouldn't matter)
3447 final int MANAGED_PROFILE_USER_ID = 15;
3448 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3449 final ComponentName adminDifferentPackage =
3450 new ComponentName("another.package", "whatever.class");
3451 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3452 verify(mContext.iactivityManager)
3453 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3454
3455 // The DO can still set lock task packages
3456 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3457 final String[] doPackages = {"doPackage1", "doPackage2"};
3458 dpm.setLockTaskPackages(admin1, doPackages);
3459 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3460 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3461 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3462 verify(mContext.iactivityManager)
3463 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3464
3465 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3466 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3467 final String[] poPackages = {"poPackage1", "poPackage2"};
3468 try {
3469 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3470 fail("Didn't throw expected security exception.");
3471 } catch (SecurityException expected) {
3472 }
3473 try {
3474 dpm.getLockTaskPackages(adminDifferentPackage);
3475 fail("Didn't throw expected security exception.");
3476 } catch (SecurityException expected) {
3477 }
3478 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3479
3480 // Setting same affiliation ids
3481 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3482 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3483 dpm.setAffiliationIds(admin1, userAffiliationIds);
3484
3485 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3486 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3487
3488 // Now the managed profile can set lock task packages.
3489 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3490 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3491 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3492 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
3493 verify(mContext.iactivityManager)
3494 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3495
3496 // Unaffiliate the profile, lock task mode no longer available on the profile.
3497 dpm.setAffiliationIds(adminDifferentPackage, Collections.<String>emptyList());
3498 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3499 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
3500 verify(mContext.iactivityManager, times(2))
3501 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3502
3503 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3504 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3505 }
3506
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003507 public void testIsDeviceManaged() throws Exception {
3508 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3509 setupDeviceOwner();
3510
3511 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3512 // find out that the device has a device owner.
3513 assertTrue(dpm.isDeviceManaged());
3514 mContext.binder.callingUid = 1234567;
3515 mContext.callerPermissions.add(permission.MANAGE_USERS);
3516 assertTrue(dpm.isDeviceManaged());
3517 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3518 mContext.binder.clearCallingIdentity();
3519 assertTrue(dpm.isDeviceManaged());
3520
3521 clearDeviceOwner();
3522
3523 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3524 // not have a device owner.
3525 mContext.binder.callingUid = 1234567;
3526 mContext.callerPermissions.add(permission.MANAGE_USERS);
3527 assertFalse(dpm.isDeviceManaged());
3528 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3529 mContext.binder.clearCallingIdentity();
3530 assertFalse(dpm.isDeviceManaged());
3531 }
3532
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003533 public void testDeviceOwnerOrganizationName() throws Exception {
3534 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3535 setupDeviceOwner();
3536
3537 dpm.setOrganizationName(admin1, "organization");
3538
3539 // Device owner can retrieve organization managing the device.
3540 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3541
3542 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3543 mContext.binder.callingUid = 1234567;
3544 mContext.callerPermissions.add(permission.MANAGE_USERS);
3545 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3546 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3547
3548 // System can retrieve organization managing the device.
3549 mContext.binder.clearCallingIdentity();
3550 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3551
3552 // Removing the device owner clears the organization managing the device.
3553 clearDeviceOwner();
3554 assertNull(dpm.getDeviceOwnerOrganizationName());
3555 }
3556
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003557 public void testWipeDataManagedProfile() throws Exception {
3558 final int MANAGED_PROFILE_USER_ID = 15;
3559 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3560 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3561 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3562
3563 // Even if the caller is the managed profile, the current user is the user 0
3564 when(mContext.iactivityManager.getCurrentUser())
3565 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3566
3567 dpm.wipeData(0);
3568 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3569 MANAGED_PROFILE_USER_ID);
3570 }
3571
3572 public void testWipeDataManagedProfileDisallowed() throws Exception {
3573 final int MANAGED_PROFILE_USER_ID = 15;
3574 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3575 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3576
3577 // Even if the caller is the managed profile, the current user is the user 0
3578 when(mContext.iactivityManager.getCurrentUser())
3579 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3580
3581 when(mContext.userManager.getUserRestrictionSource(
3582 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3583 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3584 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3585 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3586 try {
3587 // The PO is not allowed to remove the profile if the user restriction was set on the
3588 // profile by the system
3589 dpm.wipeData(0);
3590 fail("SecurityException not thrown");
3591 } catch (SecurityException expected) {
3592 }
3593 }
3594
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003595 public void testWipeDataDeviceOwner() throws Exception {
3596 setDeviceOwner();
3597 when(mContext.userManager.getUserRestrictionSource(
3598 UserManager.DISALLOW_FACTORY_RESET,
3599 UserHandle.SYSTEM))
3600 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3601
3602 dpm.wipeData(0);
3603 verify(mContext.recoverySystem).rebootWipeUserData(
3604 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3605 }
3606
3607 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3608 setDeviceOwner();
3609 when(mContext.userManager.getUserRestrictionSource(
3610 UserManager.DISALLOW_FACTORY_RESET,
3611 UserHandle.SYSTEM))
3612 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3613 try {
3614 // The DO is not allowed to wipe the device if the user restriction was set
3615 // by the system
3616 dpm.wipeData(0);
3617 fail("SecurityException not thrown");
3618 } catch (SecurityException expected) {
3619 }
3620 }
3621
3622 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3623 final int MANAGED_PROFILE_USER_ID = 15;
3624 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3625 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3626
3627 // Even if the caller is the managed profile, the current user is the user 0
3628 when(mContext.iactivityManager.getCurrentUser())
3629 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3630
3631 when(mContext.userManager.getUserRestrictionSource(
3632 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3633 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3634 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3635
3636 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3637 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3638
3639 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3640 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3641 // Failed password attempts on the parent user are taken into account, as there isn't a
3642 // separate work challenge.
3643 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3644 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3645 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3646
3647 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3648 // both the user restriction and the policy were set by the PO.
3649 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3650 MANAGED_PROFILE_USER_ID);
3651 verifyZeroInteractions(mContext.recoverySystem);
3652 }
3653
3654 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3655 throws Exception {
3656 final int MANAGED_PROFILE_USER_ID = 15;
3657 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3658 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3659
3660 // Even if the caller is the managed profile, the current user is the user 0
3661 when(mContext.iactivityManager.getCurrentUser())
3662 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3663
3664 when(mContext.userManager.getUserRestrictionSource(
3665 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3666 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3667 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3668
3669 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3670 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3671
3672 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3673 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3674 // Failed password attempts on the parent user are taken into account, as there isn't a
3675 // separate work challenge.
3676 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3677 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3678 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3679
3680 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3681 // not wiped.
3682 verify(mContext.userManagerInternal, never())
3683 .removeUserEvenWhenDisallowed(anyInt());
3684 verifyZeroInteractions(mContext.recoverySystem);
3685 }
3686
3687 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3688 setDeviceOwner();
3689 when(mContext.userManager.getUserRestrictionSource(
3690 UserManager.DISALLOW_FACTORY_RESET,
3691 UserHandle.SYSTEM))
3692 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3693
3694 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3695
3696 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3697 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3698 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3699 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3700 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3701
3702 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3703 // user restriction and the policy were set by the DO.
3704 verify(mContext.recoverySystem).rebootWipeUserData(
3705 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3706 }
3707
3708 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3709 setDeviceOwner();
3710 when(mContext.userManager.getUserRestrictionSource(
3711 UserManager.DISALLOW_FACTORY_RESET,
3712 UserHandle.SYSTEM))
3713 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3714
3715 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3716
3717 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3718 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3719 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3720 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3721 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3722
3723 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
3724 verifyZeroInteractions(mContext.recoverySystem);
3725 verify(mContext.userManagerInternal, never())
3726 .removeUserEvenWhenDisallowed(anyInt());
3727 }
3728
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003729 public void testGetPermissionGrantState() throws Exception {
3730 final String permission = "some.permission";
3731 final String app1 = "com.example.app1";
3732 final String app2 = "com.example.app2";
3733
3734 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3735 .thenReturn(PackageManager.PERMISSION_GRANTED);
3736 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3737 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3738 when(mContext.packageManager.getPermissionFlags(permission, app1,
3739 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3740 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3741 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3742 .thenReturn(PackageManager.PERMISSION_DENIED);
3743 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3744 UserHandle.SYSTEM);
3745 when(mContext.packageManager.getPermissionFlags(permission, app2,
3746 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3747
3748 // System can retrieve permission grant state.
3749 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003750 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003751 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3752 dpm.getPermissionGrantState(null, app1, permission));
3753 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3754 dpm.getPermissionGrantState(null, app2, permission));
3755
3756 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003757 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3758 mContext.packageName = app1;
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003759 try {
3760 dpm.getPermissionGrantState(null, app1, permission);
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003761 fail("Didn't throw SecurityException");
3762 } catch (SecurityException expected) {
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003763 }
3764
3765 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003766 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3767 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003768 setAsProfileOwner(admin1);
3769 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3770 dpm.getPermissionGrantState(admin1, app1, permission));
3771 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3772 dpm.getPermissionGrantState(admin1, app2, permission));
3773 }
3774
Rubin Xuaab7a412016-12-30 21:13:29 +00003775 public void testResetPasswordWithToken() throws Exception {
3776 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3777 setupDeviceOwner();
3778 // test token validation
3779 try {
3780 dpm.setResetPasswordToken(admin1, new byte[31]);
3781 fail("should not have accepted tokens too short");
3782 } catch (IllegalArgumentException expected) {
3783 }
3784 // test adding a token
3785 final byte[] token = new byte[32];
3786 final long handle = 123456;
3787 final String password = "password";
3788 when(mContext.lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
3789 .thenReturn(handle);
3790 assertTrue(dpm.setResetPasswordToken(admin1, token));
3791
3792 // test password activation
3793 when(mContext.lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
3794 .thenReturn(true);
3795 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3796
3797 // test reset password with token
3798 when(mContext.lockPatternUtils.setLockCredentialWithToken(eq(password),
3799 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3800 eq(UserHandle.USER_SYSTEM)))
3801 .thenReturn(true);
3802 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3803
3804 // test removing a token
3805 when(mContext.lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
3806 .thenReturn(true);
3807 assertTrue(dpm.clearResetPasswordToken(admin1));
3808 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003809
3810 public void testIsDefaultInputMethodSetByOwnerForDeviceOwner() throws Exception {
3811 final String defaultIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3812 final Uri defaultImeUri = Settings.Secure.getUriFor(defaultIme);
3813 final UserHandle firstUser = UserHandle.SYSTEM;
3814 final UserHandle secondUser = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
3815
3816 // Set up a Device Owner.
3817 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3818 setupDeviceOwner();
3819
3820 // First and second user set default IMEs manually.
3821 final long ident = mContext.binder.clearCallingIdentity();
3822 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3823 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3824 mContext.binder.restoreCallingIdentity(ident);
3825
3826 // Device Owner changes default IME for first user.
3827 when(mContext.settings.settingsSecureGetStringForUser(defaultIme, UserHandle.USER_SYSTEM))
3828 .thenReturn("ime1");
3829 dpm.setSecureSetting(admin1, defaultIme, "ime2");
3830 verify(mContext.settings).settingsSecurePutStringForUser(defaultIme, "ime2",
3831 UserHandle.USER_SYSTEM);
3832 reset(mContext.settings);
3833 dpms.notifyChangeToContentObserver(defaultImeUri, UserHandle.USER_SYSTEM);
3834 mContext.binder.clearCallingIdentity();
3835 assertTrue(dpm.isDefaultInputMethodSetByOwner(firstUser));
3836 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3837 mContext.binder.restoreCallingIdentity(ident);
3838
3839 // Second user changes default IME manually.
3840 dpms.notifyChangeToContentObserver(defaultImeUri, DpmMockContext.CALLER_USER_HANDLE);
3841 mContext.binder.clearCallingIdentity();
3842 assertTrue(dpm.isDefaultInputMethodSetByOwner(firstUser));
3843 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3844 mContext.binder.restoreCallingIdentity(ident);
3845
3846 // First user changes default IME manually.
3847 dpms.notifyChangeToContentObserver(defaultImeUri, UserHandle.USER_SYSTEM);
3848 mContext.binder.clearCallingIdentity();
3849 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3850 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3851 mContext.binder.restoreCallingIdentity(ident);
3852
3853 // Device Owner changes default IME for first user again.
3854 when(mContext.settings.settingsSecureGetStringForUser(defaultIme, UserHandle.USER_SYSTEM))
3855 .thenReturn("ime2");
3856 dpm.setSecureSetting(admin1, defaultIme, "ime3");
3857 verify(mContext.settings).settingsSecurePutStringForUser(defaultIme, "ime3",
3858 UserHandle.USER_SYSTEM);
3859 dpms.notifyChangeToContentObserver(defaultImeUri, UserHandle.USER_SYSTEM);
3860 mContext.binder.clearCallingIdentity();
3861 assertTrue(dpm.isDefaultInputMethodSetByOwner(firstUser));
3862 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3863
3864 // Restarting the DPMS should not lose information.
3865 initializeDpms();
3866 assertTrue(dpm.isDefaultInputMethodSetByOwner(firstUser));
3867 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3868 mContext.binder.restoreCallingIdentity(ident);
3869
3870 // Device Owner can find out whether it set the default IME itself.
3871 assertTrue(dpm.isDefaultInputMethodSetByOwner(firstUser));
3872
3873 // Removing the Device Owner should clear the information that it set the default IME.
3874 clearDeviceOwner();
3875 mContext.binder.clearCallingIdentity();
3876 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3877 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3878 }
3879
3880 public void testIsDefaultInputMethodSetByOwnerForProfileOwner() throws Exception {
3881 final String defaultIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3882 final Uri defaultImeUri = Settings.Secure.getUriFor(defaultIme);
3883 final UserHandle firstUser = UserHandle.SYSTEM;
3884 final UserHandle secondUser = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
3885
3886 // Set up a profile owner.
3887 setupProfileOwner();
3888
3889 // First and second user set default IMEs manually.
3890 final long ident = mContext.binder.clearCallingIdentity();
3891 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3892 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3893 mContext.binder.restoreCallingIdentity(ident);
3894
3895 // Profile Owner changes default IME for second user.
3896 when(mContext.settings.settingsSecureGetStringForUser(defaultIme,
3897 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
3898 dpm.setSecureSetting(admin1, defaultIme, "ime2");
3899 verify(mContext.settings).settingsSecurePutStringForUser(defaultIme, "ime2",
3900 DpmMockContext.CALLER_USER_HANDLE);
3901 reset(mContext.settings);
3902 dpms.notifyChangeToContentObserver(defaultImeUri, DpmMockContext.CALLER_USER_HANDLE);
3903 mContext.binder.clearCallingIdentity();
3904 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3905 assertTrue(dpm.isDefaultInputMethodSetByOwner(secondUser));
3906 mContext.binder.restoreCallingIdentity(ident);
3907
3908 // First user changes default IME manually.
3909 dpms.notifyChangeToContentObserver(defaultImeUri, UserHandle.USER_SYSTEM);
3910 mContext.binder.clearCallingIdentity();
3911 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3912 assertTrue(dpm.isDefaultInputMethodSetByOwner(secondUser));
3913 mContext.binder.restoreCallingIdentity(ident);
3914
3915 // Second user changes default IME manually.
3916 dpms.notifyChangeToContentObserver(defaultImeUri, DpmMockContext.CALLER_USER_HANDLE);
3917 mContext.binder.clearCallingIdentity();
3918 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3919 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3920 mContext.binder.restoreCallingIdentity(ident);
3921
3922 // Profile Owner changes default IME for second user again.
3923 when(mContext.settings.settingsSecureGetStringForUser(defaultIme,
3924 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
3925 dpm.setSecureSetting(admin1, defaultIme, "ime3");
3926 verify(mContext.settings).settingsSecurePutStringForUser(defaultIme, "ime3",
3927 DpmMockContext.CALLER_USER_HANDLE);
3928 dpms.notifyChangeToContentObserver(defaultImeUri, DpmMockContext.CALLER_USER_HANDLE);
3929 mContext.binder.clearCallingIdentity();
3930 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3931 assertTrue(dpm.isDefaultInputMethodSetByOwner(secondUser));
3932
3933 // Restarting the DPMS should not lose information.
3934 initializeDpms();
3935 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3936 assertTrue(dpm.isDefaultInputMethodSetByOwner(secondUser));
3937 mContext.binder.restoreCallingIdentity(ident);
3938
3939 // Profile Owner can find out whether it set the default IME itself.
3940 assertTrue(dpm.isDefaultInputMethodSetByOwner(secondUser));
3941
3942 // Removing the Profile Owner should clear the information that it set the default IME.
3943 dpm.clearProfileOwner(admin1);
3944 mContext.binder.clearCallingIdentity();
3945 assertFalse(dpm.isDefaultInputMethodSetByOwner(firstUser));
3946 assertFalse(dpm.isDefaultInputMethodSetByOwner(secondUser));
3947 }
Rubin Xuaab7a412016-12-30 21:13:29 +00003948
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003949 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
3950 setDeviceOwner();
3951
3952 mContext.packageName = admin1.getPackageName();
3953 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3954 verifyCanGetOwnerInstalledCaCerts(admin1);
3955 }
3956
3957 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
3958 setAsProfileOwner(admin1);
3959
3960 mContext.packageName = admin1.getPackageName();
3961 verifyCanGetOwnerInstalledCaCerts(admin1);
3962 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1);
3963 }
3964
3965 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
3966 setAsProfileOwner(admin1);
3967
3968 final String delegate = "com.example.delegate";
3969 final int delegateUid = setupPackageInPackageManager(delegate, 20988);
3970 dpm.setCertInstallerPackage(admin1, delegate);
3971
3972 mContext.packageName = delegate;
3973 mContext.binder.callingUid = delegateUid;
3974 verifyCanGetOwnerInstalledCaCerts(null);
3975 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null);
3976 }
3977
3978 private void verifyCanGetOwnerInstalledCaCerts(ComponentName caller) throws Exception {
3979 final UserHandle user = UserHandle.getUserHandleForUid(mContext.binder.callingUid);
3980 final int ownerUid = user.equals(UserHandle.SYSTEM) ?
3981 DpmMockContext.CALLER_SYSTEM_USER_UID : DpmMockContext.CALLER_UID;
3982
3983 mContext.applicationInfo = new ApplicationInfo();
3984 mContext.userContexts.put(user, mContext);
3985 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
3986
3987 // Install a CA cert.
3988 final String alias = "cert";
3989 final byte[] caCert = TEST_CA.getBytes();
3990 when(mContext.keyChainConnection.getService().installCaCertificate(caCert))
3991 .thenReturn(alias);
3992 assertTrue(dpm.installCaCert(caller, caCert));
3993 when(mContext.keyChainConnection.getService().getUserCaAliases())
3994 .thenReturn(asSlice(new String[] {alias}));
3995 mContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED));
3996 flushTasks();
3997
3998 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
3999 final String packageName = mContext.packageName;
4000 mContext.packageName = admin1.getPackageName();
4001 final long callerIdentity = mContext.binder.clearCallingIdentity();
4002 mContext.binder.callingUid = ownerUid;
4003 List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(user);
4004 assertNotNull(ownerInstalledCaCerts);
4005 assertEquals(1, ownerInstalledCaCerts.size());
4006 assertTrue(ownerInstalledCaCerts.contains(alias));
4007
4008 // Restarting the DPMS should not lose information.
4009 initializeDpms();
4010 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(user));
4011
4012 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
4013 mContext.packageName = "com.android.frameworks.servicestests";
4014 mContext.binder.clearCallingIdentity();
4015 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(user));
4016
4017 // Remove the CA cert.
4018 mContext.packageName = packageName;
4019 mContext.binder.restoreCallingIdentity(callerIdentity);
4020 reset(mContext.keyChainConnection.getService());
4021 mContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED));
4022 flushTasks();
4023
4024 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4025 // Owner.
4026 mContext.packageName = admin1.getPackageName();
4027 mContext.binder.callingUid = ownerUid;
4028 ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(user);
4029 assertNotNull(ownerInstalledCaCerts);
4030 assertTrue(ownerInstalledCaCerts.isEmpty());
4031
4032 mContext.packageName = packageName;
4033 mContext.binder.restoreCallingIdentity(callerIdentity);
4034 }
4035
4036 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(ComponentName caller)
4037 throws Exception {
4038 final UserHandle user = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4039
4040 mContext.applicationInfo = new ApplicationInfo();
4041 mContext.userContexts.put(user, mContext);
4042 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4043
4044 // Install a CA cert.
4045 final String alias = "cert";
4046 final byte[] caCert = TEST_CA.getBytes();
4047 when(mContext.keyChainConnection.getService().installCaCertificate(caCert))
4048 .thenReturn(alias);
4049 assertTrue(dpm.installCaCert(caller, caCert));
4050 when(mContext.keyChainConnection.getService().getUserCaAliases())
4051 .thenReturn(asSlice(new String[] {alias}));
4052 mContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED));
4053 flushTasks();
4054
4055 // Removing the Profile Owner should clear the information which CA certs were installed
4056 // by it.
4057 mContext.packageName = admin1.getPackageName();
4058 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4059 dpm.clearProfileOwner(admin1);
4060 mContext.packageName = "com.android.frameworks.servicestests";
4061 mContext.binder.clearCallingIdentity();
4062 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(user);
4063 assertNotNull(ownerInstalledCaCerts);
4064 assertTrue(ownerInstalledCaCerts.isEmpty());
4065 }
4066
Victor Chang3e794af2016-03-04 13:48:17 +00004067 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
4068 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
4069 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4070 dpms.notifyChangeToContentObserver(
4071 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4072 }
4073
4074 private void assertProvisioningAllowed(String action, boolean expected) {
4075 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4076 dpm.isProvisioningAllowed(action));
4077 }
Tony Mak2f26b792016-11-28 17:54:51 +00004078
Nicolas Prevot45d29072017-01-18 16:11:19 +00004079 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4080 int uid) {
4081 String previousPackageName = mContext.packageName;
4082 int previousUid = mMockContext.binder.callingUid;
4083
4084 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4085 mContext.packageName = packageName;
4086 mMockContext.binder.callingUid = uid;
4087 assertProvisioningAllowed(action, expected);
4088
4089 // Set the previous package name / calling uid to go back to the initial state.
4090 mContext.packageName = previousPackageName;
4091 mMockContext.binder.callingUid = previousUid;
4092 }
4093
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004094 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004095 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4096 }
4097
4098 private void assertCheckProvisioningPreCondition(
4099 String action, String packageName, int provisioningCondition) {
4100 assertEquals("checkProvisioningPreCondition("
4101 + action + ", " + packageName + ") returning unexpected result",
4102 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004103 }
4104
Tony Mak2f26b792016-11-28 17:54:51 +00004105 /**
4106 * Setup a managed profile with the specified admin and its uid.
4107 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4108 * @param adminUid uid of the admin package.
4109 * @param copyFromAdmin package information for {@code admin} will be built based on this
4110 * component's information.
4111 */
4112 private void addManagedProfile(
4113 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4114 final int userId = UserHandle.getUserId(adminUid);
4115 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
4116 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4117 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4118 dpm.setActiveAdmin(admin, false, userId);
4119 assertTrue(dpm.setProfileOwner(admin, null, userId));
4120 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4121 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004122
4123 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004124 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004125 */
Robin Leeabaa0692017-02-20 20:54:22 +00004126 private static StringParceledListSlice asSlice(String[] s) {
4127 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004128 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004129
4130 private void flushTasks() throws Exception {
4131 Boolean tasksFlushed[] = new Boolean[] {false};
4132 final Runnable tasksFlushedNotifier = () -> {
4133 synchronized (tasksFlushed) {
4134 tasksFlushed[0] = true;
4135 tasksFlushed.notify();
4136 }
4137 };
4138
4139 // Flush main thread handler.
4140 dpms.mHandler.post(tasksFlushedNotifier);
4141 synchronized (tasksFlushed) {
4142 if (!tasksFlushed[0]) {
4143 tasksFlushed.wait();
4144 }
4145 }
4146
4147 // Flush background thread handler.
4148 tasksFlushed[0] = false;
4149 dpms.mBackgroundHandler.post(tasksFlushedNotifier);
4150 synchronized (tasksFlushed) {
4151 if (!tasksFlushed[0]) {
4152 tasksFlushed.wait();
4153 }
4154 }
4155 }
Victor Chang3e794af2016-03-04 13:48:17 +00004156}