blob: 2c85799b0dd05bced29a7a41cdb1dbfa40f0f930 [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 Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
yinxuf4f9cec2017-06-19 10:28:19 -070020import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010021import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
22import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
23import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
24
Pavel Grafova1ea8d92017-05-25 21:55:24 +010025import static com.android.server.testutis.TestUtils.assertExpectException;
26
Pavel Grafov75c0a892017-05-18 17:28:27 +010027import static org.mockito.Matchers.any;
28import static org.mockito.Matchers.anyInt;
29import static org.mockito.Matchers.anyLong;
30import static org.mockito.Matchers.anyObject;
31import static org.mockito.Matchers.anyString;
32import static org.mockito.Matchers.eq;
33import static org.mockito.Matchers.isNull;
34import static org.mockito.Mockito.atLeast;
35import static org.mockito.Mockito.doAnswer;
36import static org.mockito.Mockito.doReturn;
37import static org.mockito.Mockito.never;
38import static org.mockito.Mockito.nullable;
39import static org.mockito.Mockito.reset;
40import static org.mockito.Mockito.timeout;
41import static org.mockito.Mockito.times;
42import static org.mockito.Mockito.verify;
43import static org.mockito.Mockito.verifyZeroInteractions;
44import static org.mockito.Mockito.when;
45import static org.mockito.hamcrest.MockitoHamcrest.argThat;
46
Makoto Onukif76b06a2015-09-22 15:03:44 -070047import android.Manifest.permission;
48import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000049import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070050import android.app.admin.DeviceAdminReceiver;
51import android.app.admin.DevicePolicyManager;
52import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010053import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070054import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070055import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000056import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000057import android.content.pm.ApplicationInfo;
58import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070059import android.content.pm.PackageManager;
Robin Leeabaa0692017-02-20 20:54:22 +000060import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000061import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010062import android.graphics.Color;
63import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080064import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080065import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070066import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080067import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070068import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070069import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010070import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080071import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010072import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000073import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080074import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000075import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010076import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070077import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070078
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010079import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000080import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000081import com.android.server.LocalServices;
82import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000083import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000084
Robin Lee7f5c91c2017-02-08 21:27:02 +000085import org.hamcrest.BaseMatcher;
86import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070087import org.mockito.invocation.InvocationOnMock;
88import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070089
Makoto Onukic8a5a552015-11-19 14:29:12 -080090import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000091import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000092import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070093import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070094import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070095import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010096import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000097import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070099/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700100 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000101 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700102 m FrameworksServicesTests &&
103 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000104 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700105 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800106 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107
108 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000109 *
110 * , or:
111 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700112 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000113@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100114@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000116 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
117 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
118 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100119 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
120 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000121
Pavel Grafov75c0a892017-05-18 17:28:27 +0100122 // TODO replace all instances of this with explicit {@link #mServiceContext}.
123 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100125
126 private DpmMockContext mServiceContext;
127 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700128 public DevicePolicyManager dpm;
129 public DevicePolicyManagerServiceTestable dpms;
130
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100131 /*
132 * The CA cert below is the content of cacert.pem as generated by:
133 *
134 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
135 */
136 private static final String TEST_CA =
137 "-----BEGIN CERTIFICATE-----\n" +
138 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
139 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
140 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
141 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
142 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
143 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
144 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
145 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
146 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
147 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
148 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
149 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
150 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
151 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
152 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
153 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
154 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
155 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
156 "wQ==\n" +
157 "-----END CERTIFICATE-----\n";
158
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700159 @Override
160 protected void setUp() throws Exception {
161 super.setUp();
162
163 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100164 mServiceContext = mContext;
165 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
166 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700167 .thenReturn(true);
168
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800169 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100170 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800171
Makoto Onukia52562c2015-10-01 16:12:31 -0700172 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700173
Makoto Onukid932f762015-09-29 16:53:38 -0700174 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
175 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
176 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800177 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700178
Pavel Grafov75c0a892017-05-18 17:28:27 +0100179 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
180 mAdmin1Context.packageName = admin1.getPackageName();
181 mAdmin1Context.applicationInfo = new ApplicationInfo();
182 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
183
Makoto Onukib643fb02015-09-22 15:03:44 -0700184 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700185 }
186
Robin Lee2c68dad2017-03-17 12:50:24 +0000187 @Override
188 protected void tearDown() throws Exception {
189 flushTasks();
190 super.tearDown();
191 }
192
Makoto Onukia52562c2015-10-01 16:12:31 -0700193 private void initializeDpms() {
194 // Need clearCallingIdentity() to pass permission checks.
195 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100196 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700197
Pavel Grafov75c0a892017-05-18 17:28:27 +0100198 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
199 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
200 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700201
Pavel Grafov75c0a892017-05-18 17:28:27 +0100202 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700203
Pavel Grafov75c0a892017-05-18 17:28:27 +0100204 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700205 }
206
Makoto Onukib643fb02015-09-22 15:03:44 -0700207 private void setUpUserManager() {
208 // Emulate UserManager.set/getApplicationRestriction().
209 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
210
211 // UM.setApplicationRestrictions() will save to appRestrictions.
212 doAnswer(new Answer<Void>() {
213 @Override
214 public Void answer(InvocationOnMock invocation) throws Throwable {
215 String pkg = (String) invocation.getArguments()[0];
216 Bundle bundle = (Bundle) invocation.getArguments()[1];
217 UserHandle user = (UserHandle) invocation.getArguments()[2];
218
219 appRestrictions.put(Pair.create(pkg, user), bundle);
220
221 return null;
222 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100223 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100224 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700225
226 // UM.getApplicationRestrictions() will read from appRestrictions.
227 doAnswer(new Answer<Bundle>() {
228 @Override
229 public Bundle answer(InvocationOnMock invocation) throws Throwable {
230 String pkg = (String) invocation.getArguments()[0];
231 UserHandle user = (UserHandle) invocation.getArguments()[1];
232
233 return appRestrictions.get(Pair.create(pkg, user));
234 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100235 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700236 anyString(), any(UserHandle.class));
237
Makoto Onukid932f762015-09-29 16:53:38 -0700238 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100239 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700240 }
241
242 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100243 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700244
Pavel Grafov75c0a892017-05-18 17:28:27 +0100245 mServiceContext.binder.callingUid =
246 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
247 runAsCaller(mServiceContext, dpms, dpm -> {
248 // PO needs to be a DA.
249 dpm.setActiveAdmin(admin, /*replace=*/ false);
250 // Fire!
251 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
252 // Check
253 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
254 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700255
Pavel Grafov75c0a892017-05-18 17:28:27 +0100256 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700257 }
258
259 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100260 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700261 .thenReturn(false);
262
263 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100264 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700265
266 // If the device has no DPMS feature, it shouldn't register the local service.
267 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
268 }
269
270 /**
271 * Caller doesn't have proper permissions.
272 */
273 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700274 // 1. Failure cases.
275
276 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100277 assertExpectException(SecurityException.class, /* messageRegex= */ null,
278 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700279
280 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
281 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100282
283 assertExpectException(SecurityException.class, /* messageRegex= */ null,
284 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700285 }
286
Makoto Onukif76b06a2015-09-22 15:03:44 -0700287 /**
288 * Test for:
289 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800290 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700291 * {@link DevicePolicyManager#isAdminActive}
292 * {@link DevicePolicyManager#isAdminActiveAsUser}
293 * {@link DevicePolicyManager#getActiveAdmins}
294 * {@link DevicePolicyManager#getActiveAdminsAsUser}
295 */
296 public void testSetActiveAdmin() throws Exception {
297 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700298 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
299
Makoto Onukif76b06a2015-09-22 15:03:44 -0700300 // 2. Call the API.
301 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700302
303 // 3. Verify internal calls.
304
305 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700306 verify(mContext.spiedContext).sendBroadcastAsUser(
307 MockUtils.checkIntentAction(
308 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
309 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
310 verify(mContext.spiedContext).sendBroadcastAsUser(
311 MockUtils.checkIntentAction(
312 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700313 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
314
Pavel Grafov75c0a892017-05-18 17:28:27 +0100315 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700316 eq(admin1.getPackageName()),
317 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
318 eq(PackageManager.DONT_KILL_APP),
319 eq(DpmMockContext.CALLER_USER_HANDLE),
320 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700321
322 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700323
324 // Make sure it's active admin1.
325 assertTrue(dpm.isAdminActive(admin1));
326 assertFalse(dpm.isAdminActive(admin2));
327 assertFalse(dpm.isAdminActive(admin3));
328
329 // But not admin1 for a different user.
330
331 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
332 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
333 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
334
335 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
336 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
337
338 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
339
340 // Next, add one more admin.
341 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700342 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
343 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700344
345 dpm.setActiveAdmin(admin2, /* replace =*/ false);
346
347 // Now we have two admins.
348 assertTrue(dpm.isAdminActive(admin1));
349 assertTrue(dpm.isAdminActive(admin2));
350 assertFalse(dpm.isAdminActive(admin3));
351
352 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
353 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100354 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700355 eq(admin1.getPackageName()),
356 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
357 eq(PackageManager.DONT_KILL_APP),
358 eq(DpmMockContext.CALLER_USER_HANDLE),
359 anyString());
360
361 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100362 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
363 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700364
365 // 5. Add the same admin1 again with replace, which should succeed.
366 dpm.setActiveAdmin(admin1, /* replace =*/ true);
367
368 // TODO make sure it's replaced.
369
370 // 6. Test getActiveAdmins()
371 List<ComponentName> admins = dpm.getActiveAdmins();
372 assertEquals(2, admins.size());
373 assertEquals(admin1, admins.get(0));
374 assertEquals(admin2, admins.get(1));
375
376 // Another user has no admins.
377 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
378
379 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
380 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
381
382 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
383 }
384
Makoto Onukid932f762015-09-29 16:53:38 -0700385 public void testSetActiveAdmin_multiUsers() throws Exception {
386
387 final int ANOTHER_USER_ID = 100;
388 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
389
Pavel Grafov75c0a892017-05-18 17:28:27 +0100390 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700391
392 // Set up pacakge manager for the other user.
393 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700394
395 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
396
397 dpm.setActiveAdmin(admin1, /* replace =*/ false);
398
399 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
400 dpm.setActiveAdmin(admin2, /* replace =*/ false);
401
402
403 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
404 assertTrue(dpm.isAdminActive(admin1));
405 assertFalse(dpm.isAdminActive(admin2));
406
407 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
408 assertFalse(dpm.isAdminActive(admin1));
409 assertTrue(dpm.isAdminActive(admin2));
410 }
411
Makoto Onukif76b06a2015-09-22 15:03:44 -0700412 /**
413 * Test for:
414 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800415 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700416 */
417 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
418 // 1. Make sure the caller has proper permissions.
419 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
420
421 dpm.setActiveAdmin(admin1, /* replace =*/ false);
422 assertTrue(dpm.isAdminActive(admin1));
423
424 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100425 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
426 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700427 }
428
429 /**
430 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800431 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
432 * BIND_DEVICE_ADMIN.
433 */
434 public void testSetActiveAdmin_permissionCheck() throws Exception {
435 // 1. Make sure the caller has proper permissions.
436 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
437
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100438 assertExpectException(IllegalArgumentException.class,
439 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
440 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800441 assertFalse(dpm.isAdminActive(adminNoPerm));
442
443 // Change the target API level to MNC. Now it can be set as DA.
444 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
445 VERSION_CODES.M);
446 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
447 assertTrue(dpm.isAdminActive(adminNoPerm));
448
449 // TODO Test the "load from the file" case where DA will still be loaded even without
450 // BIND_DEVICE_ADMIN and target API is N.
451 }
452
453 /**
454 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700455 * {@link DevicePolicyManager#removeActiveAdmin}
456 */
457 public void testRemoveActiveAdmin_SecurityException() {
458 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
459
460 // Add admin.
461
462 dpm.setActiveAdmin(admin1, /* replace =*/ false);
463
464 assertTrue(dpm.isAdminActive(admin1));
465
466 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
467
468 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100469 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
470 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700471
472 // Try to remove active admin with a different caller userid should fail too, without
473 // having MANAGE_DEVICE_ADMINS.
474 mContext.callerPermissions.clear();
475
Makoto Onukid932f762015-09-29 16:53:38 -0700476 // Change the caller, and call into DPMS directly with a different user-id.
477
Makoto Onukif76b06a2015-09-22 15:03:44 -0700478 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100479 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
480 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700481 }
482
483 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800484 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
485 * (because we can't send the remove broadcast).
486 */
487 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
488 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
489
490 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
491
492 // Add admin.
493
494 dpm.setActiveAdmin(admin1, /* replace =*/ false);
495
496 assertTrue(dpm.isAdminActive(admin1));
497
498 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
499
500 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100501 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800502 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100503 assertExpectException(IllegalStateException.class,
504 /* messageRegex= */ "User must be running and unlocked",
505 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800506
507 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
508
509 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100510 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800511 .thenReturn(true);
512
513 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700514 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800515 }
516
517 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700518 * Test for:
519 * {@link DevicePolicyManager#removeActiveAdmin}
520 */
Makoto Onukid932f762015-09-29 16:53:38 -0700521 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700522 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
523
524 // Add admin1.
525
526 dpm.setActiveAdmin(admin1, /* replace =*/ false);
527
528 assertTrue(dpm.isAdminActive(admin1));
529 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
530
531 // Different user, but should work, because caller has proper permissions.
532 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700533
534 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700535 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700536
537 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700538 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700539
540 // TODO DO Still can't be removed in this case.
541 }
542
543 /**
544 * Test for:
545 * {@link DevicePolicyManager#removeActiveAdmin}
546 */
547 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
548 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
549 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
550
551 // Add admin1.
552
553 dpm.setActiveAdmin(admin1, /* replace =*/ false);
554
555 assertTrue(dpm.isAdminActive(admin1));
556 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
557
558 // Broadcast from saveSettingsLocked().
559 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
560 MockUtils.checkIntentAction(
561 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
562 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
563
564 // Remove. No permissions, but same user, so it'll work.
565 mContext.callerPermissions.clear();
566 dpm.removeActiveAdmin(admin1);
567
Makoto Onukif76b06a2015-09-22 15:03:44 -0700568 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
569 MockUtils.checkIntentAction(
570 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
571 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
572 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700573 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700574 eq(dpms.mHandler),
575 eq(Activity.RESULT_OK),
576 isNull(String.class),
577 isNull(Bundle.class));
578
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700579 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700580
581 // Again broadcast from saveSettingsLocked().
582 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
583 MockUtils.checkIntentAction(
584 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
585 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
586
587 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700588 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700589
590 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000591 * Test for: @{link DevicePolicyManager#setActivePasswordState}
592 *
593 * Validates that when the password for a user changes, the notification broadcast intent
594 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
595 * addition to ones in the original user.
596 */
597 public void testSetActivePasswordState_sendToProfiles() throws Exception {
598 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
599
600 final int MANAGED_PROFILE_USER_ID = 78;
601 final int MANAGED_PROFILE_ADMIN_UID =
602 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
603
604 // Setup device owner.
605 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
606 mContext.packageName = admin1.getPackageName();
607 setupDeviceOwner();
608
609 // Add a managed profile belonging to the system user.
610 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
611
612 // Change the parent user's password.
613 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
614
615 // Both the device owner and the managed profile owner should receive this broadcast.
616 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
617 intent.setComponent(admin1);
618 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
619
620 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
621 MockUtils.checkIntent(intent),
622 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
623 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
624 MockUtils.checkIntent(intent),
625 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
626 }
627
628 /**
629 * Test for: @{link DevicePolicyManager#setActivePasswordState}
630 *
631 * Validates that when the password for a managed profile changes, the notification broadcast
632 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
633 * its parent.
634 */
635 public void testSetActivePasswordState_notSentToParent() throws Exception {
636 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
637
638 final int MANAGED_PROFILE_USER_ID = 78;
639 final int MANAGED_PROFILE_ADMIN_UID =
640 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
641
642 // Setup device owner.
643 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
644 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100645 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000646 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
647 setupDeviceOwner();
648
649 // Add a managed profile belonging to the system user.
650 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
651
652 // Change the profile's password.
653 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
654
655 // Both the device owner and the managed profile owner should receive this broadcast.
656 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
657 intent.setComponent(admin1);
658 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
659
660 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
661 MockUtils.checkIntent(intent),
662 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
663 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
664 MockUtils.checkIntent(intent),
665 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
666 }
667 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000668 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700669 */
670 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000671 setDeviceOwner();
672
673 // Try to set a profile owner on the same user, which should fail.
674 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
675 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100676 assertExpectException(IllegalStateException.class,
677 /* messageRegex= */ "already has a device owner",
678 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000679
680 // DO admin can't be deactivated.
681 dpm.removeActiveAdmin(admin1);
682 assertTrue(dpm.isAdminActive(admin1));
683
684 // TODO Test getDeviceOwnerName() too. To do so, we need to change
685 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
686 }
687
688 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700689 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800690 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700691 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
692 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
693
Makoto Onukid932f762015-09-29 16:53:38 -0700694 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700695 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
696
Makoto Onukid932f762015-09-29 16:53:38 -0700697 // Make sure admin1 is installed on system user.
698 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700699
Makoto Onukic8a5a552015-11-19 14:29:12 -0800700 // Check various get APIs.
701 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
702
Makoto Onukib643fb02015-09-22 15:03:44 -0700703 // DO needs to be an DA.
704 dpm.setActiveAdmin(admin1, /* replace =*/ false);
705
706 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700707 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700708
Makoto Onukic8a5a552015-11-19 14:29:12 -0800709 // getDeviceOwnerComponent should return the admin1 component.
710 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
711 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
712
713 // Check various get APIs.
714 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
715
716 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
717 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
718 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
719 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
720
721 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
722
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000723 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100724 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000725 eq(admin1.getPackageName()));
726
Makoto Onukib643fb02015-09-22 15:03:44 -0700727 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100728 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700729 eq(UserHandle.USER_SYSTEM), eq(false));
730
731 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
732 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
733 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
734
Makoto Onukic8a5a552015-11-19 14:29:12 -0800735 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700736 }
737
Makoto Onukic8a5a552015-11-19 14:29:12 -0800738 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
739 final int origCallingUser = mContext.binder.callingUid;
740 final List origPermissions = new ArrayList(mContext.callerPermissions);
741 mContext.callerPermissions.clear();
742
743 mContext.callerPermissions.add(permission.MANAGE_USERS);
744
745 mContext.binder.callingUid = Process.SYSTEM_UID;
746
747 // TODO Test getDeviceOwnerName() too. To do so, we need to change
748 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
749 if (hasDeviceOwner) {
750 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
751 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
752 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
753
754 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
755 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
756 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
757 } else {
758 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
759 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
760 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
761
762 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
763 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
764 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
765 }
766
767 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
768 if (hasDeviceOwner) {
769 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
770 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
771 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
772
773 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
774 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
775 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
776 } else {
777 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
778 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
779 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
780
781 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
782 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
783 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
784 }
785
786 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
787 // Still with MANAGE_USERS.
788 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
789 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
790 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
791
792 if (hasDeviceOwner) {
793 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
794 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
795 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
796 } else {
797 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
798 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
799 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
800 }
801
802 mContext.binder.callingUid = Process.SYSTEM_UID;
803 mContext.callerPermissions.remove(permission.MANAGE_USERS);
804 // System can still call "OnAnyUser" without MANAGE_USERS.
805 if (hasDeviceOwner) {
806 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
807 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
808 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
809
810 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
811 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
812 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
813 } else {
814 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
815 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
816 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
817
818 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
819 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
820 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
821 }
822
823 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
824 // Still no MANAGE_USERS.
825 if (hasDeviceOwner) {
826 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
827 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
828 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
829 } else {
830 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
831 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
832 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
833 }
834
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100835 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
836 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
837 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
838 dpm::getDeviceOwnerComponentOnAnyUser);
839 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
840 dpm::getDeviceOwnerUserId);
841 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
842 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800843
844 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
845 // Still no MANAGE_USERS.
846 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
847 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
848 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
849
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100850 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
851 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
852 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
853 dpm::getDeviceOwnerComponentOnAnyUser);
854 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
855 dpm::getDeviceOwnerUserId);
856 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
857 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800858
859 // Restore.
860 mContext.binder.callingUid = origCallingUser;
861 mContext.callerPermissions.addAll(origPermissions);
862 }
863
864
Makoto Onukib643fb02015-09-22 15:03:44 -0700865 /**
866 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
867 */
868 public void testSetDeviceOwner_noSuchPackage() {
869 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800870 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700871 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
872 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
873
874 // Call from a process on the system user.
875 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
876
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100877 assertExpectException(IllegalArgumentException.class,
878 /* messageRegex= */ "Invalid component",
879 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -0700880 }
881
882 public void testSetDeviceOwner_failures() throws Exception {
883 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
884 }
885
Makoto Onukia52562c2015-10-01 16:12:31 -0700886 public void testClearDeviceOwner() throws Exception {
887 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800888 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700889 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
890 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
891
892 // Set admin1 as a DA to the secondary user.
893 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
894
895 dpm.setActiveAdmin(admin1, /* replace =*/ false);
896
897 // Set admin 1 as the DO to the system user.
898
899 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
900 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
901 dpm.setActiveAdmin(admin1, /* replace =*/ false);
902 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
903
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000904 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100905 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000906 eq(admin1.getPackageName()));
907
Makoto Onukic8a5a552015-11-19 14:29:12 -0800908 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700909
Makoto Onuki90b89652016-01-28 14:44:18 -0800910 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100911 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000912 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800913
914 assertTrue(dpm.isAdminActive(admin1));
915 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
916
Makoto Onukia52562c2015-10-01 16:12:31 -0700917 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100918 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -0700919
920 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100921 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
922 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800923
924 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100925 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100926 assertExpectException(IllegalStateException.class,
927 /* messageRegex= */ "User must be running and unlocked",
928 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800929
Pavel Grafov75c0a892017-05-18 17:28:27 +0100930 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
931 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700932 dpm.clearDeviceOwnerApp(admin1.getPackageName());
933
934 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800935 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700936
Pavel Grafov75c0a892017-05-18 17:28:27 +0100937 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000938 eq(false),
939 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
940
Pavel Grafov75c0a892017-05-18 17:28:27 +0100941 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -0800942 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100943 eq(null),
944 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800945
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700946 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100947
948 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
949 // and once for clearing it.
950 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
951 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
952 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700953 // TODO Check other calls.
954 }
955
956 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
957 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800958 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700959 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
960 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
961
962 // Set admin1 as a DA to the secondary user.
963 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
964
965 dpm.setActiveAdmin(admin1, /* replace =*/ false);
966
967 // Set admin 1 as the DO to the system user.
968
969 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
970 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
971 dpm.setActiveAdmin(admin1, /* replace =*/ false);
972 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
973
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000974 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100975 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000976 eq(admin1.getPackageName()));
977
Makoto Onukic8a5a552015-11-19 14:29:12 -0800978 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700979
980 // Now call clear from the secondary user, which should throw.
981 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
982
983 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100984 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700985 eq(admin1.getPackageName()),
986 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100987 assertExpectException(SecurityException.class,
988 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
989 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -0700990
Makoto Onukic8a5a552015-11-19 14:29:12 -0800991 // DO shouldn't be removed.
992 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700993 }
994
Makoto Onukib643fb02015-09-22 15:03:44 -0700995 public void testSetProfileOwner() throws Exception {
996 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700997
Makoto Onuki90b89652016-01-28 14:44:18 -0800998 // PO admin can't be deactivated.
999 dpm.removeActiveAdmin(admin1);
1000 assertTrue(dpm.isAdminActive(admin1));
1001
Makoto Onuki803d6752015-10-30 12:58:39 -07001002 // Try setting DO on the same user, which should fail.
1003 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001004 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1005 runAsCaller(mServiceContext, dpms, dpm -> {
1006 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001007 assertExpectException(IllegalStateException.class,
1008 /* messageRegex= */ "already has a profile owner",
1009 () -> dpm.setDeviceOwner(admin2, "owner-name",
1010 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001011 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001012 }
1013
Makoto Onuki90b89652016-01-28 14:44:18 -08001014 public void testClearProfileOwner() throws Exception {
1015 setAsProfileOwner(admin1);
1016
1017 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1018
1019 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1020 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1021
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001022 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001023 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001024 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001025 assertExpectException(IllegalStateException.class,
1026 /* messageRegex= */ "User must be running and unlocked",
1027 () -> dpm.clearProfileOwner(admin1));
1028
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001029 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001030 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001031 dpm.clearProfileOwner(admin1);
1032
1033 // Check
1034 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001035 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001036 }
1037
Makoto Onukib643fb02015-09-22 15:03:44 -07001038 public void testSetProfileOwner_failures() throws Exception {
1039 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1040 }
1041
Makoto Onukia52562c2015-10-01 16:12:31 -07001042 public void testGetDeviceOwnerAdminLocked() throws Exception {
1043 checkDeviceOwnerWithMultipleDeviceAdmins();
1044 }
1045
1046 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1047 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1048 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1049 // make sure it gets the right component from the right user.
1050
1051 final int ANOTHER_USER_ID = 100;
1052 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1053
Pavel Grafov75c0a892017-05-18 17:28:27 +01001054 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001055
1056 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001057 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001058 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1059 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1060
1061 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1062
Pavel Grafov75c0a892017-05-18 17:28:27 +01001063 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001064
Makoto Onukia52562c2015-10-01 16:12:31 -07001065 // Make sure the admin packge is installed to each user.
1066 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1067 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1068
1069 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1070 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1071
1072 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1073
1074
1075 // Set active admins to the users.
1076 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1077 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1078
1079 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1080 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1081
1082 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1083
1084 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001085 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001086 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1087
Makoto Onukic8a5a552015-11-19 14:29:12 -08001088 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001089
1090 // Then check getDeviceOwnerAdminLocked().
1091 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1092 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1093 }
1094
1095 /**
1096 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001097 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1098 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001099 *
1100 * We didn't use to persist the DO component class name, but now we do, and the above method
1101 * finds the right component from a package name upon migration.
1102 */
1103 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001104 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001105 checkDeviceOwnerWithMultipleDeviceAdmins();
1106
1107 // Overwrite the device owner setting and clears the clas name.
1108 dpms.mOwners.setDeviceOwner(
1109 new ComponentName(admin2.getPackageName(), ""),
1110 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1111 dpms.mOwners.writeDeviceOwner();
1112
1113 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001114 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001115
1116 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001117 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001118 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001119 initializeDpms();
1120
1121 // Now the DO component name is a full name.
1122 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1123 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001124 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001125 }
1126
Makoto Onukib643fb02015-09-22 15:03:44 -07001127 public void testSetGetApplicationRestriction() {
1128 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001129 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001130
1131 {
1132 Bundle rest = new Bundle();
1133 rest.putString("KEY_STRING", "Foo1");
1134 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1135 }
1136
1137 {
1138 Bundle rest = new Bundle();
1139 rest.putString("KEY_STRING", "Foo2");
1140 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1141 }
1142
1143 {
1144 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1145 assertNotNull(returned);
1146 assertEquals(returned.size(), 1);
1147 assertEquals(returned.get("KEY_STRING"), "Foo1");
1148 }
1149
1150 {
1151 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1152 assertNotNull(returned);
1153 assertEquals(returned.size(), 1);
1154 assertEquals(returned.get("KEY_STRING"), "Foo2");
1155 }
1156
1157 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1158 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1159 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001160
Edman Anjosf9946772016-11-28 16:35:15 +01001161 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001162 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1163 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001164 *
1165 * @param packageName the name of the package to be setup
1166 * @param appId the application ID to be given to the package
1167 * @return the UID of the package as known by the mock package manager
1168 */
1169 private int setupPackageInPackageManager(final String packageName, final int appId)
1170 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001171 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001172 ApplicationInfo.FLAG_HAS_CODE);
1173 }
1174
1175 /**
1176 * Setup a package in the package manager mock. Useful for faking installed applications.
1177 *
1178 * @param packageName the name of the package to be setup
1179 * @param userId the user id where the package will be "installed"
1180 * @param appId the application ID to be given to the package
1181 * @param flags flags to set in the ApplicationInfo for this package
1182 * @return the UID of the package as known by the mock package manager
1183 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001184 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1185 int flags) throws Exception {
1186 final int uid = UserHandle.getUid(userId, appId);
1187 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001188 final PackageInfo pi = new PackageInfo();
1189 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001190 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001191 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001192 eq(packageName),
1193 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001194 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001195 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001196 eq(packageName),
1197 anyInt(),
1198 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001199 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001200 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001201 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001202 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001203 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001204 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001205 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001206 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001207 return uid;
1208 }
1209
Robin Lee7f5c91c2017-02-08 21:27:02 +00001210 public void testCertificateDisclosure() throws Exception {
1211 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1212 final UserHandle user = UserHandle.of(userId);
1213
1214 mContext.applicationInfo = new ApplicationInfo();
1215 mContext.callerPermissions.add(permission.MANAGE_USERS);
1216 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001217 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001218 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1219
Robin Leeabaa0692017-02-20 20:54:22 +00001220 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1221 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001222
1223 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1224 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1225
1226 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001227 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001228 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001229 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001230 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001231 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001232 .cancelAsUser(anyString(), anyInt(), eq(user));
1233
1234 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001235 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001236 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001237 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1238 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001239 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001240 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001241 .notifyAsUser(anyString(), anyInt(), argThat(
1242 new BaseMatcher<Notification>() {
1243 @Override
1244 public boolean matches(Object item) {
1245 final Notification noti = (Notification) item;
1246 return TEST_STRING.equals(
1247 noti.extras.getString(Notification.EXTRA_TITLE));
1248 }
1249 @Override
1250 public void describeTo(Description description) {
1251 description.appendText(
1252 "Notification{title=\"" + TEST_STRING + "\"}");
1253 }
1254 }), eq(user));
1255 }
1256
Edman Anjosf9946772016-11-28 16:35:15 +01001257 /**
1258 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1259 * privileges can acually be exercised by a delegate are not covered here.
1260 */
1261 public void testDelegation() throws Exception {
1262 setAsProfileOwner(admin1);
1263
1264 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1265
1266 // Given two packages
1267 final String CERT_DELEGATE = "com.delegate.certs";
1268 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1269 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1270 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1271 20989);
1272
1273 // On delegation
1274 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1275 mContext.packageName = admin1.getPackageName();
1276 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1277 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1278
1279 // DPMS correctly stores and retrieves the delegates
1280 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1281 assertEquals(2, policy.mDelegationMap.size());
1282 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1283 DELEGATION_CERT_INSTALL);
1284 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1285 DELEGATION_CERT_INSTALL);
1286 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1287 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1288 DELEGATION_APP_RESTRICTIONS);
1289 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1290 DELEGATION_APP_RESTRICTIONS);
1291 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1292
1293 // On calling install certificate APIs from an unauthorized process
1294 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1295 mContext.packageName = RESTRICTIONS_DELEGATE;
1296
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001297 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1298 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001299
1300 // On calling install certificate APIs from an authorized process
1301 mContext.binder.callingUid = CERT_DELEGATE_UID;
1302 mContext.packageName = CERT_DELEGATE;
1303
1304 // DPMS executes without a SecurityException
1305 try {
1306 dpm.installCaCert(null, null);
1307 } catch (SecurityException unexpected) {
1308 fail("Threw SecurityException on authorized access");
1309 } catch (NullPointerException expected) {
1310 }
1311
1312 // On removing a delegate
1313 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1314 mContext.packageName = admin1.getPackageName();
1315 dpm.setCertInstallerPackage(admin1, null);
1316
1317 // DPMS does not allow access to ex-delegate
1318 mContext.binder.callingUid = CERT_DELEGATE_UID;
1319 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001320 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1321 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001322
1323 // But still allows access to other existing delegates
1324 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1325 mContext.packageName = RESTRICTIONS_DELEGATE;
1326 try {
1327 dpm.getApplicationRestrictions(null, "pkg");
1328 } catch (SecurityException expected) {
1329 fail("Threw SecurityException on authorized access");
1330 }
1331 }
1332
Esteban Talaverabf60f722015-12-10 16:26:44 +00001333 public void testApplicationRestrictionsManagingApp() throws Exception {
1334 setAsProfileOwner(admin1);
1335
Rubin Xued1928a2016-02-11 17:23:06 +00001336 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001337 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001338 final String nonDelegateExceptionMessageRegex =
1339 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001340 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001341 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1342 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001343
Esteban Talaverabf60f722015-12-10 16:26:44 +00001344 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1345 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001346 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1347 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001348 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001349 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001350 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001351 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1352 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001353
1354 // Check via the profile owner that no restrictions were set.
1355 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001356 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001357 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1358
Rubin Xued1928a2016-02-11 17:23:06 +00001359 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001360 assertExpectException(PackageManager.NameNotFoundException.class,
1361 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1362 () -> dpm.setApplicationRestrictionsManagingPackage(
1363 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001364
Esteban Talaverabf60f722015-12-10 16:26:44 +00001365 // Let appRestrictionsManagerPackage manage app restrictions
1366 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1367 assertEquals(appRestrictionsManagerPackage,
1368 dpm.getApplicationRestrictionsManagingPackage(admin1));
1369
1370 // Now that package should be able to set and retrieve app restrictions.
1371 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001372 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001373 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1374 dpm.setApplicationRestrictions(null, "pkg1", rest);
1375 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1376 assertEquals(1, returned.size(), 1);
1377 assertEquals("Foo1", returned.get("KEY_STRING"));
1378
1379 // The same app running on a separate user shouldn't be able to manage app restrictions.
1380 mContext.binder.callingUid = UserHandle.getUid(
1381 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1382 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001383 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1384 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001385
1386 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1387 // too.
1388 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001389 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001390 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1391 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1392 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1393
1394 // Removing the ability for the package to manage app restrictions.
1395 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1396 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1397 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001398 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001399 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001400 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1401 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001402 }
1403
Makoto Onukia4f11972015-10-01 13:19:58 -07001404 public void testSetUserRestriction_asDo() throws Exception {
1405 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001406 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001407 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1408 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1409
1410 // First, set DO.
1411
1412 // Call from a process on the system user.
1413 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1414
1415 // Make sure admin1 is installed on system user.
1416 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001417
1418 // Call.
1419 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001420 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001421 UserHandle.USER_SYSTEM));
1422
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001423 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001424 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001425 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001426 DpmTestUtils.assertRestrictions(
1427 DpmTestUtils.newRestrictions(defaultRestrictions),
1428 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1429 );
1430 DpmTestUtils.assertRestrictions(
1431 DpmTestUtils.newRestrictions(defaultRestrictions),
1432 dpm.getUserRestrictions(admin1)
1433 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001434 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001435 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001436 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001437 eq(true) /* isDeviceOwner */,
1438 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001439 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001440 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001441
1442 for (String restriction : defaultRestrictions) {
1443 dpm.clearUserRestriction(admin1, restriction);
1444 }
1445
Esteban Talavera548a04b2016-12-20 15:22:30 +00001446 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001447 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448
1449 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001450 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001451 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001452 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1453 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001454 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001455
Makoto Onukia4f11972015-10-01 13:19:58 -07001456 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001457 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001458 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001459 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1460 UserManager.DISALLOW_ADD_USER),
1461 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001462 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001463
Makoto Onuki068c54a2015-10-13 14:34:03 -07001464 DpmTestUtils.assertRestrictions(
1465 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001466 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001467 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1468 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001469 DpmTestUtils.assertRestrictions(
1470 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001471 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001472 dpm.getUserRestrictions(admin1)
1473 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001474
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001475 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001476 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001477 eq(UserHandle.USER_SYSTEM),
1478 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001479 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001480 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001481
Makoto Onuki068c54a2015-10-13 14:34:03 -07001482 DpmTestUtils.assertRestrictions(
1483 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1484 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1485 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001486 DpmTestUtils.assertRestrictions(
1487 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1488 dpm.getUserRestrictions(admin1)
1489 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001490
1491 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001492 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001493 eq(UserHandle.USER_SYSTEM),
1494 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001495 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001496 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001497
Esteban Talavera548a04b2016-12-20 15:22:30 +00001498 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001499
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001500 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1501 // DO sets them, the scope is global.
1502 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001503 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001504 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001505 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001506 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001507 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001508 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1509 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001510 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001511
1512 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1513 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001514 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001515
1516 // More tests.
1517 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001518 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001519 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001520 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1521 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001522 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001523
1524 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001525 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001526 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001527 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001528 UserManager.DISALLOW_ADD_USER),
1529 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001530 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001531
1532 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001533 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001534 eq(UserHandle.USER_SYSTEM),
1535 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001536 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001537 UserManager.DISALLOW_ADD_USER),
1538 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001539 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001540
1541 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1542 // locally.
1543 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001544 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001545
1546 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1547 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1548 dpm.setCameraDisabled(admin2, true);
1549
Pavel Grafov75c0a892017-05-18 17:28:27 +01001550 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001551 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001552 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001553 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001554 UserManager.DISALLOW_ADD_USER),
1555 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001556 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001557 // TODO Make sure restrictions are written to the file.
1558 }
1559
1560 public void testSetUserRestriction_asPo() {
1561 setAsProfileOwner(admin1);
1562
Makoto Onuki068c54a2015-10-13 14:34:03 -07001563 DpmTestUtils.assertRestrictions(
1564 DpmTestUtils.newRestrictions(),
1565 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1566 .ensureUserRestrictions()
1567 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001568
1569 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001570 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001571 eq(DpmMockContext.CALLER_USER_HANDLE),
1572 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001573 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001574 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001575
Makoto Onukia4f11972015-10-01 13:19:58 -07001576 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001577 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001578 eq(DpmMockContext.CALLER_USER_HANDLE),
1579 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1580 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001581 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001582 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001583
Makoto Onuki068c54a2015-10-13 14:34:03 -07001584 DpmTestUtils.assertRestrictions(
1585 DpmTestUtils.newRestrictions(
1586 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1587 UserManager.DISALLOW_OUTGOING_CALLS
1588 ),
1589 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1590 .ensureUserRestrictions()
1591 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001592 DpmTestUtils.assertRestrictions(
1593 DpmTestUtils.newRestrictions(
1594 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1595 UserManager.DISALLOW_OUTGOING_CALLS
1596 ),
1597 dpm.getUserRestrictions(admin1)
1598 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001599
1600 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001601 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001602 eq(DpmMockContext.CALLER_USER_HANDLE),
1603 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001604 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001605 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001606
1607 DpmTestUtils.assertRestrictions(
1608 DpmTestUtils.newRestrictions(
1609 UserManager.DISALLOW_OUTGOING_CALLS
1610 ),
1611 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1612 .ensureUserRestrictions()
1613 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001614 DpmTestUtils.assertRestrictions(
1615 DpmTestUtils.newRestrictions(
1616 UserManager.DISALLOW_OUTGOING_CALLS
1617 ),
1618 dpm.getUserRestrictions(admin1)
1619 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001620
1621 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001622 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001623 eq(DpmMockContext.CALLER_USER_HANDLE),
1624 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001625 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001626 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001627
Makoto Onuki068c54a2015-10-13 14:34:03 -07001628 DpmTestUtils.assertRestrictions(
1629 DpmTestUtils.newRestrictions(),
1630 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1631 .ensureUserRestrictions()
1632 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001633 DpmTestUtils.assertRestrictions(
1634 DpmTestUtils.newRestrictions(),
1635 dpm.getUserRestrictions(admin1)
1636 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001637
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001638 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1639 // though when DO sets them they'll be applied globally.
1640 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001641 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001642 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001643 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001644 eq(DpmMockContext.CALLER_USER_HANDLE),
1645 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1646 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001647 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001648 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649
1650 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001651 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001652 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001653 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001654 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001655 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001656 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001657
Makoto Onukia4f11972015-10-01 13:19:58 -07001658 // TODO Make sure restrictions are written to the file.
1659 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001660
Esteban Talavera548a04b2016-12-20 15:22:30 +00001661
1662 public void testDefaultEnabledUserRestrictions() throws Exception {
1663 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1664 mContext.callerPermissions.add(permission.MANAGE_USERS);
1665 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1666 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1667
1668 // First, set DO.
1669
1670 // Call from a process on the system user.
1671 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1672
1673 // Make sure admin1 is installed on system user.
1674 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1675
1676 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1677 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1678 UserHandle.USER_SYSTEM));
1679
1680 // Check that the user restrictions that are enabled by default are set. Then unset them.
1681 String[] defaultRestrictions = UserRestrictionsUtils
1682 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1683 assertTrue(defaultRestrictions.length > 0);
1684 DpmTestUtils.assertRestrictions(
1685 DpmTestUtils.newRestrictions(defaultRestrictions),
1686 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1687 );
1688 DpmTestUtils.assertRestrictions(
1689 DpmTestUtils.newRestrictions(defaultRestrictions),
1690 dpm.getUserRestrictions(admin1)
1691 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001692 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001693 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001694 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001695 eq(true) /* isDeviceOwner */,
1696 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001697 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001698 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001699
1700 for (String restriction : defaultRestrictions) {
1701 dpm.clearUserRestriction(admin1, restriction);
1702 }
1703
1704 assertNoDeviceOwnerRestrictions();
1705
1706 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001707 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001708 initializeDpms();
1709 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1710 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1711
1712 assertNoDeviceOwnerRestrictions();
1713
1714 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1715 // is set as it wasn't enabled during setDeviceOwner.
1716 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1717 assertFalse(UserRestrictionsUtils
1718 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1719 UserRestrictionsUtils
1720 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1721 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001722 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001723 initializeDpms();
1724 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1725 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1726
1727 DpmTestUtils.assertRestrictions(
1728 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1729 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1730 );
1731 DpmTestUtils.assertRestrictions(
1732 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1733 dpm.getUserRestrictions(admin1)
1734 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001735 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001736 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001737 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001738 eq(true) /* isDeviceOwner */,
1739 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001740 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001741 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001742
1743 // Remove the restriction.
1744 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1745
1746 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1747 initializeDpms();
1748 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1749 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1750 assertNoDeviceOwnerRestrictions();
1751 } finally {
1752 UserRestrictionsUtils
1753 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1754 }
1755 }
1756
1757 private void assertNoDeviceOwnerRestrictions() {
1758 DpmTestUtils.assertRestrictions(
1759 DpmTestUtils.newRestrictions(),
1760 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1761 );
1762 DpmTestUtils.assertRestrictions(
1763 DpmTestUtils.newRestrictions(),
1764 dpm.getUserRestrictions(admin1)
1765 );
1766 }
1767
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001768 public void testGetMacAddress() throws Exception {
1769 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1770 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1771 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1772
1773 // In this test, change the caller user to "system".
1774 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1775
1776 // Make sure admin1 is installed on system user.
1777 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1778
1779 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001780 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1781 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001782
1783 // DO needs to be an DA.
1784 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1785 assertTrue(dpm.isAdminActive(admin1));
1786
1787 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001788 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1789 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001790
1791 // Test 3. Caller has PO, but not DO.
1792 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001793 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1794 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001795
1796 // Remove PO.
1797 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001798 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001799 // Test 4, Caller is DO now.
1800 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1801
1802 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001803 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001804
1805 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001806 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001807 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001808
1809 // 4-3. With a real MAC address.
1810 final WifiInfo wi = new WifiInfo();
1811 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001812 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001813 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001814 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001815
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001816 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001817 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1818 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1819
1820 // In this test, change the caller user to "system".
1821 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1822
1823 // Make sure admin1 is installed on system user.
1824 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1825
1826 // Set admin1 as DA.
1827 dpm.setActiveAdmin(admin1, false);
1828 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001829 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1830 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001831
1832 // Set admin1 as PO.
1833 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001834 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1835 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001836
1837 // Remove PO and add DO.
1838 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001839 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001840 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1841
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001842 // admin1 is DO.
1843 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001844 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001845 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001846 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1847 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001848
1849 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001850 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001851 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001852 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1853 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001854
1855 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001856 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001857 dpm.reboot(admin1);
1858 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001859
1860 public void testSetGetSupportText() {
1861 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1862 dpm.setActiveAdmin(admin1, true);
1863 dpm.setActiveAdmin(admin2, true);
1864 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1865
1866 // Null default support messages.
1867 {
1868 assertNull(dpm.getLongSupportMessage(admin1));
1869 assertNull(dpm.getShortSupportMessage(admin1));
1870 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1871 assertNull(dpm.getShortSupportMessageForUser(admin1,
1872 DpmMockContext.CALLER_USER_HANDLE));
1873 assertNull(dpm.getLongSupportMessageForUser(admin1,
1874 DpmMockContext.CALLER_USER_HANDLE));
1875 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1876 }
1877
1878 // Only system can call the per user versions.
1879 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001880 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1881 () -> dpm.getShortSupportMessageForUser(admin1,
1882 DpmMockContext.CALLER_USER_HANDLE));
1883 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1884 () -> dpm.getLongSupportMessageForUser(admin1,
1885 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00001886 }
1887
1888 // Can't set message for admin in another uid.
1889 {
1890 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001891 assertExpectException(SecurityException.class,
1892 /* messageRegex= */ "is not owned by uid",
1893 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00001894 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1895 }
1896
1897 // Set/Get short returns what it sets and other admins text isn't changed.
1898 {
1899 final String supportText = "Some text to test with.";
1900 dpm.setShortSupportMessage(admin1, supportText);
1901 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1902 assertNull(dpm.getLongSupportMessage(admin1));
1903 assertNull(dpm.getShortSupportMessage(admin2));
1904
1905 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1906 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1907 DpmMockContext.CALLER_USER_HANDLE));
1908 assertNull(dpm.getShortSupportMessageForUser(admin2,
1909 DpmMockContext.CALLER_USER_HANDLE));
1910 assertNull(dpm.getLongSupportMessageForUser(admin1,
1911 DpmMockContext.CALLER_USER_HANDLE));
1912 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1913
1914 dpm.setShortSupportMessage(admin1, null);
1915 assertNull(dpm.getShortSupportMessage(admin1));
1916 }
1917
1918 // Set/Get long returns what it sets and other admins text isn't changed.
1919 {
1920 final String supportText = "Some text to test with.\nWith more text.";
1921 dpm.setLongSupportMessage(admin1, supportText);
1922 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1923 assertNull(dpm.getShortSupportMessage(admin1));
1924 assertNull(dpm.getLongSupportMessage(admin2));
1925
1926 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1927 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1928 DpmMockContext.CALLER_USER_HANDLE));
1929 assertNull(dpm.getLongSupportMessageForUser(admin2,
1930 DpmMockContext.CALLER_USER_HANDLE));
1931 assertNull(dpm.getShortSupportMessageForUser(admin1,
1932 DpmMockContext.CALLER_USER_HANDLE));
1933 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1934
1935 dpm.setLongSupportMessage(admin1, null);
1936 assertNull(dpm.getLongSupportMessage(admin1));
1937 }
1938 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001939
phweiss73145f42017-01-17 19:06:38 +01001940 public void testCreateAdminSupportIntent() throws Exception {
1941 // Setup device owner.
1942 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1943 setupDeviceOwner();
1944
1945 // Nonexisting permission returns null
1946 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
1947 assertNull(intent);
1948
1949 // Existing permission that is not set returns null
1950 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1951 assertNull(intent);
1952
1953 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01001954 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01001955 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1956 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1957 .thenReturn(true);
1958 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1959 assertNull(intent);
1960
1961 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01001962 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01001963 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1964 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1965 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
1966 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1967 assertNotNull(intent);
1968 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
1969 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
1970 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001971 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01001972 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
1973 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1974
1975 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
1976 // user restrictions
1977
1978 // Camera is not disabled
1979 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1980 assertNull(intent);
1981
1982 // Camera is disabled
1983 dpm.setCameraDisabled(admin1, true);
1984 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1985 assertNotNull(intent);
1986 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
1987 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1988
1989 // Screen capture is not disabled
1990 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1991 assertNull(intent);
1992
1993 // Screen capture is disabled
1994 dpm.setScreenCaptureDisabled(admin1, true);
1995 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1996 assertNotNull(intent);
1997 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
1998 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1999
2000 // Same checks for different user
2001 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2002 // Camera should be disabled by device owner
2003 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2004 assertNotNull(intent);
2005 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2006 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2007 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2008 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2009 // ScreenCapture should not be disabled by device owner
2010 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2011 assertNull(intent);
2012 }
2013
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002014 /**
2015 * Test for:
2016 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002017 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002018 * {@link DevicePolicyManager#isAffiliatedUser}
2019 */
2020 public void testUserAffiliation() throws Exception {
2021 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2022 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2023 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2024
2025 // Check that the system user is unaffiliated.
2026 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2027 assertFalse(dpm.isAffiliatedUser());
2028
2029 // Set a device owner on the system user. Check that the system user becomes affiliated.
2030 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2031 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2032 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2033 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002034 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002035
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002036 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002037 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2038 setAsProfileOwner(admin2);
2039 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002040 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002041
2042 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2043 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002044 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002045 userAffiliationIds.add("red");
2046 userAffiliationIds.add("green");
2047 userAffiliationIds.add("blue");
2048 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002049 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002050 assertFalse(dpm.isAffiliatedUser());
2051
2052 // Have the device owner specify a set of affiliation ids that do not intersect with those
2053 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002054 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002055 deviceAffiliationIds.add("cyan");
2056 deviceAffiliationIds.add("yellow");
2057 deviceAffiliationIds.add("magenta");
2058 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2059 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002060 MoreAsserts.assertContentsInAnyOrder(
2061 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002062 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2063 assertFalse(dpm.isAffiliatedUser());
2064
2065 // Have the profile owner specify a set of affiliation ids that intersect with those
2066 // specified by the device owner. Check that the test user becomes affiliated.
2067 userAffiliationIds.add("yellow");
2068 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002069 MoreAsserts.assertContentsInAnyOrder(
2070 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002071 assertTrue(dpm.isAffiliatedUser());
2072
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002073 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002074 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002075 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002076 assertFalse(dpm.isAffiliatedUser());
2077
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002078 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2079 dpm.setAffiliationIds(admin2, userAffiliationIds);
2080 assertTrue(dpm.isAffiliatedUser());
2081 dpm.clearProfileOwner(admin2);
2082 assertFalse(dpm.isAffiliatedUser());
2083
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002084 // Check that the system user remains affiliated.
2085 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2086 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002087
2088 // Clear the device owner - the user becomes unaffiliated.
2089 clearDeviceOwner();
2090 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002091 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002092
2093 public void testGetUserProvisioningState_defaultResult() {
2094 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2095 }
2096
2097 public void testSetUserProvisioningState_permission() throws Exception {
2098 setupProfileOwner();
2099 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2100
2101 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2102 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2103 }
2104
2105 public void testSetUserProvisioningState_unprivileged() throws Exception {
2106 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002107 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2108 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2109 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002110 }
2111
2112 public void testSetUserProvisioningState_noManagement() {
2113 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002114 assertExpectException(IllegalStateException.class,
2115 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2116 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2117 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002118 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2119 }
2120
2121 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2122 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2123 setupDeviceOwner();
2124 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2125
2126 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2127 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2128 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2129 }
2130
2131 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2132 throws Exception {
2133 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2134 setupDeviceOwner();
2135 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2136
2137 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2138 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2139 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2140 }
2141
2142 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2143 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2144 setupDeviceOwner();
2145 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2146
2147 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2148 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2149 }
2150
2151 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2152 throws Exception {
2153 setupProfileOwner();
2154 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2155
2156 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2157 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2158 DevicePolicyManager.STATE_USER_UNMANAGED);
2159 }
2160
2161 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2162 throws Exception {
2163 setupProfileOwner();
2164 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2165
2166 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2167 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2168 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2169 }
2170
2171 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2172 setupProfileOwner();
2173 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2174
2175 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2176 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2177 }
2178
2179 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2180 setupProfileOwner();
2181 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2182
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002183 assertExpectException(IllegalStateException.class,
2184 /* messageRegex= */ "Cannot move to user provisioning state",
2185 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2186 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2187 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002188 }
2189
2190 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2191 throws Exception {
2192 setupProfileOwner();
2193 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2194
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002195 assertExpectException(IllegalStateException.class,
2196 /* messageRegex= */ "Cannot move to user provisioning state",
2197 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2198 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2199 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002200 }
2201
2202 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2203 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2204 for (int state : states) {
2205 dpm.setUserProvisioningState(state, userId);
2206 assertEquals(state, dpm.getUserProvisioningState());
2207 }
2208 }
2209
2210 private void setupProfileOwner() throws Exception {
2211 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2212
2213 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2214 dpm.setActiveAdmin(admin1, false);
2215 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2216
2217 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2218 }
2219
2220 private void setupDeviceOwner() throws Exception {
2221 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2222
2223 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2224 dpm.setActiveAdmin(admin1, false);
2225 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2226
2227 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2228 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002229
2230 public void testSetMaximumTimeToLock() {
2231 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2232
2233 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2234 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2235
Pavel Grafov75c0a892017-05-18 17:28:27 +01002236 reset(getServices().powerManagerInternal);
2237 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002238
2239 dpm.setMaximumTimeToLock(admin1, 0);
2240 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002241 reset(getServices().powerManagerInternal);
2242 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002243
2244 dpm.setMaximumTimeToLock(admin1, 1);
2245 verifyScreenTimeoutCall(1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002246 reset(getServices().powerManagerInternal);
2247 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002248
2249 dpm.setMaximumTimeToLock(admin2, 10);
2250 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002251 reset(getServices().powerManagerInternal);
2252 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002253
2254 dpm.setMaximumTimeToLock(admin1, 5);
2255 verifyScreenTimeoutCall(5, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002256 reset(getServices().powerManagerInternal);
2257 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002258
2259 dpm.setMaximumTimeToLock(admin2, 4);
2260 verifyScreenTimeoutCall(4, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002261 reset(getServices().powerManagerInternal);
2262 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002263
2264 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002265 reset(getServices().powerManagerInternal);
2266 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002267
2268 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2269 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002270 reset(getServices().powerManagerInternal);
2271 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002272
2273 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2274 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002275 reset(getServices().powerManagerInternal);
2276 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002277
2278 dpm.setMaximumTimeToLock(admin2, 10);
2279 verifyScreenTimeoutCall(10, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002280 reset(getServices().powerManagerInternal);
2281 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002282
2283 // There's no restriction; shold be set to MAX.
2284 dpm.setMaximumTimeToLock(admin2, 0);
2285 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2286 }
2287
Michal Karpinski943aabd2016-10-06 11:09:25 +01002288 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2289 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2290 setupDeviceOwner();
2291 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2292
Michal Karpinskid084ca52017-01-18 15:54:18 +00002293 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2294 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2295 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2296 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2297 - ONE_MINUTE;
2298
2299 // verify that the minimum timeout cannot be modified on user builds (system property is
2300 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002301 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002302
2303 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2304 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2305 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2306
Pavel Grafov75c0a892017-05-18 17:28:27 +01002307 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002308
2309 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002310 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002311
2312 // Always return the default (second arg) when getting system property for long type
Pavel Grafov75c0a892017-05-18 17:28:27 +01002313 when(getServices().systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2314 invocation -> invocation.getArguments()[1]
Michal Karpinskid084ca52017-01-18 15:54:18 +00002315 );
2316
2317 // reset to default (0 means the admin is not participating, so default should be returned)
2318 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002319
2320 // aggregation should be the default if unset by any admin
2321 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2322 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2323
2324 // admin not participating by default
2325 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2326
2327 //clamping from the top
2328 dpm.setRequiredStrongAuthTimeout(admin1,
2329 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2330 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2331 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2332 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2333 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2334
Michal Karpinskid084ca52017-01-18 15:54:18 +00002335 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002336 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2337 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2338 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2339 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2340
2341 // clamping from the bottom
2342 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2343 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2344 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2345
Michal Karpinskid084ca52017-01-18 15:54:18 +00002346 // values within range
2347 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2348 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2349 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2350
2351 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2352 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2353 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002354
2355 // reset to default
2356 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2357 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2358 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2359 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2360
2361 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002362 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2363 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002364 }
2365
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002366 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2367 boolean shouldStayOnWhilePluggedInBeCleared) {
2368 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002369 verify(getServices().powerManagerInternal, times(0))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002370 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2371 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002372 verify(getServices().powerManagerInternal, times(1))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002373 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2374 }
2375 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2376 // UnfinishedVerificationException.
2377 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002378
Esteban Talavera01576862016-12-15 11:16:44 +00002379 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002380 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002381 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002382 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002383 .thenReturn(false);
2384 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002385 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2386 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002387 .thenReturn(true);
2388 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2389
2390 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002391 }
Victor Chang3e794af2016-03-04 13:48:17 +00002392
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002393 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2394 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002395 mContext.packageName = admin1.getPackageName();
2396 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002397 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2398 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2399 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2400 false);
2401 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2402 }
2403
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002404 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2405 setup_DeviceAdminFeatureOff();
2406 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2407 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2408 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2409 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2410 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2411 assertCheckProvisioningPreCondition(
2412 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2413 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2414 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2415 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2416 }
2417
Esteban Talavera01576862016-12-15 11:16:44 +00002418 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002419 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002420 .thenReturn(false);
2421 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002422 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2423 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002424 .thenReturn(true);
2425 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2426
2427 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002428 }
Victor Chang3e794af2016-03-04 13:48:17 +00002429
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002430 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2431 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002432 mContext.packageName = admin1.getPackageName();
2433 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002434 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2435 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2436 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2437 false);
2438 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2439
2440 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002441 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002442 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2443 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2444 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2445 true);
2446 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2447 }
2448
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002449 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2450 setup_ManagedProfileFeatureOff();
2451 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2452 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2453 DevicePolicyManager.CODE_OK);
2454 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2455 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2456 assertCheckProvisioningPreCondition(
2457 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2458 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2459 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2460 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2461
2462 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002463 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002464 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2465 DevicePolicyManager.CODE_OK);
2466 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2467 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2468 assertCheckProvisioningPreCondition(
2469 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2470 DevicePolicyManager.CODE_OK);
2471 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2472 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2473 }
2474
Esteban Talavera01576862016-12-15 11:16:44 +00002475 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002476 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002477 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002478 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2479 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002480 .thenReturn(true);
2481 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2482
2483 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002484 }
Victor Chang3e794af2016-03-04 13:48:17 +00002485
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002486 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2487 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002488 mContext.packageName = admin1.getPackageName();
2489 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002490 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2491 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2492 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2493 false /* because of non-split user */);
2494 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2495 false /* because of non-split user */);
2496 }
2497
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002498 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002499 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002500 setup_nonSplitUser_firstBoot_primaryUser();
2501 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2502 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2503 DevicePolicyManager.CODE_OK);
2504 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2505 DevicePolicyManager.CODE_OK);
2506 assertCheckProvisioningPreCondition(
2507 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2508 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2509 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2510 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2511 }
2512
Esteban Talavera01576862016-12-15 11:16:44 +00002513 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002514 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002515 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002516 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2517 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002518 .thenReturn(true);
2519 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2520
2521 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002522 }
Victor Chang3e794af2016-03-04 13:48:17 +00002523
Nicolas Prevot45d29072017-01-18 16:11:19 +00002524 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2525 setDeviceOwner();
2526 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2527 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2528 }
2529
2530 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2531 setup_nonSplitUser_withDo_primaryUser();
2532 final int MANAGED_PROFILE_USER_ID = 18;
2533 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2534 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002535 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002536 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002537 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002538 true)).thenReturn(true);
2539 }
2540
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002541 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2542 throws Exception {
2543 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002544 mContext.packageName = admin1.getPackageName();
2545 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002546 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2547 false/* because of completed device setup */);
2548 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2549 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2550 false/* because of non-split user */);
2551 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2552 false/* because of non-split user */);
2553 }
2554
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002555 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2556 throws Exception {
2557 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2558 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2559 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2560 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2561 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2562 DevicePolicyManager.CODE_OK);
2563 assertCheckProvisioningPreCondition(
2564 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2565 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2566 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2567 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2568 }
2569
Nicolas Prevot45d29072017-01-18 16:11:19 +00002570 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2571 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002572 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002573 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2574
2575 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2576 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002577 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002578
2579 // COMP mode is allowed.
2580 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2581 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002582 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002583
Nicolas Prevot45d29072017-01-18 16:11:19 +00002584 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002585 assertCheckProvisioningPreCondition(
2586 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002587 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002588 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002589 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2590 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2591 }
Esteban Talavera01576862016-12-15 11:16:44 +00002592
Nicolas Prevot45d29072017-01-18 16:11:19 +00002593 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2594 setup_nonSplitUser_withDo_primaryUser();
2595 mContext.packageName = admin1.getPackageName();
2596 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2597 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2598 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002599 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002600 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2601 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2602 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002603 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002604 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2605 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2606 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2607 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2608 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002609 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002610 assertCheckProvisioningPreCondition(
2611 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002612 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002613 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002614 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2615 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2616 }
Esteban Talavera01576862016-12-15 11:16:44 +00002617
Nicolas Prevot45d29072017-01-18 16:11:19 +00002618 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2619 throws Exception {
2620 setup_nonSplitUser_withDo_primaryUser();
2621 mContext.packageName = admin1.getPackageName();
2622 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002623 // The DO should not be allowed to initiate provisioning if the restriction is set by
2624 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002625 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002626 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2627 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2628 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002629 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002630 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2631 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2632 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2633 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2634 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002635 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2636
2637 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002638 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002639 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002640 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002641 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2642 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2643 }
2644
2645 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2646 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2647 mContext.packageName = admin1.getPackageName();
2648 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2649
2650 // We can delete the managed profile to create a new one, so provisioning is allowed.
2651 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2652 DevicePolicyManager.CODE_OK);
2653 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2654 assertCheckProvisioningPreCondition(
2655 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2656 DpmMockContext.ANOTHER_PACKAGE_NAME,
2657 DevicePolicyManager.CODE_OK);
2658 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2659 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2660 }
2661
2662 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2663 throws Exception {
2664 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2665 mContext.packageName = admin1.getPackageName();
2666 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002667 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002668 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2669 eq(UserHandle.SYSTEM)))
2670 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002671 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002672 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2673 eq(UserHandle.SYSTEM)))
2674 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002675
2676 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002677 assertCheckProvisioningPreCondition(
2678 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2679 DpmMockContext.ANOTHER_PACKAGE_NAME,
2680 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2681 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2682 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002683
2684 // But the device owner can still do it because it has set the restriction itself.
2685 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2686 DevicePolicyManager.CODE_OK);
2687 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002688 }
2689
2690 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002691 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002692 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002693 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2694 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002695 .thenReturn(false);
2696 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2697
2698 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002699 }
Victor Chang3e794af2016-03-04 13:48:17 +00002700
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002701 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2702 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002703 mContext.packageName = admin1.getPackageName();
2704 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002705 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2706 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2707 false /* because canAddMoreManagedProfiles returns false */);
2708 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2709 true);
2710 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2711 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002712 }
2713
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002714 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2715 throws Exception {
2716 setup_splitUser_firstBoot_systemUser();
2717 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2718 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2719 DevicePolicyManager.CODE_OK);
2720 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002721 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002722 assertCheckProvisioningPreCondition(
2723 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2724 DevicePolicyManager.CODE_OK);
2725 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2726 DevicePolicyManager.CODE_SYSTEM_USER);
2727 }
2728
Esteban Talavera01576862016-12-15 11:16:44 +00002729 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002730 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002731 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002732 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2733 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002734 .thenReturn(false);
2735 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2736
2737 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002738 }
Victor Chang3e794af2016-03-04 13:48:17 +00002739
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002740 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2741 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002742 mContext.packageName = admin1.getPackageName();
2743 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002744 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2745 true/* it's undefined behavior. Can be changed into false in the future */);
2746 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2747 false /* because canAddMoreManagedProfiles returns false */);
2748 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2749 true/* it's undefined behavior. Can be changed into false in the future */);
2750 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2751 false/* because calling uid is system user */);
2752 }
2753
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002754 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2755 throws Exception {
2756 setup_splitUser_afterDeviceSetup_systemUser();
2757 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2758 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2759 DevicePolicyManager.CODE_OK);
2760 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002761 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002762 assertCheckProvisioningPreCondition(
2763 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2764 DevicePolicyManager.CODE_OK);
2765 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2766 DevicePolicyManager.CODE_SYSTEM_USER);
2767 }
2768
Esteban Talavera01576862016-12-15 11:16:44 +00002769 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002770 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002771 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002772 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2773 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002774 true)).thenReturn(true);
2775 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2776
2777 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002778 }
Victor Chang3e794af2016-03-04 13:48:17 +00002779
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002780 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2781 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002782 mContext.packageName = admin1.getPackageName();
2783 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002784 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2786 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2787 true);
2788 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002789 }
2790
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002791 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002792 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002793 setup_splitUser_firstBoot_primaryUser();
2794 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2795 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2796 DevicePolicyManager.CODE_OK);
2797 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2798 DevicePolicyManager.CODE_OK);
2799 assertCheckProvisioningPreCondition(
2800 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2801 DevicePolicyManager.CODE_OK);
2802 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2803 DevicePolicyManager.CODE_OK);
2804 }
2805
Esteban Talavera01576862016-12-15 11:16:44 +00002806 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002807 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002808 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002809 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2810 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002811 true)).thenReturn(true);
2812 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2813
2814 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002815 }
Victor Chang3e794af2016-03-04 13:48:17 +00002816
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002817 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2818 throws Exception {
2819 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002820 mContext.packageName = admin1.getPackageName();
2821 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002822 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2823 true/* it's undefined behavior. Can be changed into false in the future */);
2824 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2825 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2826 true/* it's undefined behavior. Can be changed into false in the future */);
2827 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2828 false/* because user setup completed */);
2829 }
2830
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002831 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002832 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002833 setup_splitUser_afterDeviceSetup_primaryUser();
2834 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2835 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2836 DevicePolicyManager.CODE_OK);
2837 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2838 DevicePolicyManager.CODE_OK);
2839 assertCheckProvisioningPreCondition(
2840 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2841 DevicePolicyManager.CODE_OK);
2842 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2843 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2844 }
2845
Esteban Talavera01576862016-12-15 11:16:44 +00002846 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002847 setDeviceOwner();
2848
Pavel Grafov75c0a892017-05-18 17:28:27 +01002849 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002850 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002851 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2852 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002853 .thenReturn(false);
2854 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2855
2856 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002857 }
Victor Chang3e794af2016-03-04 13:48:17 +00002858
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002859 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2860 throws Exception {
2861 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002862 mContext.packageName = admin1.getPackageName();
2863 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002864 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2865 false /* can't provision managed profile on system user */);
2866 }
2867
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002868 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002869 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002870 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2871 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2872 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2873 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2874 }
2875
2876 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002877 setDeviceOwner();
2878
Pavel Grafov75c0a892017-05-18 17:28:27 +01002879 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002880 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002881 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2882 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002883 true)).thenReturn(true);
2884 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2885
2886 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002887 }
Victor Chang3e794af2016-03-04 13:48:17 +00002888
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002889 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2890 throws Exception {
2891 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002892 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2893 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002894 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2895 }
2896
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002897 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002898 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002899 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2900 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002901
2902 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002903 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2904 DevicePolicyManager.CODE_OK);
2905 }
2906
2907 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002908 setDeviceOwner();
2909
Pavel Grafov75c0a892017-05-18 17:28:27 +01002910 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002911 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002912 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2913 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002914 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2915 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002916 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002917 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002918 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002919 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00002920 true)).thenReturn(true);
2921 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2922
2923 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002924 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002925
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002926 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2927 throws Exception {
2928 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002929 mContext.packageName = admin1.getPackageName();
2930 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002931 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2932 }
2933
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002934 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2935 throws Exception {
2936 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2937 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2938 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2939 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2940 }
2941
2942 public void testCheckProvisioningPreCondition_permission() {
2943 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002944 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2945 () -> dpm.checkProvisioningPreCondition(
2946 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002947 }
2948
Victor Chang3577ed22016-08-25 18:49:26 +01002949 public void testForceUpdateUserSetupComplete_permission() {
2950 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002951 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2952 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01002953 }
2954
2955 public void testForceUpdateUserSetupComplete_systemUser() {
2956 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2957 // GIVEN calling from user 20
2958 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002959 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2960 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01002961 }
2962
2963 public void testForceUpdateUserSetupComplete_userbuild() {
2964 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2965 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2966
2967 final int userId = UserHandle.USER_SYSTEM;
2968 // GIVEN userComplete is false in SettingsProvider
2969 setUserSetupCompleteForUser(false, userId);
2970
2971 // GIVEN userComplete is true in DPM
2972 DevicePolicyManagerService.DevicePolicyData userData =
2973 new DevicePolicyManagerService.DevicePolicyData(userId);
2974 userData.mUserSetupComplete = true;
2975 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2976
2977 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01002978 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01002979
2980 assertTrue(dpms.hasUserSetupCompleted());
2981
2982 dpm.forceUpdateUserSetupComplete();
2983
2984 // THEN the state in dpms is not changed
2985 assertTrue(dpms.hasUserSetupCompleted());
2986 }
2987
2988 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2989 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2990 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2991
2992 final int userId = UserHandle.USER_SYSTEM;
2993 // GIVEN userComplete is false in SettingsProvider
2994 setUserSetupCompleteForUser(false, userId);
2995
2996 // GIVEN userComplete is true in DPM
2997 DevicePolicyManagerService.DevicePolicyData userData =
2998 new DevicePolicyManagerService.DevicePolicyData(userId);
2999 userData.mUserSetupComplete = true;
3000 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3001
3002 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003003 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003004
3005 assertTrue(dpms.hasUserSetupCompleted());
3006
3007 dpm.forceUpdateUserSetupComplete();
3008
3009 // THEN the state in dpms is not changed
3010 assertFalse(dpms.hasUserSetupCompleted());
3011 }
3012
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003013 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003014 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003015 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003016
3017 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3018 runAsCaller(mAdmin1Context, dpms, dpm -> {
3019 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3020 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003021 }
3022
3023 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3024 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3025 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003026
3027 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3028 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003029 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003030 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3031 .thenReturn(true);
3032
3033 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003034 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003035
3036 // Enabling logging should not change the timestamp.
3037 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003038 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003039 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003040 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003041 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003042 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003043
3044 // Retrieving the logs should update the timestamp.
3045 final long beforeRetrieval = System.currentTimeMillis();
3046 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003047 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003048 final long afterRetrieval = System.currentTimeMillis();
3049 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3050 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3051
3052 // Retrieving the pre-boot logs should update the timestamp.
3053 Thread.sleep(2);
3054 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003055 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003056 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3057
3058 // Checking the timestamp again should not change it.
3059 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003060 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003061
3062 // Retrieving the logs again should update the timestamp.
3063 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003064 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003065 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3066
3067 // Disabling logging should not change the timestamp.
3068 Thread.sleep(2);
3069 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003070 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003071
3072 // Restarting the DPMS should not lose the timestamp.
3073 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003074 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003075
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003076 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3077 mContext.binder.callingUid = 1234567;
3078 mContext.callerPermissions.add(permission.MANAGE_USERS);
3079 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3080 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3081
3082 // System can retrieve the timestamp.
3083 mContext.binder.clearCallingIdentity();
3084 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3085
3086 // Removing the device owner should clear the timestamp.
3087 clearDeviceOwner();
3088 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003089 }
3090
3091 public void testGetLastBugReportRequestTime() throws Exception {
3092 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3093 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003094
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003095 mContext.packageName = admin1.getPackageName();
3096 mContext.applicationInfo = new ApplicationInfo();
3097 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3098 .thenReturn(Color.WHITE);
3099 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3100 anyObject())).thenReturn(Color.WHITE);
3101
Esteban Talaverad36dd152016-12-15 08:51:45 +00003102 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3103 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003104 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003105
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003106 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003107 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003108
3109 // Requesting a bug report should update the timestamp.
3110 final long beforeRequest = System.currentTimeMillis();
3111 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003112 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003113 final long afterRequest = System.currentTimeMillis();
3114 assertTrue(bugReportRequestTime >= beforeRequest);
3115 assertTrue(bugReportRequestTime <= afterRequest);
3116
3117 // Checking the timestamp again should not change it.
3118 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003119 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003120
3121 // Restarting the DPMS should not lose the timestamp.
3122 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003123 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003124
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003125 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3126 mContext.binder.callingUid = 1234567;
3127 mContext.callerPermissions.add(permission.MANAGE_USERS);
3128 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3129 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3130
3131 // System can retrieve the timestamp.
3132 mContext.binder.clearCallingIdentity();
3133 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3134
3135 // Removing the device owner should clear the timestamp.
3136 clearDeviceOwner();
3137 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003138 }
3139
3140 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3141 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3142 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003143 mContext.packageName = admin1.getPackageName();
3144 mContext.applicationInfo = new ApplicationInfo();
3145 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3146 .thenReturn(Color.WHITE);
3147 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3148 anyObject())).thenReturn(Color.WHITE);
3149
3150 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3151 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003152 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
3153 when(getServices().iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003154 .thenReturn(true);
3155
3156 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003157 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003158
3159 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3160 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003161 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003162
3163 // Enabling logging should not change the timestamp.
3164 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003165 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003166
3167 // Retrieving the logs should update the timestamp.
3168 final long beforeRetrieval = System.currentTimeMillis();
3169 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003170 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003171 final long afterRetrieval = System.currentTimeMillis();
3172 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3173 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3174
3175 // Checking the timestamp again should not change it.
3176 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003177 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003178
3179 // Retrieving the logs again should update the timestamp.
3180 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003181 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003182 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3183
3184 // Disabling logging should not change the timestamp.
3185 Thread.sleep(2);
3186 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003187 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003188
3189 // Restarting the DPMS should not lose the timestamp.
3190 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003191 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3192
3193 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3194 mContext.binder.callingUid = 1234567;
3195 mContext.callerPermissions.add(permission.MANAGE_USERS);
3196 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3197 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3198
3199 // System can retrieve the timestamp.
3200 mContext.binder.clearCallingIdentity();
3201 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3202
3203 // Removing the device owner should clear the timestamp.
3204 clearDeviceOwner();
3205 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003206 }
3207
Tony Mak2f26b792016-11-28 17:54:51 +00003208 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3209 // Setup device owner.
3210 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3211 setupDeviceOwner();
3212
3213 // Only device owner is setup, the result list should be empty.
3214 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3215 MoreAsserts.assertEmpty(targetUsers);
3216
3217 // Setup a managed profile managed by the same admin.
3218 final int MANAGED_PROFILE_USER_ID = 15;
3219 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3220 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3221
3222 // Add a secondary user, it should never talk with.
3223 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003224 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003225
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003226 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3227 // other.
3228 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3229 MoreAsserts.assertEmpty(targetUsers);
3230
3231 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3232 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3233 MoreAsserts.assertEmpty(targetUsers);
3234
3235 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003236 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003237 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3238 dpm.setAffiliationIds(admin1, userAffiliationIds);
3239
3240 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3241 dpm.setAffiliationIds(admin1, userAffiliationIds);
3242
Tony Mak2f26b792016-11-28 17:54:51 +00003243 // Calling from device owner admin, the result list should just contain the managed
3244 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003245 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003246 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3247 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3248
3249 // Calling from managed profile admin, the result list should just contain the system
3250 // user id.
3251 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3252 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3253 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003254
3255 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003256 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003257
3258 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3259 // to each other.
3260 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3261 MoreAsserts.assertEmpty(targetUsers);
3262
3263 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3264 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3265 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003266 }
3267
3268 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3269 // Setup a device owner.
3270 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3271 setupDeviceOwner();
3272
3273 // Set up a managed profile managed by different package.
3274 final int MANAGED_PROFILE_USER_ID = 15;
3275 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3276 final ComponentName adminDifferentPackage =
3277 new ComponentName("another.package", "whatever.class");
3278 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3279
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003280 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003281 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003282 dpm.setAffiliationIds(admin1, userAffiliationIds);
3283
3284 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3285 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3286
Tony Mak2f26b792016-11-28 17:54:51 +00003287 // Calling from device owner admin, we should get zero bind device admin target users as
3288 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003289 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003290 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3291 MoreAsserts.assertEmpty(targetUsers);
3292
3293 // Calling from managed profile admin, we should still get zero target users for the same
3294 // reason.
3295 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3296 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3297 MoreAsserts.assertEmpty(targetUsers);
3298 }
3299
Esteban Talaverabdcada92017-02-01 14:20:06 +00003300 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3301 // Setup a device owner.
3302 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3303 setupDeviceOwner();
3304 // Lock task packages are updated when loading user data.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003305 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003306 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3307
3308 // Set up a managed profile managed by different package (package name shouldn't matter)
3309 final int MANAGED_PROFILE_USER_ID = 15;
3310 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3311 final ComponentName adminDifferentPackage =
3312 new ComponentName("another.package", "whatever.class");
3313 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003314 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003315 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3316
3317 // The DO can still set lock task packages
3318 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3319 final String[] doPackages = {"doPackage1", "doPackage2"};
3320 dpm.setLockTaskPackages(admin1, doPackages);
3321 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3322 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3323 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003324 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003325 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3326
3327 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3328 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3329 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003330 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3331 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3332 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3333 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003334 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3335
3336 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003337 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003338 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3339 dpm.setAffiliationIds(admin1, userAffiliationIds);
3340
3341 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3342 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3343
3344 // Now the managed profile can set lock task packages.
3345 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3346 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3347 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3348 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003349 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003350 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3351
3352 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003353 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003354 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3355 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003356 verify(getServices().iactivityManager, times(2))
Esteban Talaverabdcada92017-02-01 14:20:06 +00003357 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3358
3359 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3360 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3361 }
3362
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003363 public void testIsDeviceManaged() throws Exception {
3364 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3365 setupDeviceOwner();
3366
3367 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3368 // find out that the device has a device owner.
3369 assertTrue(dpm.isDeviceManaged());
3370 mContext.binder.callingUid = 1234567;
3371 mContext.callerPermissions.add(permission.MANAGE_USERS);
3372 assertTrue(dpm.isDeviceManaged());
3373 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3374 mContext.binder.clearCallingIdentity();
3375 assertTrue(dpm.isDeviceManaged());
3376
3377 clearDeviceOwner();
3378
3379 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3380 // not have a device owner.
3381 mContext.binder.callingUid = 1234567;
3382 mContext.callerPermissions.add(permission.MANAGE_USERS);
3383 assertFalse(dpm.isDeviceManaged());
3384 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3385 mContext.binder.clearCallingIdentity();
3386 assertFalse(dpm.isDeviceManaged());
3387 }
3388
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003389 public void testDeviceOwnerOrganizationName() throws Exception {
3390 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3391 setupDeviceOwner();
3392
3393 dpm.setOrganizationName(admin1, "organization");
3394
3395 // Device owner can retrieve organization managing the device.
3396 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3397
3398 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3399 mContext.binder.callingUid = 1234567;
3400 mContext.callerPermissions.add(permission.MANAGE_USERS);
3401 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3402 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3403
3404 // System can retrieve organization managing the device.
3405 mContext.binder.clearCallingIdentity();
3406 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3407
3408 // Removing the device owner clears the organization managing the device.
3409 clearDeviceOwner();
3410 assertNull(dpm.getDeviceOwnerOrganizationName());
3411 }
3412
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003413 public void testWipeDataManagedProfile() throws Exception {
3414 final int MANAGED_PROFILE_USER_ID = 15;
3415 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3416 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3417 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3418
3419 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003420 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003421 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3422
3423 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003424 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003425 MANAGED_PROFILE_USER_ID);
3426 }
3427
3428 public void testWipeDataManagedProfileDisallowed() throws Exception {
3429 final int MANAGED_PROFILE_USER_ID = 15;
3430 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3431 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3432
3433 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003434 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003435 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3436
Pavel Grafov75c0a892017-05-18 17:28:27 +01003437 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003438 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3439 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3440 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3441 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003442 // The PO is not allowed to remove the profile if the user restriction was set on the
3443 // profile by the system
3444 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3445 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003446 }
3447
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003448 public void testWipeDataDeviceOwner() throws Exception {
3449 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003450 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003451 UserManager.DISALLOW_FACTORY_RESET,
3452 UserHandle.SYSTEM))
3453 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3454
3455 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003456 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003457 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3458 /*wipeEuicc=*/ eq(false));
3459 }
3460
3461 public void testWipeEuiccDataEnabled() throws Exception {
3462 setDeviceOwner();
3463 when(getServices().userManager.getUserRestrictionSource(
3464 UserManager.DISALLOW_FACTORY_RESET,
3465 UserHandle.SYSTEM))
3466 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3467
3468 dpm.wipeData(WIPE_EUICC);
3469 verify(getServices().recoverySystem).rebootWipeUserData(
3470 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3471 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003472 }
3473
3474 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3475 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003476 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003477 UserManager.DISALLOW_FACTORY_RESET,
3478 UserHandle.SYSTEM))
3479 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003480 // The DO is not allowed to wipe the device if the user restriction was set
3481 // by the system
3482 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3483 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003484 }
3485
3486 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3487 final int MANAGED_PROFILE_USER_ID = 15;
3488 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3489 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3490
3491 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003492 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003493 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3494
Pavel Grafov75c0a892017-05-18 17:28:27 +01003495 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003496 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3497 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3498 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3499
3500 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3501 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3502
3503 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3504 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3505 // Failed password attempts on the parent user are taken into account, as there isn't a
3506 // separate work challenge.
3507 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3508 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3509 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3510
3511 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3512 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003513 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003514 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003515 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003516 }
3517
3518 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3519 throws Exception {
3520 final int MANAGED_PROFILE_USER_ID = 15;
3521 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3522 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3523
3524 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003525 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003526 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3527
Pavel Grafov75c0a892017-05-18 17:28:27 +01003528 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003529 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3530 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3531 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3532
3533 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3534 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3535
3536 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3537 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3538 // Failed password attempts on the parent user are taken into account, as there isn't a
3539 // separate work challenge.
3540 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3541 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3542 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3543
3544 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3545 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003546 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003547 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003548 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003549 }
3550
3551 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3552 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003553 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003554 UserManager.DISALLOW_FACTORY_RESET,
3555 UserHandle.SYSTEM))
3556 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3557
3558 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3559
3560 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3561 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3562 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3563 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3564 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3565
3566 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3567 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003568 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003569 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3570 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003571 }
3572
3573 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3574 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003575 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003576 UserManager.DISALLOW_FACTORY_RESET,
3577 UserHandle.SYSTEM))
3578 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3579
3580 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3581
3582 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3583 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3584 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3585 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3586 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3587
3588 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003589 verifyZeroInteractions(getServices().recoverySystem);
3590 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003591 .removeUserEvenWhenDisallowed(anyInt());
3592 }
3593
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003594 public void testGetPermissionGrantState() throws Exception {
3595 final String permission = "some.permission";
3596 final String app1 = "com.example.app1";
3597 final String app2 = "com.example.app2";
3598
Pavel Grafov75c0a892017-05-18 17:28:27 +01003599 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003600 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003601 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003602 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003603 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003604 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3605 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003606 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003607 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003608 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003609 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003610 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003611 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3612
3613 // System can retrieve permission grant state.
3614 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003615 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003616 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3617 dpm.getPermissionGrantState(null, app1, permission));
3618 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3619 dpm.getPermissionGrantState(null, app2, permission));
3620
3621 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003622 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3623 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003624 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3625 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003626
3627 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003628 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3629 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003630 setAsProfileOwner(admin1);
3631 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3632 dpm.getPermissionGrantState(admin1, app1, permission));
3633 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3634 dpm.getPermissionGrantState(admin1, app2, permission));
3635 }
3636
Rubin Xuaab7a412016-12-30 21:13:29 +00003637 public void testResetPasswordWithToken() throws Exception {
3638 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3639 setupDeviceOwner();
3640 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003641 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3642 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3643
Rubin Xuaab7a412016-12-30 21:13:29 +00003644 // test adding a token
3645 final byte[] token = new byte[32];
3646 final long handle = 123456;
3647 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003648 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003649 .thenReturn(handle);
3650 assertTrue(dpm.setResetPasswordToken(admin1, token));
3651
3652 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003653 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003654 .thenReturn(true);
3655 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3656
3657 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003658 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xuaab7a412016-12-30 21:13:29 +00003659 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3660 eq(UserHandle.USER_SYSTEM)))
3661 .thenReturn(true);
3662 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3663
3664 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003665 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003666 .thenReturn(true);
3667 assertTrue(dpm.clearResetPasswordToken(admin1));
3668 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003669
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003670 public void testIsActivePasswordSufficient() throws Exception {
3671 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3672 mContext.packageName = admin1.getPackageName();
3673 setupDeviceOwner();
3674
3675 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3676 dpm.setPasswordMinimumLength(admin1, 8);
3677 dpm.setPasswordMinimumLetters(admin1, 6);
3678 dpm.setPasswordMinimumLowerCase(admin1, 3);
3679 dpm.setPasswordMinimumUpperCase(admin1, 1);
3680 dpm.setPasswordMinimumNonLetter(admin1, 1);
3681 dpm.setPasswordMinimumNumeric(admin1, 1);
3682 dpm.setPasswordMinimumSymbols(admin1, 0);
3683
3684 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3685 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3686 8, 2,
3687 6, 1,
3688 0, 1);
3689
3690 setActivePasswordState(passwordMetricsNoSymbols);
3691 assertTrue(dpm.isActivePasswordSufficient());
3692
3693 initializeDpms();
3694 reset(mContext.spiedContext);
3695 assertTrue(dpm.isActivePasswordSufficient());
3696
3697 // This call simulates the user entering the password for the first time after a reboot.
3698 // This causes password metrics to be reloaded into memory. Until this happens,
3699 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3700 // even if the DPC changes password requirements so that the password no longer meets the
3701 // requirements. This is a known limitation of the current implementation of
3702 // isActivePasswordSufficient() - see b/34218769.
3703 setActivePasswordState(passwordMetricsNoSymbols);
3704 assertTrue(dpm.isActivePasswordSufficient());
3705
3706 dpm.setPasswordMinimumSymbols(admin1, 1);
3707 // This assertion would fail if we had not called setActivePasswordState() again after
3708 // initializeDpms() - see previous comment.
3709 assertFalse(dpm.isActivePasswordSufficient());
3710
3711 initializeDpms();
3712 reset(mContext.spiedContext);
3713 assertFalse(dpm.isActivePasswordSufficient());
3714
3715 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3716 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3717 7, 2,
3718 5, 1,
3719 1, 2);
3720
3721 setActivePasswordState(passwordMetricsWithSymbols);
3722 assertTrue(dpm.isActivePasswordSufficient());
3723 }
3724
Pavel Grafov75c0a892017-05-18 17:28:27 +01003725 private void setActivePasswordState(PasswordMetrics passwordMetrics)
3726 throws Exception {
3727 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003728 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003729
Pavel Grafov75c0a892017-05-18 17:28:27 +01003730 dpm.setActivePasswordState(passwordMetrics, userHandle);
3731 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003732
Pavel Grafov75c0a892017-05-18 17:28:27 +01003733 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3734 intent.setComponent(admin1);
3735 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3736
3737 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3738 MockUtils.checkIntent(intent),
3739 MockUtils.checkUserHandle(userHandle));
3740
3741 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
3742 // let it finish with system uid, otherwise it will throw and crash.
3743 flushTasks();
3744
3745 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003746 }
3747
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003748 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3749 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3750 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3751 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3752 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3753 DpmMockContext.SYSTEM_UID);
3754 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3755 DpmMockContext.SYSTEM_UID);
3756
3757 // Set up a device owner.
3758 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003759 setupDeviceOwner();
3760
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003761 // First and second user set IMEs manually.
3762 mContext.binder.callingUid = firstUserSystemUid;
3763 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3764 mContext.binder.callingUid = secondUserSystemUid;
3765 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003766
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003767 // Device owner changes IME for first user.
3768 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003769 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003770 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003771 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003772 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003773 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003774 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003775 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3776 mContext.binder.callingUid = firstUserSystemUid;
3777 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3778 mContext.binder.callingUid = secondUserSystemUid;
3779 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003780
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003781 // Second user changes IME manually.
3782 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3783 mContext.binder.callingUid = firstUserSystemUid;
3784 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3785 mContext.binder.callingUid = secondUserSystemUid;
3786 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003787
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003788 // First user changes IME manually.
3789 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3790 mContext.binder.callingUid = firstUserSystemUid;
3791 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3792 mContext.binder.callingUid = secondUserSystemUid;
3793 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003794
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003795 // Device owner changes IME for first user again.
3796 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003797 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003798 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003799 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003800 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003801 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003802 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3803 mContext.binder.callingUid = firstUserSystemUid;
3804 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3805 mContext.binder.callingUid = secondUserSystemUid;
3806 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003807
3808 // Restarting the DPMS should not lose information.
3809 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003810 mContext.binder.callingUid = firstUserSystemUid;
3811 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3812 mContext.binder.callingUid = secondUserSystemUid;
3813 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003814
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003815 // Device owner can find out whether it set the current IME itself.
3816 mContext.binder.callingUid = deviceOwnerUid;
3817 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003818
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003819 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003820 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003821 mContext.binder.callingUid = firstUserSystemUid;
3822 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3823 mContext.binder.callingUid = secondUserSystemUid;
3824 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003825 }
3826
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003827 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3828 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3829 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3830 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3831 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3832 DpmMockContext.SYSTEM_UID);
3833 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3834 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003835
3836 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003837 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003838 setupProfileOwner();
3839
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003840 // First and second user set IMEs manually.
3841 mContext.binder.callingUid = firstUserSystemUid;
3842 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3843 mContext.binder.callingUid = secondUserSystemUid;
3844 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003845
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003846 // Profile owner changes IME for second user.
3847 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003848 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003849 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003850 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003851 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003852 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003853 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003854 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3855 mContext.binder.callingUid = firstUserSystemUid;
3856 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3857 mContext.binder.callingUid = secondUserSystemUid;
3858 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003859
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003860 // First user changes IME manually.
3861 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3862 mContext.binder.callingUid = firstUserSystemUid;
3863 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3864 mContext.binder.callingUid = secondUserSystemUid;
3865 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003866
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003867 // Second user changes IME manually.
3868 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3869 mContext.binder.callingUid = firstUserSystemUid;
3870 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3871 mContext.binder.callingUid = secondUserSystemUid;
3872 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003873
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003874 // Profile owner changes IME for second user again.
3875 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003876 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003877 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003878 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003879 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003880 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003881 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3882 mContext.binder.callingUid = firstUserSystemUid;
3883 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3884 mContext.binder.callingUid = secondUserSystemUid;
3885 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003886
3887 // Restarting the DPMS should not lose information.
3888 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003889 mContext.binder.callingUid = firstUserSystemUid;
3890 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3891 mContext.binder.callingUid = secondUserSystemUid;
3892 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003893
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003894 // Profile owner can find out whether it set the current IME itself.
3895 mContext.binder.callingUid = profileOwnerUid;
3896 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003897
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003898 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003899 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003900 mContext.binder.callingUid = firstUserSystemUid;
3901 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3902 mContext.binder.callingUid = secondUserSystemUid;
3903 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003904 }
Rubin Xuaab7a412016-12-30 21:13:29 +00003905
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003906 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
3907 throws Exception {
3908 // Set up a device owner.
3909 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3910 setupDeviceOwner();
3911 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3912 }
3913
3914 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
3915 throws Exception {
3916 // Set up a profile owner.
3917 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3918 setupProfileOwner();
3919 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3920 }
3921
3922 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
3923 int adminUid) throws Exception {
3924 mContext.binder.callingUid = adminUid;
3925 final int userId = UserHandle.getUserId(adminUid);
3926
3927 final String packageName = "some.package";
3928 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
3929 admin1, Collections.singletonList(packageName)));
3930 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3931
3932 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3933 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
3934
3935 // Attempt to set to empty list (which means no listener is whitelisted)
3936 mContext.binder.callingUid = adminUid;
3937 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01003938 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003939 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3940
3941 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3942 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
3943 }
3944
3945 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
3946 // Set up a managed profile
3947 final int MANAGED_PROFILE_USER_ID = 15;
3948 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3949 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3950 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3951
3952 final String permittedListener = "some.package";
3953 setupPackageInPackageManager(
3954 permittedListener,
3955 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3956 /*appId=*/ 12345, /*flags=*/ 0);
3957
3958 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
3959 admin1, Collections.singletonList(permittedListener)));
3960
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003961 // isNotificationListenerServicePermitted should throw if not called from System.
3962 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3963 () -> dpms.isNotificationListenerServicePermitted(
3964 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003965
3966 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3967 assertTrue(dpms.isNotificationListenerServicePermitted(
3968 permittedListener, MANAGED_PROFILE_USER_ID));
3969 }
3970
3971 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
3972 throws Exception {
3973 // Set up a managed profile
3974 final int MANAGED_PROFILE_USER_ID = 15;
3975 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3976 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3977 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3978
3979 final String permittedListener = "permitted.package";
3980 int appId = 12345;
3981 setupPackageInPackageManager(
3982 permittedListener,
3983 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3984 appId, /*flags=*/ 0);
3985
3986 final String notPermittedListener = "not.permitted.package";
3987 setupPackageInPackageManager(
3988 notPermittedListener,
3989 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3990 ++appId, /*flags=*/ 0);
3991
3992 final String systemListener = "system.package";
3993 setupPackageInPackageManager(
3994 systemListener,
3995 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3996 ++appId, ApplicationInfo.FLAG_SYSTEM);
3997
3998 // By default all packages are allowed
3999 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4000
4001 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4002 assertTrue(dpms.isNotificationListenerServicePermitted(
4003 permittedListener, MANAGED_PROFILE_USER_ID));
4004 assertTrue(dpms.isNotificationListenerServicePermitted(
4005 notPermittedListener, MANAGED_PROFILE_USER_ID));
4006 assertTrue(dpms.isNotificationListenerServicePermitted(
4007 systemListener, MANAGED_PROFILE_USER_ID));
4008
4009 // Setting only one package in the whitelist
4010 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4011 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4012 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004013 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004014 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4015 assertEquals(1, permittedListeners.size());
4016 assertEquals(permittedListener, permittedListeners.get(0));
4017
4018 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4019 assertTrue(dpms.isNotificationListenerServicePermitted(
4020 permittedListener, MANAGED_PROFILE_USER_ID));
4021 assertFalse(dpms.isNotificationListenerServicePermitted(
4022 notPermittedListener, MANAGED_PROFILE_USER_ID));
4023 // System packages are always allowed (even if not in the whitelist)
4024 assertTrue(dpms.isNotificationListenerServicePermitted(
4025 systemListener, MANAGED_PROFILE_USER_ID));
4026
4027 // Setting an empty whitelist - only system listeners allowed
4028 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4029 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004030 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004031 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4032
4033 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4034 assertFalse(dpms.isNotificationListenerServicePermitted(
4035 permittedListener, MANAGED_PROFILE_USER_ID));
4036 assertFalse(dpms.isNotificationListenerServicePermitted(
4037 notPermittedListener, MANAGED_PROFILE_USER_ID));
4038 // System packages are always allowed (even if not in the whitelist)
4039 assertTrue(dpms.isNotificationListenerServicePermitted(
4040 systemListener, MANAGED_PROFILE_USER_ID));
4041
4042 // Setting a null whitelist - all listeners allowed
4043 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4044 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4045 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4046
4047 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4048 assertTrue(dpms.isNotificationListenerServicePermitted(
4049 permittedListener, MANAGED_PROFILE_USER_ID));
4050 assertTrue(dpms.isNotificationListenerServicePermitted(
4051 notPermittedListener, MANAGED_PROFILE_USER_ID));
4052 assertTrue(dpms.isNotificationListenerServicePermitted(
4053 systemListener, MANAGED_PROFILE_USER_ID));
4054 }
4055
4056 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4057 throws Exception {
4058 // Set up a managed profile
4059 final int MANAGED_PROFILE_USER_ID = 15;
4060 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4061 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4062 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4063
4064 final String nonSystemPackage = "non.system.package";
4065 int appId = 12345;
4066 setupPackageInPackageManager(
4067 nonSystemPackage,
4068 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4069 appId, /*flags=*/ 0);
4070
4071 final String systemListener = "system.package";
4072 setupPackageInPackageManager(
4073 systemListener,
4074 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4075 ++appId, ApplicationInfo.FLAG_SYSTEM);
4076
4077 // By default all packages are allowed (for all profiles)
4078 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4079
4080 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4081 assertTrue(dpms.isNotificationListenerServicePermitted(
4082 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4083 assertTrue(dpms.isNotificationListenerServicePermitted(
4084 systemListener, MANAGED_PROFILE_USER_ID));
4085 assertTrue(dpms.isNotificationListenerServicePermitted(
4086 nonSystemPackage, UserHandle.USER_SYSTEM));
4087 assertTrue(dpms.isNotificationListenerServicePermitted(
4088 systemListener, UserHandle.USER_SYSTEM));
4089
4090 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4091 // all allowed in primary profile
4092 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4093 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004094 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004095 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4096
4097 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4098 assertFalse(dpms.isNotificationListenerServicePermitted(
4099 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4100 assertTrue(dpms.isNotificationListenerServicePermitted(
4101 systemListener, MANAGED_PROFILE_USER_ID));
4102 assertTrue(dpms.isNotificationListenerServicePermitted(
4103 nonSystemPackage, UserHandle.USER_SYSTEM));
4104 assertTrue(dpms.isNotificationListenerServicePermitted(
4105 systemListener, UserHandle.USER_SYSTEM));
4106 }
4107
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004108 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004109 mServiceContext.packageName = mRealTestContext.getPackageName();
4110 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4111 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004112 setDeviceOwner();
4113
Pavel Grafov75c0a892017-05-18 17:28:27 +01004114 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004115 }
4116
4117 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004118 mServiceContext.packageName = mRealTestContext.getPackageName();
4119 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4120 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004121 setAsProfileOwner(admin1);
4122
Pavel Grafov75c0a892017-05-18 17:28:27 +01004123 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4124 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004125 }
4126
4127 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004128 mServiceContext.packageName = mRealTestContext.getPackageName();
4129 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4130 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004131 setAsProfileOwner(admin1);
4132
Pavel Grafov75c0a892017-05-18 17:28:27 +01004133 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4134 caller.packageName = "com.example.delegate";
4135 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4136 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004137
Pavel Grafov75c0a892017-05-18 17:28:27 +01004138 // Make caller a delegated cert installer.
4139 runAsCaller(mAdmin1Context, dpms,
4140 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004141
4142 verifyCanGetOwnerInstalledCaCerts(null, caller);
4143 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004144 }
4145
Robin Lee2c68dad2017-03-17 12:50:24 +00004146 private void verifyCanGetOwnerInstalledCaCerts(
4147 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004148 final String alias = "cert";
4149 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004150
4151 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004152 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004153 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4154 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004155 }
4156 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4157
4158 // caller: device admin or delegated certificate installer
4159 callerContext.applicationInfo = new ApplicationInfo();
4160 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4161
4162 // system_server
4163 final DpmMockContext serviceContext = mContext;
4164 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004165 getServices().addPackageContext(callerUser, admin1Context);
4166 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004167
4168 // Install a CA cert.
4169 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004170 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004171 .thenReturn(alias);
4172 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004173 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004174 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004175 });
4176
Pavel Grafov75c0a892017-05-18 17:28:27 +01004177 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4178 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4179 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004180 flushTasks();
4181
Robin Lee2c68dad2017-03-17 12:50:24 +00004182 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4183
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004184 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004185 runAsCaller(admin1Context, dpms, (dpm) -> {
4186 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004187 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004188 ownerInstalledCaCerts.addAll(installedCaCerts);
4189 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004190
4191 // Restarting the DPMS should not lose information.
4192 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004193 runAsCaller(admin1Context, dpms, (dpm) ->
4194 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004195
4196 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004197 runAsCaller(serviceContext, dpms, (dpm) -> {
4198 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004199
Robin Lee2c68dad2017-03-17 12:50:24 +00004200 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004201 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004202 });
4203
Pavel Grafov75c0a892017-05-18 17:28:27 +01004204 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4205 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4206 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004207 flushTasks();
4208
4209 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4210 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004211 runAsCaller(admin1Context, dpms, (dpm) -> {
4212 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4213 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004214 }
4215
Robin Lee2c68dad2017-03-17 12:50:24 +00004216 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4217 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004218 final String alias = "cert";
4219 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004220
4221 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004222 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004223 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4224 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004225 }
4226 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4227
4228 // caller: device admin or delegated certificate installer
4229 callerContext.applicationInfo = new ApplicationInfo();
4230 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4231
4232 // system_server
4233 final DpmMockContext serviceContext = mContext;
4234 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004235 getServices().addPackageContext(callerUser, admin1Context);
4236 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004237
4238 // Install a CA cert as caller
4239 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004240 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004241 .thenReturn(alias);
4242 assertTrue(dpm.installCaCert(callerName, caCert));
4243 });
4244
4245 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004246 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004247 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004248 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4249 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4250 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004251 flushTasks();
4252
Robin Lee2c68dad2017-03-17 12:50:24 +00004253 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004254 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004255
4256 runAsCaller(serviceContext, dpms, (dpm) -> {
4257 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4258 assertNotNull(ownerInstalledCaCerts);
4259 assertTrue(ownerInstalledCaCerts.isEmpty());
4260 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004261 }
4262
Victor Chang3e794af2016-03-04 13:48:17 +00004263 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004264 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004265 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4266 dpms.notifyChangeToContentObserver(
4267 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4268 }
4269
4270 private void assertProvisioningAllowed(String action, boolean expected) {
4271 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4272 dpm.isProvisioningAllowed(action));
4273 }
Tony Mak2f26b792016-11-28 17:54:51 +00004274
Nicolas Prevot45d29072017-01-18 16:11:19 +00004275 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4276 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004277 final String previousPackageName = mContext.packageName;
4278 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004279
4280 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4281 mContext.packageName = packageName;
4282 mMockContext.binder.callingUid = uid;
4283 assertProvisioningAllowed(action, expected);
4284
4285 // Set the previous package name / calling uid to go back to the initial state.
4286 mContext.packageName = previousPackageName;
4287 mMockContext.binder.callingUid = previousUid;
4288 }
4289
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004290 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004291 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4292 }
4293
4294 private void assertCheckProvisioningPreCondition(
4295 String action, String packageName, int provisioningCondition) {
4296 assertEquals("checkProvisioningPreCondition("
4297 + action + ", " + packageName + ") returning unexpected result",
4298 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004299 }
4300
Tony Mak2f26b792016-11-28 17:54:51 +00004301 /**
4302 * Setup a managed profile with the specified admin and its uid.
4303 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4304 * @param adminUid uid of the admin package.
4305 * @param copyFromAdmin package information for {@code admin} will be built based on this
4306 * component's information.
4307 */
4308 private void addManagedProfile(
4309 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4310 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004311 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004312 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4313 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4314 dpm.setActiveAdmin(admin, false, userId);
4315 assertTrue(dpm.setProfileOwner(admin, null, userId));
4316 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4317 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004318
4319 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004320 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004321 */
Robin Leeabaa0692017-02-20 20:54:22 +00004322 private static StringParceledListSlice asSlice(String[] s) {
4323 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004324 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004325
4326 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004327 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4328 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004329
Robin Lee2c68dad2017-03-17 12:50:24 +00004330 // We can't let exceptions happen on the background thread. Throw them here if they happen
4331 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004332 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004333 }
Victor Chang3e794af2016-03-04 13:48:17 +00004334}