blob: 0fda0fe8c7383c745bc045692704bd86f5ebe0ae [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
Eugene Susla4f8680b2017-08-07 17:25:30 -070025import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010026
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;
Christine Franks361b8252017-06-23 18:12:46 -070037import static org.mockito.Mockito.mock;
Pavel Grafov75c0a892017-05-18 17:28:27 +010038import static org.mockito.Mockito.never;
39import static org.mockito.Mockito.nullable;
40import static org.mockito.Mockito.reset;
41import static org.mockito.Mockito.timeout;
42import static org.mockito.Mockito.times;
43import static org.mockito.Mockito.verify;
44import static org.mockito.Mockito.verifyZeroInteractions;
45import static org.mockito.Mockito.when;
46import static org.mockito.hamcrest.MockitoHamcrest.argThat;
47
Makoto Onukif76b06a2015-09-22 15:03:44 -070048import android.Manifest.permission;
49import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000050import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070051import android.app.admin.DeviceAdminReceiver;
52import android.app.admin.DevicePolicyManager;
53import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010054import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070055import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070056import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000057import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000058import android.content.pm.ApplicationInfo;
59import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070060import android.content.pm.PackageManager;
Robin Leeabaa0692017-02-20 20:54:22 +000061import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000062import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010063import android.graphics.Color;
64import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080065import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080066import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070067import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080068import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070069import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070070import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010071import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080072import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010073import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000074import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080075import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000076import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010077import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070078import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070079
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010080import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000081import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000082import com.android.server.LocalServices;
83import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000084import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000085
Robin Lee7f5c91c2017-02-08 21:27:02 +000086import org.hamcrest.BaseMatcher;
87import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070088import org.mockito.invocation.InvocationOnMock;
89import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070090
Makoto Onukic8a5a552015-11-19 14:29:12 -080091import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000092import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000093import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070094import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070096import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010097import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000098import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070099
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700101 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000102 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103 m FrameworksServicesTests &&
104 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000105 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800107 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108
109 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000110 *
111 * , or:
112 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000114@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100115@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000117 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
118 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
119 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100120 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
121 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000122
Pavel Grafov75c0a892017-05-18 17:28:27 +0100123 // TODO replace all instances of this with explicit {@link #mServiceContext}.
124 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700125 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100126
127 private DpmMockContext mServiceContext;
128 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700129 public DevicePolicyManager dpm;
130 public DevicePolicyManagerServiceTestable dpms;
131
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100132 /*
133 * The CA cert below is the content of cacert.pem as generated by:
134 *
135 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
136 */
137 private static final String TEST_CA =
138 "-----BEGIN CERTIFICATE-----\n" +
139 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
140 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
141 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
142 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
143 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
144 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
145 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
146 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
147 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
148 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
149 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
150 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
151 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
152 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
153 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
154 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
155 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
156 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
157 "wQ==\n" +
158 "-----END CERTIFICATE-----\n";
159
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700160 @Override
161 protected void setUp() throws Exception {
162 super.setUp();
163
164 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100165 mServiceContext = mContext;
166 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
167 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700168 .thenReturn(true);
169
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800170 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100171 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800172
Makoto Onukia52562c2015-10-01 16:12:31 -0700173 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700174
Makoto Onukid932f762015-09-29 16:53:38 -0700175 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
176 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
177 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800178 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700179
Pavel Grafov75c0a892017-05-18 17:28:27 +0100180 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
181 mAdmin1Context.packageName = admin1.getPackageName();
182 mAdmin1Context.applicationInfo = new ApplicationInfo();
183 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
184
Makoto Onukib643fb02015-09-22 15:03:44 -0700185 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700186 }
187
Robin Lee2c68dad2017-03-17 12:50:24 +0000188 @Override
189 protected void tearDown() throws Exception {
190 flushTasks();
191 super.tearDown();
192 }
193
Makoto Onukia52562c2015-10-01 16:12:31 -0700194 private void initializeDpms() {
195 // Need clearCallingIdentity() to pass permission checks.
196 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100197 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700198
Pavel Grafov75c0a892017-05-18 17:28:27 +0100199 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
200 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
201 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700202
Pavel Grafov75c0a892017-05-18 17:28:27 +0100203 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700204
Pavel Grafov75c0a892017-05-18 17:28:27 +0100205 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700206 }
207
Makoto Onukib643fb02015-09-22 15:03:44 -0700208 private void setUpUserManager() {
209 // Emulate UserManager.set/getApplicationRestriction().
210 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
211
212 // UM.setApplicationRestrictions() will save to appRestrictions.
213 doAnswer(new Answer<Void>() {
214 @Override
215 public Void answer(InvocationOnMock invocation) throws Throwable {
216 String pkg = (String) invocation.getArguments()[0];
217 Bundle bundle = (Bundle) invocation.getArguments()[1];
218 UserHandle user = (UserHandle) invocation.getArguments()[2];
219
220 appRestrictions.put(Pair.create(pkg, user), bundle);
221
222 return null;
223 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100224 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100225 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700226
227 // UM.getApplicationRestrictions() will read from appRestrictions.
228 doAnswer(new Answer<Bundle>() {
229 @Override
230 public Bundle answer(InvocationOnMock invocation) throws Throwable {
231 String pkg = (String) invocation.getArguments()[0];
232 UserHandle user = (UserHandle) invocation.getArguments()[1];
233
234 return appRestrictions.get(Pair.create(pkg, user));
235 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100236 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700237 anyString(), any(UserHandle.class));
238
Makoto Onukid932f762015-09-29 16:53:38 -0700239 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100240 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700241 }
242
243 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100244 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700245
Pavel Grafov75c0a892017-05-18 17:28:27 +0100246 mServiceContext.binder.callingUid =
247 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
248 runAsCaller(mServiceContext, dpms, dpm -> {
249 // PO needs to be a DA.
250 dpm.setActiveAdmin(admin, /*replace=*/ false);
251 // Fire!
252 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
253 // Check
254 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
255 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700256
Pavel Grafov75c0a892017-05-18 17:28:27 +0100257 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700258 }
259
260 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100261 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700262 .thenReturn(false);
263
264 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100265 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700266
267 // If the device has no DPMS feature, it shouldn't register the local service.
268 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
269 }
270
271 /**
272 * Caller doesn't have proper permissions.
273 */
274 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700275 // 1. Failure cases.
276
277 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100278 assertExpectException(SecurityException.class, /* messageRegex= */ null,
279 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700280
281 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
282 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100283
284 assertExpectException(SecurityException.class, /* messageRegex= */ null,
285 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700286 }
287
Makoto Onukif76b06a2015-09-22 15:03:44 -0700288 /**
289 * Test for:
290 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800291 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700292 * {@link DevicePolicyManager#isAdminActive}
293 * {@link DevicePolicyManager#isAdminActiveAsUser}
294 * {@link DevicePolicyManager#getActiveAdmins}
295 * {@link DevicePolicyManager#getActiveAdminsAsUser}
296 */
297 public void testSetActiveAdmin() throws Exception {
298 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700299 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
300
Makoto Onukif76b06a2015-09-22 15:03:44 -0700301 // 2. Call the API.
302 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700303
304 // 3. Verify internal calls.
305
306 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700307 verify(mContext.spiedContext).sendBroadcastAsUser(
308 MockUtils.checkIntentAction(
309 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
310 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
311 verify(mContext.spiedContext).sendBroadcastAsUser(
312 MockUtils.checkIntentAction(
313 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700314 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
315
Pavel Grafov75c0a892017-05-18 17:28:27 +0100316 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700317 eq(admin1.getPackageName()),
318 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
319 eq(PackageManager.DONT_KILL_APP),
320 eq(DpmMockContext.CALLER_USER_HANDLE),
321 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700322
323 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700324
325 // Make sure it's active admin1.
326 assertTrue(dpm.isAdminActive(admin1));
327 assertFalse(dpm.isAdminActive(admin2));
328 assertFalse(dpm.isAdminActive(admin3));
329
330 // But not admin1 for a different user.
331
332 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
333 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
334 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
335
336 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
337 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
338
339 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
340
341 // Next, add one more admin.
342 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700343 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700344 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700345
346 dpm.setActiveAdmin(admin2, /* replace =*/ false);
347
348 // Now we have two admins.
349 assertTrue(dpm.isAdminActive(admin1));
350 assertTrue(dpm.isAdminActive(admin2));
351 assertFalse(dpm.isAdminActive(admin3));
352
353 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
354 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100355 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700356 eq(admin1.getPackageName()),
357 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
358 eq(PackageManager.DONT_KILL_APP),
359 eq(DpmMockContext.CALLER_USER_HANDLE),
360 anyString());
361
362 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100363 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
364 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700365
366 // 5. Add the same admin1 again with replace, which should succeed.
367 dpm.setActiveAdmin(admin1, /* replace =*/ true);
368
369 // TODO make sure it's replaced.
370
371 // 6. Test getActiveAdmins()
372 List<ComponentName> admins = dpm.getActiveAdmins();
373 assertEquals(2, admins.size());
374 assertEquals(admin1, admins.get(0));
375 assertEquals(admin2, admins.get(1));
376
377 // Another user has no admins.
378 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
379
380 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
381 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
382
383 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
384 }
385
Makoto Onukid932f762015-09-29 16:53:38 -0700386 public void testSetActiveAdmin_multiUsers() throws Exception {
387
388 final int ANOTHER_USER_ID = 100;
389 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
390
Pavel Grafov75c0a892017-05-18 17:28:27 +0100391 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700392
393 // Set up pacakge manager for the other user.
394 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700395
396 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
397
398 dpm.setActiveAdmin(admin1, /* replace =*/ false);
399
400 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
401 dpm.setActiveAdmin(admin2, /* replace =*/ false);
402
403
404 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
405 assertTrue(dpm.isAdminActive(admin1));
406 assertFalse(dpm.isAdminActive(admin2));
407
408 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
409 assertFalse(dpm.isAdminActive(admin1));
410 assertTrue(dpm.isAdminActive(admin2));
411 }
412
Makoto Onukif76b06a2015-09-22 15:03:44 -0700413 /**
414 * Test for:
415 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800416 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700417 */
418 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
419 // 1. Make sure the caller has proper permissions.
420 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
421
422 dpm.setActiveAdmin(admin1, /* replace =*/ false);
423 assertTrue(dpm.isAdminActive(admin1));
424
425 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100426 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
427 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700428 }
429
430 /**
431 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800432 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
433 * BIND_DEVICE_ADMIN.
434 */
435 public void testSetActiveAdmin_permissionCheck() throws Exception {
436 // 1. Make sure the caller has proper permissions.
437 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
438
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100439 assertExpectException(IllegalArgumentException.class,
440 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
441 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800442 assertFalse(dpm.isAdminActive(adminNoPerm));
443
444 // Change the target API level to MNC. Now it can be set as DA.
445 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
446 VERSION_CODES.M);
447 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
448 assertTrue(dpm.isAdminActive(adminNoPerm));
449
450 // TODO Test the "load from the file" case where DA will still be loaded even without
451 // BIND_DEVICE_ADMIN and target API is N.
452 }
453
454 /**
455 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700456 * {@link DevicePolicyManager#removeActiveAdmin}
457 */
458 public void testRemoveActiveAdmin_SecurityException() {
459 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
460
461 // Add admin.
462
463 dpm.setActiveAdmin(admin1, /* replace =*/ false);
464
465 assertTrue(dpm.isAdminActive(admin1));
466
467 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
468
469 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100470 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
471 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700472
473 // Try to remove active admin with a different caller userid should fail too, without
474 // having MANAGE_DEVICE_ADMINS.
475 mContext.callerPermissions.clear();
476
Makoto Onukid932f762015-09-29 16:53:38 -0700477 // Change the caller, and call into DPMS directly with a different user-id.
478
Makoto Onukif76b06a2015-09-22 15:03:44 -0700479 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100480 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
481 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700482 }
483
484 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800485 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
486 * (because we can't send the remove broadcast).
487 */
488 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
489 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
490
491 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
492
493 // Add admin.
494
495 dpm.setActiveAdmin(admin1, /* replace =*/ false);
496
497 assertTrue(dpm.isAdminActive(admin1));
498
499 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
500
501 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100502 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800503 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100504 assertExpectException(IllegalStateException.class,
505 /* messageRegex= */ "User must be running and unlocked",
506 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800507
508 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
509
510 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100511 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800512 .thenReturn(true);
513
514 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700515 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800516 }
517
518 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700519 * Test for:
520 * {@link DevicePolicyManager#removeActiveAdmin}
521 */
Makoto Onukid932f762015-09-29 16:53:38 -0700522 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700523 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
524
525 // Add admin1.
526
527 dpm.setActiveAdmin(admin1, /* replace =*/ false);
528
529 assertTrue(dpm.isAdminActive(admin1));
530 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
531
532 // Different user, but should work, because caller has proper permissions.
533 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700534
535 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700536 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700537
538 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700539 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700540
541 // TODO DO Still can't be removed in this case.
542 }
543
544 /**
545 * Test for:
546 * {@link DevicePolicyManager#removeActiveAdmin}
547 */
548 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
549 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
550 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
551
552 // Add admin1.
553
554 dpm.setActiveAdmin(admin1, /* replace =*/ false);
555
556 assertTrue(dpm.isAdminActive(admin1));
557 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
558
559 // Broadcast from saveSettingsLocked().
560 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
561 MockUtils.checkIntentAction(
562 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
563 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
564
565 // Remove. No permissions, but same user, so it'll work.
566 mContext.callerPermissions.clear();
567 dpm.removeActiveAdmin(admin1);
568
Makoto Onukif76b06a2015-09-22 15:03:44 -0700569 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
570 MockUtils.checkIntentAction(
571 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
572 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
573 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700574 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700575 eq(dpms.mHandler),
576 eq(Activity.RESULT_OK),
577 isNull(String.class),
578 isNull(Bundle.class));
579
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700580 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700581
582 // Again broadcast from saveSettingsLocked().
583 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
584 MockUtils.checkIntentAction(
585 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
586 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
587
588 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700589 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700590
591 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000592 * Test for: @{link DevicePolicyManager#setActivePasswordState}
593 *
594 * Validates that when the password for a user changes, the notification broadcast intent
595 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
596 * addition to ones in the original user.
597 */
598 public void testSetActivePasswordState_sendToProfiles() throws Exception {
599 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
600
601 final int MANAGED_PROFILE_USER_ID = 78;
602 final int MANAGED_PROFILE_ADMIN_UID =
603 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
604
605 // Setup device owner.
606 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
607 mContext.packageName = admin1.getPackageName();
608 setupDeviceOwner();
609
610 // Add a managed profile belonging to the system user.
611 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
612
613 // Change the parent user's password.
614 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
615
616 // Both the device owner and the managed profile owner should receive this broadcast.
617 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
618 intent.setComponent(admin1);
619 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
620
621 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
622 MockUtils.checkIntent(intent),
623 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
624 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
625 MockUtils.checkIntent(intent),
626 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
627 }
628
629 /**
630 * Test for: @{link DevicePolicyManager#setActivePasswordState}
631 *
632 * Validates that when the password for a managed profile changes, the notification broadcast
633 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
634 * its parent.
635 */
636 public void testSetActivePasswordState_notSentToParent() throws Exception {
637 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
638
639 final int MANAGED_PROFILE_USER_ID = 78;
640 final int MANAGED_PROFILE_ADMIN_UID =
641 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
642
643 // Setup device owner.
644 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
645 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100646 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000647 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
648 setupDeviceOwner();
649
650 // Add a managed profile belonging to the system user.
651 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
652
653 // Change the profile's password.
654 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
655
656 // Both the device owner and the managed profile owner should receive this broadcast.
657 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
658 intent.setComponent(admin1);
659 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
660
661 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
662 MockUtils.checkIntent(intent),
663 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
664 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
665 MockUtils.checkIntent(intent),
666 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
667 }
668 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000669 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700670 */
671 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000672 setDeviceOwner();
673
674 // Try to set a profile owner on the same user, which should fail.
675 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
676 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100677 assertExpectException(IllegalStateException.class,
678 /* messageRegex= */ "already has a device owner",
679 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000680
681 // DO admin can't be deactivated.
682 dpm.removeActiveAdmin(admin1);
683 assertTrue(dpm.isAdminActive(admin1));
684
685 // TODO Test getDeviceOwnerName() too. To do so, we need to change
686 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
687 }
688
689 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700690 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800691 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700692 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
693 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
694
Makoto Onukid932f762015-09-29 16:53:38 -0700695 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700696 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
697
Makoto Onukid932f762015-09-29 16:53:38 -0700698 // Make sure admin1 is installed on system user.
699 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700700
Makoto Onukic8a5a552015-11-19 14:29:12 -0800701 // Check various get APIs.
702 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
703
Makoto Onukib643fb02015-09-22 15:03:44 -0700704 // DO needs to be an DA.
705 dpm.setActiveAdmin(admin1, /* replace =*/ false);
706
707 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700708 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700709
Makoto Onukic8a5a552015-11-19 14:29:12 -0800710 // getDeviceOwnerComponent should return the admin1 component.
711 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
712 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
713
714 // Check various get APIs.
715 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
716
717 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
718 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
719 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
720 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
721
722 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
723
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000724 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100725 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000726 eq(admin1.getPackageName()));
727
Makoto Onukib643fb02015-09-22 15:03:44 -0700728 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100729 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700730 eq(UserHandle.USER_SYSTEM), eq(false));
731
732 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
733 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
734 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
735
Makoto Onukic8a5a552015-11-19 14:29:12 -0800736 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700737 }
738
Makoto Onukic8a5a552015-11-19 14:29:12 -0800739 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
740 final int origCallingUser = mContext.binder.callingUid;
741 final List origPermissions = new ArrayList(mContext.callerPermissions);
742 mContext.callerPermissions.clear();
743
744 mContext.callerPermissions.add(permission.MANAGE_USERS);
745
746 mContext.binder.callingUid = Process.SYSTEM_UID;
747
748 // TODO Test getDeviceOwnerName() too. To do so, we need to change
749 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
750 if (hasDeviceOwner) {
751 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
752 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
753 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
754
755 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
756 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
757 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
758 } else {
759 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
760 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
761 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
762
763 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
764 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
765 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
766 }
767
768 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
769 if (hasDeviceOwner) {
770 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
771 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
772 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
773
774 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
775 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
776 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
777 } else {
778 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
779 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
780 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
781
782 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
783 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
784 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
785 }
786
787 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
788 // Still with MANAGE_USERS.
789 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
790 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
791 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
792
793 if (hasDeviceOwner) {
794 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
795 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
796 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
797 } else {
798 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
799 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
800 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
801 }
802
803 mContext.binder.callingUid = Process.SYSTEM_UID;
804 mContext.callerPermissions.remove(permission.MANAGE_USERS);
805 // System can still call "OnAnyUser" without MANAGE_USERS.
806 if (hasDeviceOwner) {
807 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
808 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
809 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
810
811 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
812 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
813 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
814 } else {
815 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
816 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
817 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
818
819 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
820 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
821 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
822 }
823
824 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
825 // Still no MANAGE_USERS.
826 if (hasDeviceOwner) {
827 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
828 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
829 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
830 } else {
831 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
832 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
833 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
834 }
835
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100836 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
837 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
838 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
839 dpm::getDeviceOwnerComponentOnAnyUser);
840 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
841 dpm::getDeviceOwnerUserId);
842 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
843 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800844
845 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
846 // Still no MANAGE_USERS.
847 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
848 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
849 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
850
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100851 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
852 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
853 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
854 dpm::getDeviceOwnerComponentOnAnyUser);
855 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
856 dpm::getDeviceOwnerUserId);
857 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
858 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800859
860 // Restore.
861 mContext.binder.callingUid = origCallingUser;
862 mContext.callerPermissions.addAll(origPermissions);
863 }
864
865
Makoto Onukib643fb02015-09-22 15:03:44 -0700866 /**
867 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
868 */
869 public void testSetDeviceOwner_noSuchPackage() {
870 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800871 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700872 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
873 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
874
875 // Call from a process on the system user.
876 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
877
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100878 assertExpectException(IllegalArgumentException.class,
879 /* messageRegex= */ "Invalid component",
880 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -0700881 }
882
883 public void testSetDeviceOwner_failures() throws Exception {
884 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
885 }
886
Makoto Onukia52562c2015-10-01 16:12:31 -0700887 public void testClearDeviceOwner() throws Exception {
888 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800889 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700890 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
891 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
892
893 // Set admin1 as a DA to the secondary user.
894 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
895
896 dpm.setActiveAdmin(admin1, /* replace =*/ false);
897
898 // Set admin 1 as the DO to the system user.
899
900 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
901 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
902 dpm.setActiveAdmin(admin1, /* replace =*/ false);
903 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
904
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000905 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100906 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000907 eq(admin1.getPackageName()));
908
Makoto Onukic8a5a552015-11-19 14:29:12 -0800909 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700910
Makoto Onuki90b89652016-01-28 14:44:18 -0800911 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100912 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000913 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800914
915 assertTrue(dpm.isAdminActive(admin1));
916 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
917
Makoto Onukia52562c2015-10-01 16:12:31 -0700918 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100919 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -0700920
921 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100922 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
923 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800924
925 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100926 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100927 assertExpectException(IllegalStateException.class,
928 /* messageRegex= */ "User must be running and unlocked",
929 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800930
Pavel Grafov75c0a892017-05-18 17:28:27 +0100931 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
932 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700933 dpm.clearDeviceOwnerApp(admin1.getPackageName());
934
935 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800936 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700937
Pavel Grafov75c0a892017-05-18 17:28:27 +0100938 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000939 eq(false),
940 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
941
Pavel Grafov75c0a892017-05-18 17:28:27 +0100942 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -0800943 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100944 eq(null),
945 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800946
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700947 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100948
949 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
950 // and once for clearing it.
951 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
952 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
953 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700954 // TODO Check other calls.
955 }
956
957 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
958 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800959 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700960 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
961 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
962
963 // Set admin1 as a DA to the secondary user.
964 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
965
966 dpm.setActiveAdmin(admin1, /* replace =*/ false);
967
968 // Set admin 1 as the DO to the system user.
969
970 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
971 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
972 dpm.setActiveAdmin(admin1, /* replace =*/ false);
973 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
974
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000975 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100976 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000977 eq(admin1.getPackageName()));
978
Makoto Onukic8a5a552015-11-19 14:29:12 -0800979 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700980
981 // Now call clear from the secondary user, which should throw.
982 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
983
984 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100985 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700986 eq(admin1.getPackageName()),
987 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100988 assertExpectException(SecurityException.class,
989 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
990 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -0700991
Makoto Onukic8a5a552015-11-19 14:29:12 -0800992 // DO shouldn't be removed.
993 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700994 }
995
Makoto Onukib643fb02015-09-22 15:03:44 -0700996 public void testSetProfileOwner() throws Exception {
997 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700998
Makoto Onuki90b89652016-01-28 14:44:18 -0800999 // PO admin can't be deactivated.
1000 dpm.removeActiveAdmin(admin1);
1001 assertTrue(dpm.isAdminActive(admin1));
1002
Makoto Onuki803d6752015-10-30 12:58:39 -07001003 // Try setting DO on the same user, which should fail.
1004 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001005 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1006 runAsCaller(mServiceContext, dpms, dpm -> {
1007 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001008 assertExpectException(IllegalStateException.class,
1009 /* messageRegex= */ "already has a profile owner",
1010 () -> dpm.setDeviceOwner(admin2, "owner-name",
1011 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001012 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001013 }
1014
Makoto Onuki90b89652016-01-28 14:44:18 -08001015 public void testClearProfileOwner() throws Exception {
1016 setAsProfileOwner(admin1);
1017
1018 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1019
1020 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1021 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1022
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001023 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001024 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001025 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001026 assertExpectException(IllegalStateException.class,
1027 /* messageRegex= */ "User must be running and unlocked",
1028 () -> dpm.clearProfileOwner(admin1));
1029
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001030 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001031 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001032 dpm.clearProfileOwner(admin1);
1033
1034 // Check
1035 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001036 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001037 }
1038
Makoto Onukib643fb02015-09-22 15:03:44 -07001039 public void testSetProfileOwner_failures() throws Exception {
1040 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1041 }
1042
Makoto Onukia52562c2015-10-01 16:12:31 -07001043 public void testGetDeviceOwnerAdminLocked() throws Exception {
1044 checkDeviceOwnerWithMultipleDeviceAdmins();
1045 }
1046
1047 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1048 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1049 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1050 // make sure it gets the right component from the right user.
1051
1052 final int ANOTHER_USER_ID = 100;
1053 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1054
Pavel Grafov75c0a892017-05-18 17:28:27 +01001055 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001056
1057 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001058 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001059 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1060 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1061
1062 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1063
Pavel Grafov75c0a892017-05-18 17:28:27 +01001064 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001065
Makoto Onukia52562c2015-10-01 16:12:31 -07001066 // Make sure the admin packge is installed to each user.
1067 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1068 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1069
1070 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1071 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1072
1073 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1074
1075
1076 // Set active admins to the users.
1077 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1078 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1079
1080 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1081 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1082
1083 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1084
1085 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001086 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001087 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1088
Makoto Onukic8a5a552015-11-19 14:29:12 -08001089 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001090
1091 // Then check getDeviceOwnerAdminLocked().
1092 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1093 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1094 }
1095
1096 /**
1097 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001098 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1099 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001100 *
1101 * We didn't use to persist the DO component class name, but now we do, and the above method
1102 * finds the right component from a package name upon migration.
1103 */
1104 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001105 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001106 checkDeviceOwnerWithMultipleDeviceAdmins();
1107
1108 // Overwrite the device owner setting and clears the clas name.
1109 dpms.mOwners.setDeviceOwner(
1110 new ComponentName(admin2.getPackageName(), ""),
1111 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1112 dpms.mOwners.writeDeviceOwner();
1113
1114 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001115 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001116
1117 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001118 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001119 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001120 initializeDpms();
1121
1122 // Now the DO component name is a full name.
1123 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1124 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001125 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001126 }
1127
Makoto Onukib643fb02015-09-22 15:03:44 -07001128 public void testSetGetApplicationRestriction() {
1129 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001130 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001131
1132 {
1133 Bundle rest = new Bundle();
1134 rest.putString("KEY_STRING", "Foo1");
1135 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1136 }
1137
1138 {
1139 Bundle rest = new Bundle();
1140 rest.putString("KEY_STRING", "Foo2");
1141 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1142 }
1143
1144 {
1145 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1146 assertNotNull(returned);
1147 assertEquals(returned.size(), 1);
1148 assertEquals(returned.get("KEY_STRING"), "Foo1");
1149 }
1150
1151 {
1152 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1153 assertNotNull(returned);
1154 assertEquals(returned.size(), 1);
1155 assertEquals(returned.get("KEY_STRING"), "Foo2");
1156 }
1157
1158 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1159 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1160 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001161
Edman Anjosf9946772016-11-28 16:35:15 +01001162 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001163 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1164 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001165 *
1166 * @param packageName the name of the package to be setup
1167 * @param appId the application ID to be given to the package
1168 * @return the UID of the package as known by the mock package manager
1169 */
1170 private int setupPackageInPackageManager(final String packageName, final int appId)
1171 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001172 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001173 ApplicationInfo.FLAG_HAS_CODE);
1174 }
1175
1176 /**
1177 * Setup a package in the package manager mock. Useful for faking installed applications.
1178 *
1179 * @param packageName the name of the package to be setup
1180 * @param userId the user id where the package will be "installed"
1181 * @param appId the application ID to be given to the package
1182 * @param flags flags to set in the ApplicationInfo for this package
1183 * @return the UID of the package as known by the mock package manager
1184 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001185 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1186 int flags) throws Exception {
1187 final int uid = UserHandle.getUid(userId, appId);
1188 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001189 final PackageInfo pi = new PackageInfo();
1190 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001191 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001192 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001193 eq(packageName),
1194 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001195 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001196 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001197 eq(packageName),
1198 anyInt(),
1199 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001200 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001201 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001202 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001203 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001204 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001205 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001206 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001207 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001208 return uid;
1209 }
1210
Robin Lee7f5c91c2017-02-08 21:27:02 +00001211 public void testCertificateDisclosure() throws Exception {
1212 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1213 final UserHandle user = UserHandle.of(userId);
1214
1215 mContext.applicationInfo = new ApplicationInfo();
1216 mContext.callerPermissions.add(permission.MANAGE_USERS);
1217 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001218 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001219 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1220
Robin Leeabaa0692017-02-20 20:54:22 +00001221 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1222 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001223
1224 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1225 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1226
1227 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001228 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001229 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001230 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001231 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001232 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001233 .cancelAsUser(anyString(), anyInt(), eq(user));
1234
1235 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001236 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001237 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001238 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1239 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001240 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001241 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001242 .notifyAsUser(anyString(), anyInt(), argThat(
1243 new BaseMatcher<Notification>() {
1244 @Override
1245 public boolean matches(Object item) {
1246 final Notification noti = (Notification) item;
1247 return TEST_STRING.equals(
1248 noti.extras.getString(Notification.EXTRA_TITLE));
1249 }
1250 @Override
1251 public void describeTo(Description description) {
1252 description.appendText(
1253 "Notification{title=\"" + TEST_STRING + "\"}");
1254 }
1255 }), eq(user));
1256 }
1257
Edman Anjosf9946772016-11-28 16:35:15 +01001258 /**
1259 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1260 * privileges can acually be exercised by a delegate are not covered here.
1261 */
1262 public void testDelegation() throws Exception {
1263 setAsProfileOwner(admin1);
1264
1265 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1266
1267 // Given two packages
1268 final String CERT_DELEGATE = "com.delegate.certs";
1269 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1270 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1271 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1272 20989);
1273
1274 // On delegation
1275 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1276 mContext.packageName = admin1.getPackageName();
1277 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1278 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1279
1280 // DPMS correctly stores and retrieves the delegates
1281 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1282 assertEquals(2, policy.mDelegationMap.size());
1283 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1284 DELEGATION_CERT_INSTALL);
1285 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1286 DELEGATION_CERT_INSTALL);
1287 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1288 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1289 DELEGATION_APP_RESTRICTIONS);
1290 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1291 DELEGATION_APP_RESTRICTIONS);
1292 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1293
1294 // On calling install certificate APIs from an unauthorized process
1295 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1296 mContext.packageName = RESTRICTIONS_DELEGATE;
1297
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001298 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1299 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001300
1301 // On calling install certificate APIs from an authorized process
1302 mContext.binder.callingUid = CERT_DELEGATE_UID;
1303 mContext.packageName = CERT_DELEGATE;
1304
1305 // DPMS executes without a SecurityException
1306 try {
1307 dpm.installCaCert(null, null);
1308 } catch (SecurityException unexpected) {
1309 fail("Threw SecurityException on authorized access");
1310 } catch (NullPointerException expected) {
1311 }
1312
1313 // On removing a delegate
1314 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1315 mContext.packageName = admin1.getPackageName();
1316 dpm.setCertInstallerPackage(admin1, null);
1317
1318 // DPMS does not allow access to ex-delegate
1319 mContext.binder.callingUid = CERT_DELEGATE_UID;
1320 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001321 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1322 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001323
1324 // But still allows access to other existing delegates
1325 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1326 mContext.packageName = RESTRICTIONS_DELEGATE;
1327 try {
1328 dpm.getApplicationRestrictions(null, "pkg");
1329 } catch (SecurityException expected) {
1330 fail("Threw SecurityException on authorized access");
1331 }
1332 }
1333
Esteban Talaverabf60f722015-12-10 16:26:44 +00001334 public void testApplicationRestrictionsManagingApp() throws Exception {
1335 setAsProfileOwner(admin1);
1336
Rubin Xued1928a2016-02-11 17:23:06 +00001337 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001338 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001339 final String nonDelegateExceptionMessageRegex =
1340 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001341 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001342 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1343 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001344
Esteban Talaverabf60f722015-12-10 16:26:44 +00001345 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1346 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001347 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1348 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001349 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001350 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001351 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001352 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1353 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001354
1355 // Check via the profile owner that no restrictions were set.
1356 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001357 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001358 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1359
Rubin Xued1928a2016-02-11 17:23:06 +00001360 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001361 assertExpectException(PackageManager.NameNotFoundException.class,
1362 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1363 () -> dpm.setApplicationRestrictionsManagingPackage(
1364 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001365
Esteban Talaverabf60f722015-12-10 16:26:44 +00001366 // Let appRestrictionsManagerPackage manage app restrictions
1367 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1368 assertEquals(appRestrictionsManagerPackage,
1369 dpm.getApplicationRestrictionsManagingPackage(admin1));
1370
1371 // Now that package should be able to set and retrieve app restrictions.
1372 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001373 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001374 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1375 dpm.setApplicationRestrictions(null, "pkg1", rest);
1376 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1377 assertEquals(1, returned.size(), 1);
1378 assertEquals("Foo1", returned.get("KEY_STRING"));
1379
1380 // The same app running on a separate user shouldn't be able to manage app restrictions.
1381 mContext.binder.callingUid = UserHandle.getUid(
1382 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1383 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001384 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1385 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001386
1387 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1388 // too.
1389 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001390 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001391 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1392 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1393 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1394
1395 // Removing the ability for the package to manage app restrictions.
1396 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1397 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1398 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001399 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001400 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001401 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1402 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001403 }
1404
Makoto Onukia4f11972015-10-01 13:19:58 -07001405 public void testSetUserRestriction_asDo() throws Exception {
1406 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001407 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001408 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1409 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1410
1411 // First, set DO.
1412
1413 // Call from a process on the system user.
1414 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1415
1416 // Make sure admin1 is installed on system user.
1417 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001418
1419 // Call.
1420 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001421 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001422 UserHandle.USER_SYSTEM));
1423
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001424 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001425 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001426 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001427 DpmTestUtils.assertRestrictions(
1428 DpmTestUtils.newRestrictions(defaultRestrictions),
1429 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1430 );
1431 DpmTestUtils.assertRestrictions(
1432 DpmTestUtils.newRestrictions(defaultRestrictions),
1433 dpm.getUserRestrictions(admin1)
1434 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001435 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001436 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001437 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001438 eq(true) /* isDeviceOwner */,
1439 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001440 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001441 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001442
1443 for (String restriction : defaultRestrictions) {
1444 dpm.clearUserRestriction(admin1, restriction);
1445 }
1446
Esteban Talavera548a04b2016-12-20 15:22:30 +00001447 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001448 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449
1450 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001451 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001452 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001453 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1454 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001455 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001456
Makoto Onukia4f11972015-10-01 13:19:58 -07001457 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001458 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001459 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001460 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1461 UserManager.DISALLOW_ADD_USER),
1462 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001463 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001464
Makoto Onuki068c54a2015-10-13 14:34:03 -07001465 DpmTestUtils.assertRestrictions(
1466 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001467 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001468 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1469 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001470 DpmTestUtils.assertRestrictions(
1471 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001472 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001473 dpm.getUserRestrictions(admin1)
1474 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001475
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001476 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001477 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001478 eq(UserHandle.USER_SYSTEM),
1479 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001480 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001481 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001482
Makoto Onuki068c54a2015-10-13 14:34:03 -07001483 DpmTestUtils.assertRestrictions(
1484 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1485 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1486 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001487 DpmTestUtils.assertRestrictions(
1488 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1489 dpm.getUserRestrictions(admin1)
1490 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001491
1492 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001493 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001494 eq(UserHandle.USER_SYSTEM),
1495 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001496 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001497 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001498
Esteban Talavera548a04b2016-12-20 15:22:30 +00001499 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001500
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001501 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1502 // DO sets them, the scope is global.
1503 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001504 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001505 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001506 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001507 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001508 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001509 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1510 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001511 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001512
1513 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1514 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001515 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001516
1517 // More tests.
1518 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001519 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001520 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001521 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1522 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001523 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001524
1525 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001526 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001527 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001528 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001529 UserManager.DISALLOW_ADD_USER),
1530 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001531 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001532
1533 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001534 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001535 eq(UserHandle.USER_SYSTEM),
1536 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001537 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001538 UserManager.DISALLOW_ADD_USER),
1539 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001540 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001541
1542 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1543 // locally.
1544 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001545 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001546
1547 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1548 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1549 dpm.setCameraDisabled(admin2, true);
1550
Pavel Grafov75c0a892017-05-18 17:28:27 +01001551 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001552 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001553 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001554 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001555 UserManager.DISALLOW_ADD_USER),
1556 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001557 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001558 // TODO Make sure restrictions are written to the file.
1559 }
1560
1561 public void testSetUserRestriction_asPo() {
1562 setAsProfileOwner(admin1);
1563
Makoto Onuki068c54a2015-10-13 14:34:03 -07001564 DpmTestUtils.assertRestrictions(
1565 DpmTestUtils.newRestrictions(),
1566 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1567 .ensureUserRestrictions()
1568 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001569
1570 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001571 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001572 eq(DpmMockContext.CALLER_USER_HANDLE),
1573 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001574 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001575 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001576
Makoto Onukia4f11972015-10-01 13:19:58 -07001577 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001578 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001579 eq(DpmMockContext.CALLER_USER_HANDLE),
1580 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1581 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001582 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001583 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001584
Makoto Onuki068c54a2015-10-13 14:34:03 -07001585 DpmTestUtils.assertRestrictions(
1586 DpmTestUtils.newRestrictions(
1587 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1588 UserManager.DISALLOW_OUTGOING_CALLS
1589 ),
1590 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1591 .ensureUserRestrictions()
1592 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001593 DpmTestUtils.assertRestrictions(
1594 DpmTestUtils.newRestrictions(
1595 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1596 UserManager.DISALLOW_OUTGOING_CALLS
1597 ),
1598 dpm.getUserRestrictions(admin1)
1599 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001600
1601 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001602 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001603 eq(DpmMockContext.CALLER_USER_HANDLE),
1604 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001605 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001606 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001607
1608 DpmTestUtils.assertRestrictions(
1609 DpmTestUtils.newRestrictions(
1610 UserManager.DISALLOW_OUTGOING_CALLS
1611 ),
1612 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1613 .ensureUserRestrictions()
1614 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001615 DpmTestUtils.assertRestrictions(
1616 DpmTestUtils.newRestrictions(
1617 UserManager.DISALLOW_OUTGOING_CALLS
1618 ),
1619 dpm.getUserRestrictions(admin1)
1620 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001621
1622 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001623 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001624 eq(DpmMockContext.CALLER_USER_HANDLE),
1625 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001626 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001627 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001628
Makoto Onuki068c54a2015-10-13 14:34:03 -07001629 DpmTestUtils.assertRestrictions(
1630 DpmTestUtils.newRestrictions(),
1631 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1632 .ensureUserRestrictions()
1633 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001634 DpmTestUtils.assertRestrictions(
1635 DpmTestUtils.newRestrictions(),
1636 dpm.getUserRestrictions(admin1)
1637 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001638
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001639 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1640 // though when DO sets them they'll be applied globally.
1641 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001642 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001643 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001644 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001645 eq(DpmMockContext.CALLER_USER_HANDLE),
1646 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1647 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001648 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001649 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650
1651 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001652 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001654 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001655 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001656 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001657 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001658
Makoto Onukia4f11972015-10-01 13:19:58 -07001659 // TODO Make sure restrictions are written to the file.
1660 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001661
Esteban Talavera548a04b2016-12-20 15:22:30 +00001662
1663 public void testDefaultEnabledUserRestrictions() throws Exception {
1664 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1665 mContext.callerPermissions.add(permission.MANAGE_USERS);
1666 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1667 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1668
1669 // First, set DO.
1670
1671 // Call from a process on the system user.
1672 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1673
1674 // Make sure admin1 is installed on system user.
1675 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1676
1677 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1678 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1679 UserHandle.USER_SYSTEM));
1680
1681 // Check that the user restrictions that are enabled by default are set. Then unset them.
1682 String[] defaultRestrictions = UserRestrictionsUtils
1683 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1684 assertTrue(defaultRestrictions.length > 0);
1685 DpmTestUtils.assertRestrictions(
1686 DpmTestUtils.newRestrictions(defaultRestrictions),
1687 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1688 );
1689 DpmTestUtils.assertRestrictions(
1690 DpmTestUtils.newRestrictions(defaultRestrictions),
1691 dpm.getUserRestrictions(admin1)
1692 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001693 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001694 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001695 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001696 eq(true) /* isDeviceOwner */,
1697 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001698 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001699 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001700
1701 for (String restriction : defaultRestrictions) {
1702 dpm.clearUserRestriction(admin1, restriction);
1703 }
1704
1705 assertNoDeviceOwnerRestrictions();
1706
1707 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001708 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001709 initializeDpms();
1710 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1711 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1712
1713 assertNoDeviceOwnerRestrictions();
1714
1715 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1716 // is set as it wasn't enabled during setDeviceOwner.
1717 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1718 assertFalse(UserRestrictionsUtils
1719 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1720 UserRestrictionsUtils
1721 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1722 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001723 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001724 initializeDpms();
1725 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1726 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1727
1728 DpmTestUtils.assertRestrictions(
1729 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1730 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1731 );
1732 DpmTestUtils.assertRestrictions(
1733 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1734 dpm.getUserRestrictions(admin1)
1735 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001736 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001737 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001738 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001739 eq(true) /* isDeviceOwner */,
1740 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001741 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001742 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001743
1744 // Remove the restriction.
1745 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1746
1747 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1748 initializeDpms();
1749 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1750 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1751 assertNoDeviceOwnerRestrictions();
1752 } finally {
1753 UserRestrictionsUtils
1754 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1755 }
1756 }
1757
1758 private void assertNoDeviceOwnerRestrictions() {
1759 DpmTestUtils.assertRestrictions(
1760 DpmTestUtils.newRestrictions(),
1761 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1762 );
1763 DpmTestUtils.assertRestrictions(
1764 DpmTestUtils.newRestrictions(),
1765 dpm.getUserRestrictions(admin1)
1766 );
1767 }
1768
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001769 public void testGetMacAddress() throws Exception {
1770 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1771 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1772 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1773
1774 // In this test, change the caller user to "system".
1775 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1776
1777 // Make sure admin1 is installed on system user.
1778 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1779
1780 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001781 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1782 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001783
1784 // DO needs to be an DA.
1785 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1786 assertTrue(dpm.isAdminActive(admin1));
1787
1788 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001789 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1790 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001791
1792 // Test 3. Caller has PO, but not DO.
1793 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001794 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1795 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001796
1797 // Remove PO.
1798 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001799 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001800 // Test 4, Caller is DO now.
1801 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1802
1803 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001804 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001805
1806 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001807 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001808 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001809
1810 // 4-3. With a real MAC address.
1811 final WifiInfo wi = new WifiInfo();
1812 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001813 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001814 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001815 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001816
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001817 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001818 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1819 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1820
1821 // In this test, change the caller user to "system".
1822 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1823
1824 // Make sure admin1 is installed on system user.
1825 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1826
1827 // Set admin1 as DA.
1828 dpm.setActiveAdmin(admin1, false);
1829 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001830 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1831 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001832
1833 // Set admin1 as PO.
1834 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001835 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1836 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001837
1838 // Remove PO and add DO.
1839 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001840 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001841 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1842
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001843 // admin1 is DO.
1844 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001845 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001846 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001847 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1848 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001849
1850 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001851 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001852 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001853 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1854 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001855
1856 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001857 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001858 dpm.reboot(admin1);
1859 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001860
1861 public void testSetGetSupportText() {
1862 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1863 dpm.setActiveAdmin(admin1, true);
1864 dpm.setActiveAdmin(admin2, true);
1865 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1866
1867 // Null default support messages.
1868 {
1869 assertNull(dpm.getLongSupportMessage(admin1));
1870 assertNull(dpm.getShortSupportMessage(admin1));
1871 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1872 assertNull(dpm.getShortSupportMessageForUser(admin1,
1873 DpmMockContext.CALLER_USER_HANDLE));
1874 assertNull(dpm.getLongSupportMessageForUser(admin1,
1875 DpmMockContext.CALLER_USER_HANDLE));
1876 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1877 }
1878
1879 // Only system can call the per user versions.
1880 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001881 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1882 () -> dpm.getShortSupportMessageForUser(admin1,
1883 DpmMockContext.CALLER_USER_HANDLE));
1884 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1885 () -> dpm.getLongSupportMessageForUser(admin1,
1886 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00001887 }
1888
1889 // Can't set message for admin in another uid.
1890 {
1891 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001892 assertExpectException(SecurityException.class,
1893 /* messageRegex= */ "is not owned by uid",
1894 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00001895 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1896 }
1897
1898 // Set/Get short returns what it sets and other admins text isn't changed.
1899 {
1900 final String supportText = "Some text to test with.";
1901 dpm.setShortSupportMessage(admin1, supportText);
1902 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1903 assertNull(dpm.getLongSupportMessage(admin1));
1904 assertNull(dpm.getShortSupportMessage(admin2));
1905
1906 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1907 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1908 DpmMockContext.CALLER_USER_HANDLE));
1909 assertNull(dpm.getShortSupportMessageForUser(admin2,
1910 DpmMockContext.CALLER_USER_HANDLE));
1911 assertNull(dpm.getLongSupportMessageForUser(admin1,
1912 DpmMockContext.CALLER_USER_HANDLE));
1913 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1914
1915 dpm.setShortSupportMessage(admin1, null);
1916 assertNull(dpm.getShortSupportMessage(admin1));
1917 }
1918
1919 // Set/Get long returns what it sets and other admins text isn't changed.
1920 {
1921 final String supportText = "Some text to test with.\nWith more text.";
1922 dpm.setLongSupportMessage(admin1, supportText);
1923 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1924 assertNull(dpm.getShortSupportMessage(admin1));
1925 assertNull(dpm.getLongSupportMessage(admin2));
1926
1927 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1928 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1929 DpmMockContext.CALLER_USER_HANDLE));
1930 assertNull(dpm.getLongSupportMessageForUser(admin2,
1931 DpmMockContext.CALLER_USER_HANDLE));
1932 assertNull(dpm.getShortSupportMessageForUser(admin1,
1933 DpmMockContext.CALLER_USER_HANDLE));
1934 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1935
1936 dpm.setLongSupportMessage(admin1, null);
1937 assertNull(dpm.getLongSupportMessage(admin1));
1938 }
1939 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001940
phweiss73145f42017-01-17 19:06:38 +01001941 public void testCreateAdminSupportIntent() throws Exception {
1942 // Setup device owner.
1943 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1944 setupDeviceOwner();
1945
1946 // Nonexisting permission returns null
1947 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
1948 assertNull(intent);
1949
1950 // Existing permission that is not set returns null
1951 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1952 assertNull(intent);
1953
1954 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01001955 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01001956 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1957 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1958 .thenReturn(true);
1959 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1960 assertNull(intent);
1961
1962 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01001963 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01001964 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1965 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1966 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
1967 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1968 assertNotNull(intent);
1969 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
1970 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
1971 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001972 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01001973 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
1974 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1975
1976 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
1977 // user restrictions
1978
1979 // Camera is not disabled
1980 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1981 assertNull(intent);
1982
1983 // Camera is disabled
1984 dpm.setCameraDisabled(admin1, true);
1985 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1986 assertNotNull(intent);
1987 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
1988 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1989
1990 // Screen capture is not disabled
1991 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1992 assertNull(intent);
1993
1994 // Screen capture is disabled
1995 dpm.setScreenCaptureDisabled(admin1, true);
1996 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1997 assertNotNull(intent);
1998 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
1999 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2000
2001 // Same checks for different user
2002 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2003 // Camera should be disabled by device owner
2004 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2005 assertNotNull(intent);
2006 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2007 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2008 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2009 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2010 // ScreenCapture should not be disabled by device owner
2011 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2012 assertNull(intent);
2013 }
2014
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002015 /**
2016 * Test for:
2017 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002018 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002019 * {@link DevicePolicyManager#isAffiliatedUser}
2020 */
2021 public void testUserAffiliation() throws Exception {
2022 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2023 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2024 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2025
2026 // Check that the system user is unaffiliated.
2027 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2028 assertFalse(dpm.isAffiliatedUser());
2029
2030 // Set a device owner on the system user. Check that the system user becomes affiliated.
2031 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2032 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2033 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2034 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002035 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002036
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002037 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002038 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2039 setAsProfileOwner(admin2);
2040 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002041 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002042
2043 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2044 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002045 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002046 userAffiliationIds.add("red");
2047 userAffiliationIds.add("green");
2048 userAffiliationIds.add("blue");
2049 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002050 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002051 assertFalse(dpm.isAffiliatedUser());
2052
2053 // Have the device owner specify a set of affiliation ids that do not intersect with those
2054 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002055 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002056 deviceAffiliationIds.add("cyan");
2057 deviceAffiliationIds.add("yellow");
2058 deviceAffiliationIds.add("magenta");
2059 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2060 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002061 MoreAsserts.assertContentsInAnyOrder(
2062 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002063 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2064 assertFalse(dpm.isAffiliatedUser());
2065
2066 // Have the profile owner specify a set of affiliation ids that intersect with those
2067 // specified by the device owner. Check that the test user becomes affiliated.
2068 userAffiliationIds.add("yellow");
2069 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002070 MoreAsserts.assertContentsInAnyOrder(
2071 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002072 assertTrue(dpm.isAffiliatedUser());
2073
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002074 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002075 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002076 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002077 assertFalse(dpm.isAffiliatedUser());
2078
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002079 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2080 dpm.setAffiliationIds(admin2, userAffiliationIds);
2081 assertTrue(dpm.isAffiliatedUser());
2082 dpm.clearProfileOwner(admin2);
2083 assertFalse(dpm.isAffiliatedUser());
2084
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002085 // Check that the system user remains affiliated.
2086 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2087 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002088
2089 // Clear the device owner - the user becomes unaffiliated.
2090 clearDeviceOwner();
2091 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002092 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002093
2094 public void testGetUserProvisioningState_defaultResult() {
2095 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2096 }
2097
2098 public void testSetUserProvisioningState_permission() throws Exception {
2099 setupProfileOwner();
2100 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2101
2102 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2103 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2104 }
2105
2106 public void testSetUserProvisioningState_unprivileged() throws Exception {
2107 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002108 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2109 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2110 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002111 }
2112
2113 public void testSetUserProvisioningState_noManagement() {
2114 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002115 assertExpectException(IllegalStateException.class,
2116 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2117 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2118 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002119 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2120 }
2121
2122 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2123 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2124 setupDeviceOwner();
2125 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2126
2127 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2128 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2129 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2130 }
2131
2132 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2133 throws Exception {
2134 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2135 setupDeviceOwner();
2136 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2137
2138 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2139 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2140 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2141 }
2142
2143 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2144 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2145 setupDeviceOwner();
2146 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2147
2148 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2149 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2150 }
2151
2152 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2153 throws Exception {
2154 setupProfileOwner();
2155 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2156
2157 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2158 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2159 DevicePolicyManager.STATE_USER_UNMANAGED);
2160 }
2161
2162 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2163 throws Exception {
2164 setupProfileOwner();
2165 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2166
2167 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2168 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2169 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2170 }
2171
2172 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2173 setupProfileOwner();
2174 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2175
2176 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2177 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2178 }
2179
2180 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2181 setupProfileOwner();
2182 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2183
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002184 assertExpectException(IllegalStateException.class,
2185 /* messageRegex= */ "Cannot move to user provisioning state",
2186 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2187 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2188 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002189 }
2190
2191 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2192 throws Exception {
2193 setupProfileOwner();
2194 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2195
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002196 assertExpectException(IllegalStateException.class,
2197 /* messageRegex= */ "Cannot move to user provisioning state",
2198 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2199 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2200 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002201 }
2202
2203 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2204 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2205 for (int state : states) {
2206 dpm.setUserProvisioningState(state, userId);
2207 assertEquals(state, dpm.getUserProvisioningState());
2208 }
2209 }
2210
2211 private void setupProfileOwner() throws Exception {
2212 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2213
2214 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2215 dpm.setActiveAdmin(admin1, false);
2216 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2217
2218 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2219 }
2220
2221 private void setupDeviceOwner() throws Exception {
2222 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2223
2224 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2225 dpm.setActiveAdmin(admin1, false);
2226 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2227
2228 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2229 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002230
2231 public void testSetMaximumTimeToLock() {
2232 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2233
2234 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2235 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2236
Pavel Grafov75c0a892017-05-18 17:28:27 +01002237 reset(getServices().powerManagerInternal);
2238 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002239
2240 dpm.setMaximumTimeToLock(admin1, 0);
2241 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002242 reset(getServices().powerManagerInternal);
2243 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002244
2245 dpm.setMaximumTimeToLock(admin1, 1);
2246 verifyScreenTimeoutCall(1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002247 reset(getServices().powerManagerInternal);
2248 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002249
2250 dpm.setMaximumTimeToLock(admin2, 10);
2251 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002252 reset(getServices().powerManagerInternal);
2253 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002254
2255 dpm.setMaximumTimeToLock(admin1, 5);
2256 verifyScreenTimeoutCall(5, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002257 reset(getServices().powerManagerInternal);
2258 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002259
2260 dpm.setMaximumTimeToLock(admin2, 4);
2261 verifyScreenTimeoutCall(4, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002262 reset(getServices().powerManagerInternal);
2263 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002264
2265 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002266 reset(getServices().powerManagerInternal);
2267 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002268
2269 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2270 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002271 reset(getServices().powerManagerInternal);
2272 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002273
2274 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2275 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002276 reset(getServices().powerManagerInternal);
2277 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002278
2279 dpm.setMaximumTimeToLock(admin2, 10);
2280 verifyScreenTimeoutCall(10, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002281 reset(getServices().powerManagerInternal);
2282 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002283
2284 // There's no restriction; shold be set to MAX.
2285 dpm.setMaximumTimeToLock(admin2, 0);
2286 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2287 }
2288
Michal Karpinski943aabd2016-10-06 11:09:25 +01002289 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2290 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2291 setupDeviceOwner();
2292 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2293
Michal Karpinskid084ca52017-01-18 15:54:18 +00002294 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2295 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2296 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2297 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2298 - ONE_MINUTE;
2299
2300 // verify that the minimum timeout cannot be modified on user builds (system property is
2301 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002302 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002303
2304 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2305 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2306 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2307
Pavel Grafov75c0a892017-05-18 17:28:27 +01002308 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002309
2310 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002311 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002312
Michal Karpinskid084ca52017-01-18 15:54:18 +00002313 // reset to default (0 means the admin is not participating, so default should be returned)
2314 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002315
2316 // aggregation should be the default if unset by any admin
2317 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2318 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2319
2320 // admin not participating by default
2321 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2322
2323 //clamping from the top
2324 dpm.setRequiredStrongAuthTimeout(admin1,
2325 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2326 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2327 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2328 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2329 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2330
Michal Karpinskid084ca52017-01-18 15:54:18 +00002331 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002332 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2333 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2334 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2335 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2336
2337 // clamping from the bottom
2338 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2339 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2340 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2341
Michal Karpinskid084ca52017-01-18 15:54:18 +00002342 // values within range
2343 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2344 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2345 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2346
2347 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2348 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2349 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002350
2351 // reset to default
2352 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2353 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2354 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2355 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2356
2357 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002358 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2359 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002360 }
2361
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002362 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2363 boolean shouldStayOnWhilePluggedInBeCleared) {
2364 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002365 verify(getServices().powerManagerInternal, times(0))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002366 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2367 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002368 verify(getServices().powerManagerInternal, times(1))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002369 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2370 }
2371 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2372 // UnfinishedVerificationException.
2373 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002374
Esteban Talavera01576862016-12-15 11:16:44 +00002375 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002376 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002377 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002378 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002379 .thenReturn(false);
2380 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002381 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2382 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002383 .thenReturn(true);
2384 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2385
2386 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002387 }
Victor Chang3e794af2016-03-04 13:48:17 +00002388
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002389 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2390 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002391 mContext.packageName = admin1.getPackageName();
2392 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002393 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2394 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2395 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2396 false);
2397 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2398 }
2399
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002400 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2401 setup_DeviceAdminFeatureOff();
2402 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2403 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2404 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2405 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2406 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2407 assertCheckProvisioningPreCondition(
2408 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2409 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2410 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2411 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2412 }
2413
Esteban Talavera01576862016-12-15 11:16:44 +00002414 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002415 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002416 .thenReturn(false);
2417 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002418 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2419 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002420 .thenReturn(true);
2421 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2422
2423 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002424 }
Victor Chang3e794af2016-03-04 13:48:17 +00002425
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002426 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2427 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002428 mContext.packageName = admin1.getPackageName();
2429 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002430 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2431 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2432 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2433 false);
2434 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2435
2436 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002437 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002438 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2439 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2440 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2441 true);
2442 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2443 }
2444
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002445 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2446 setup_ManagedProfileFeatureOff();
2447 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2448 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2449 DevicePolicyManager.CODE_OK);
2450 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2451 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2452 assertCheckProvisioningPreCondition(
2453 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2454 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2455 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2456 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2457
2458 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002459 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002460 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2461 DevicePolicyManager.CODE_OK);
2462 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2463 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2464 assertCheckProvisioningPreCondition(
2465 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2466 DevicePolicyManager.CODE_OK);
2467 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2468 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2469 }
2470
Esteban Talavera01576862016-12-15 11:16:44 +00002471 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002472 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002473 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002474 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2475 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002476 .thenReturn(true);
2477 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2478
2479 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002480 }
Victor Chang3e794af2016-03-04 13:48:17 +00002481
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002482 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2483 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002484 mContext.packageName = admin1.getPackageName();
2485 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002486 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2487 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2488 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2489 false /* because of non-split user */);
2490 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2491 false /* because of non-split user */);
2492 }
2493
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002494 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002495 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002496 setup_nonSplitUser_firstBoot_primaryUser();
2497 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2498 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2499 DevicePolicyManager.CODE_OK);
2500 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2501 DevicePolicyManager.CODE_OK);
2502 assertCheckProvisioningPreCondition(
2503 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2504 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2505 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2506 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2507 }
2508
Esteban Talavera01576862016-12-15 11:16:44 +00002509 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002510 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002511 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002512 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2513 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002514 .thenReturn(true);
2515 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2516
2517 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002518 }
Victor Chang3e794af2016-03-04 13:48:17 +00002519
Nicolas Prevot45d29072017-01-18 16:11:19 +00002520 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2521 setDeviceOwner();
2522 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2523 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2524 }
2525
2526 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2527 setup_nonSplitUser_withDo_primaryUser();
2528 final int MANAGED_PROFILE_USER_ID = 18;
2529 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2530 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002531 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002532 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002533 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002534 true)).thenReturn(true);
2535 }
2536
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002537 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2538 throws Exception {
2539 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002540 mContext.packageName = admin1.getPackageName();
2541 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002542 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2543 false/* because of completed device setup */);
2544 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2545 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2546 false/* because of non-split user */);
2547 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2548 false/* because of non-split user */);
2549 }
2550
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002551 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2552 throws Exception {
2553 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2554 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2555 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2556 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2557 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2558 DevicePolicyManager.CODE_OK);
2559 assertCheckProvisioningPreCondition(
2560 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2561 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2562 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2563 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2564 }
2565
Nicolas Prevot45d29072017-01-18 16:11:19 +00002566 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2567 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002568 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002569 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2570
2571 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2572 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002573 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002574
2575 // COMP mode is allowed.
2576 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2577 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002578 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002579
Nicolas Prevot45d29072017-01-18 16:11:19 +00002580 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002581 assertCheckProvisioningPreCondition(
2582 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002583 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002584 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002585 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2586 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2587 }
Esteban Talavera01576862016-12-15 11:16:44 +00002588
Nicolas Prevot45d29072017-01-18 16:11:19 +00002589 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2590 setup_nonSplitUser_withDo_primaryUser();
2591 mContext.packageName = admin1.getPackageName();
2592 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2593 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2594 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002595 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002596 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2597 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2598 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002599 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002600 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2601 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2602 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2603 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2604 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002605 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002606 assertCheckProvisioningPreCondition(
2607 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002608 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002609 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002610 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2611 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2612 }
Esteban Talavera01576862016-12-15 11:16:44 +00002613
Nicolas Prevot45d29072017-01-18 16:11:19 +00002614 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2615 throws Exception {
2616 setup_nonSplitUser_withDo_primaryUser();
2617 mContext.packageName = admin1.getPackageName();
2618 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002619 // The DO should not be allowed to initiate provisioning if the restriction is set by
2620 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002621 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002622 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2623 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2624 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002625 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002626 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2627 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2628 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2629 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2630 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002631 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2632
2633 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002634 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002635 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002636 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002637 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2638 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2639 }
2640
2641 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2642 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2643 mContext.packageName = admin1.getPackageName();
2644 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2645
2646 // We can delete the managed profile to create a new one, so provisioning is allowed.
2647 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2648 DevicePolicyManager.CODE_OK);
2649 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2650 assertCheckProvisioningPreCondition(
2651 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2652 DpmMockContext.ANOTHER_PACKAGE_NAME,
2653 DevicePolicyManager.CODE_OK);
2654 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2655 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2656 }
2657
2658 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2659 throws Exception {
2660 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2661 mContext.packageName = admin1.getPackageName();
2662 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002663 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002664 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2665 eq(UserHandle.SYSTEM)))
2666 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002667 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002668 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2669 eq(UserHandle.SYSTEM)))
2670 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002671
2672 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002673 assertCheckProvisioningPreCondition(
2674 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2675 DpmMockContext.ANOTHER_PACKAGE_NAME,
2676 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2677 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2678 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002679
2680 // But the device owner can still do it because it has set the restriction itself.
2681 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2682 DevicePolicyManager.CODE_OK);
2683 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002684 }
2685
2686 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002687 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002688 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002689 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2690 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002691 .thenReturn(false);
2692 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2693
2694 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002695 }
Victor Chang3e794af2016-03-04 13:48:17 +00002696
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002697 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2698 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002699 mContext.packageName = admin1.getPackageName();
2700 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002701 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2702 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2703 false /* because canAddMoreManagedProfiles returns false */);
2704 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2705 true);
2706 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2707 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002708 }
2709
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002710 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2711 throws Exception {
2712 setup_splitUser_firstBoot_systemUser();
2713 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2714 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2715 DevicePolicyManager.CODE_OK);
2716 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002717 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002718 assertCheckProvisioningPreCondition(
2719 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2720 DevicePolicyManager.CODE_OK);
2721 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2722 DevicePolicyManager.CODE_SYSTEM_USER);
2723 }
2724
Esteban Talavera01576862016-12-15 11:16:44 +00002725 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002726 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002727 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002728 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2729 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002730 .thenReturn(false);
2731 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2732
2733 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002734 }
Victor Chang3e794af2016-03-04 13:48:17 +00002735
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002736 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2737 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002738 mContext.packageName = admin1.getPackageName();
2739 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002740 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2741 true/* it's undefined behavior. Can be changed into false in the future */);
2742 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2743 false /* because canAddMoreManagedProfiles returns false */);
2744 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2745 true/* it's undefined behavior. Can be changed into false in the future */);
2746 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2747 false/* because calling uid is system user */);
2748 }
2749
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002750 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2751 throws Exception {
2752 setup_splitUser_afterDeviceSetup_systemUser();
2753 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2754 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2755 DevicePolicyManager.CODE_OK);
2756 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002757 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002758 assertCheckProvisioningPreCondition(
2759 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2760 DevicePolicyManager.CODE_OK);
2761 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2762 DevicePolicyManager.CODE_SYSTEM_USER);
2763 }
2764
Esteban Talavera01576862016-12-15 11:16:44 +00002765 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002766 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002767 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002768 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2769 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002770 true)).thenReturn(true);
2771 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2772
2773 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002774 }
Victor Chang3e794af2016-03-04 13:48:17 +00002775
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002776 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2777 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002778 mContext.packageName = admin1.getPackageName();
2779 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002780 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2781 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2782 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2783 true);
2784 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002785 }
2786
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002787 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002788 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002789 setup_splitUser_firstBoot_primaryUser();
2790 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2791 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2792 DevicePolicyManager.CODE_OK);
2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2794 DevicePolicyManager.CODE_OK);
2795 assertCheckProvisioningPreCondition(
2796 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2797 DevicePolicyManager.CODE_OK);
2798 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2799 DevicePolicyManager.CODE_OK);
2800 }
2801
Esteban Talavera01576862016-12-15 11:16:44 +00002802 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002803 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002804 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002805 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2806 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002807 true)).thenReturn(true);
2808 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2809
2810 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002811 }
Victor Chang3e794af2016-03-04 13:48:17 +00002812
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002813 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2814 throws Exception {
2815 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002816 mContext.packageName = admin1.getPackageName();
2817 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002818 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2819 true/* it's undefined behavior. Can be changed into false in the future */);
2820 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2821 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2822 true/* it's undefined behavior. Can be changed into false in the future */);
2823 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2824 false/* because user setup completed */);
2825 }
2826
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002827 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002828 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002829 setup_splitUser_afterDeviceSetup_primaryUser();
2830 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2831 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2832 DevicePolicyManager.CODE_OK);
2833 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2834 DevicePolicyManager.CODE_OK);
2835 assertCheckProvisioningPreCondition(
2836 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2837 DevicePolicyManager.CODE_OK);
2838 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2839 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2840 }
2841
Esteban Talavera01576862016-12-15 11:16:44 +00002842 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002843 setDeviceOwner();
2844
Pavel Grafov75c0a892017-05-18 17:28:27 +01002845 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002846 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002847 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2848 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002849 .thenReturn(false);
2850 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2851
2852 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002853 }
Victor Chang3e794af2016-03-04 13:48:17 +00002854
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002855 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2856 throws Exception {
2857 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002858 mContext.packageName = admin1.getPackageName();
2859 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002860 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2861 false /* can't provision managed profile on system user */);
2862 }
2863
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002864 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002865 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002866 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2867 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2868 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2869 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2870 }
2871
2872 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002873 setDeviceOwner();
2874
Pavel Grafov75c0a892017-05-18 17:28:27 +01002875 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002876 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002877 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2878 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002879 true)).thenReturn(true);
2880 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2881
2882 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002883 }
Victor Chang3e794af2016-03-04 13:48:17 +00002884
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002885 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2886 throws Exception {
2887 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002888 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2889 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002890 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2891 }
2892
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002893 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002894 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002895 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2896 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002897
2898 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002899 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2900 DevicePolicyManager.CODE_OK);
2901 }
2902
2903 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002904 setDeviceOwner();
2905
Pavel Grafov75c0a892017-05-18 17:28:27 +01002906 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002907 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002908 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2909 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002910 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2911 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002912 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002913 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002914 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002915 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00002916 true)).thenReturn(true);
2917 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2918
2919 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002920 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002921
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002922 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2923 throws Exception {
2924 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002925 mContext.packageName = admin1.getPackageName();
2926 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002927 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2928 }
2929
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002930 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2931 throws Exception {
2932 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2933 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2934 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2935 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2936 }
2937
2938 public void testCheckProvisioningPreCondition_permission() {
2939 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002940 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2941 () -> dpm.checkProvisioningPreCondition(
2942 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002943 }
2944
Victor Chang3577ed22016-08-25 18:49:26 +01002945 public void testForceUpdateUserSetupComplete_permission() {
2946 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002947 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2948 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01002949 }
2950
2951 public void testForceUpdateUserSetupComplete_systemUser() {
2952 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2953 // GIVEN calling from user 20
2954 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002955 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2956 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01002957 }
2958
2959 public void testForceUpdateUserSetupComplete_userbuild() {
2960 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2961 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2962
2963 final int userId = UserHandle.USER_SYSTEM;
2964 // GIVEN userComplete is false in SettingsProvider
2965 setUserSetupCompleteForUser(false, userId);
2966
2967 // GIVEN userComplete is true in DPM
2968 DevicePolicyManagerService.DevicePolicyData userData =
2969 new DevicePolicyManagerService.DevicePolicyData(userId);
2970 userData.mUserSetupComplete = true;
2971 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2972
2973 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01002974 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01002975
2976 assertTrue(dpms.hasUserSetupCompleted());
2977
2978 dpm.forceUpdateUserSetupComplete();
2979
2980 // THEN the state in dpms is not changed
2981 assertTrue(dpms.hasUserSetupCompleted());
2982 }
2983
2984 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2985 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2986 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2987
2988 final int userId = UserHandle.USER_SYSTEM;
2989 // GIVEN userComplete is false in SettingsProvider
2990 setUserSetupCompleteForUser(false, userId);
2991
2992 // GIVEN userComplete is true in DPM
2993 DevicePolicyManagerService.DevicePolicyData userData =
2994 new DevicePolicyManagerService.DevicePolicyData(userId);
2995 userData.mUserSetupComplete = true;
2996 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2997
2998 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01002999 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003000
3001 assertTrue(dpms.hasUserSetupCompleted());
3002
3003 dpm.forceUpdateUserSetupComplete();
3004
3005 // THEN the state in dpms is not changed
3006 assertFalse(dpms.hasUserSetupCompleted());
3007 }
3008
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003009 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003010 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003011 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003012
3013 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3014 runAsCaller(mAdmin1Context, dpms, dpm -> {
3015 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3016 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003017 }
3018
3019 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3020 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3021 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003022
3023 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3024 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003025 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003026 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3027 .thenReturn(true);
3028
3029 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003030 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003031
3032 // Enabling logging should not change the timestamp.
3033 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003034 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003035 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003036 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003037 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003038 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003039
3040 // Retrieving the logs should update the timestamp.
3041 final long beforeRetrieval = System.currentTimeMillis();
3042 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003043 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003044 final long afterRetrieval = System.currentTimeMillis();
3045 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3046 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3047
3048 // Retrieving the pre-boot logs should update the timestamp.
3049 Thread.sleep(2);
3050 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003051 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003052 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3053
3054 // Checking the timestamp again should not change it.
3055 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003056 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003057
3058 // Retrieving the logs again should update the timestamp.
3059 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003060 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003061 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3062
3063 // Disabling logging should not change the timestamp.
3064 Thread.sleep(2);
3065 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003066 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003067
3068 // Restarting the DPMS should not lose the timestamp.
3069 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003070 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003071
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003072 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3073 mContext.binder.callingUid = 1234567;
3074 mContext.callerPermissions.add(permission.MANAGE_USERS);
3075 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3076 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3077
3078 // System can retrieve the timestamp.
3079 mContext.binder.clearCallingIdentity();
3080 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3081
3082 // Removing the device owner should clear the timestamp.
3083 clearDeviceOwner();
3084 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003085 }
3086
3087 public void testGetLastBugReportRequestTime() throws Exception {
3088 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3089 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003090
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003091 mContext.packageName = admin1.getPackageName();
3092 mContext.applicationInfo = new ApplicationInfo();
3093 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3094 .thenReturn(Color.WHITE);
3095 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3096 anyObject())).thenReturn(Color.WHITE);
3097
Esteban Talaverad36dd152016-12-15 08:51:45 +00003098 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3099 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003100 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003101
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003102 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003103 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003104
3105 // Requesting a bug report should update the timestamp.
3106 final long beforeRequest = System.currentTimeMillis();
3107 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003108 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003109 final long afterRequest = System.currentTimeMillis();
3110 assertTrue(bugReportRequestTime >= beforeRequest);
3111 assertTrue(bugReportRequestTime <= afterRequest);
3112
3113 // Checking the timestamp again should not change it.
3114 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003115 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003116
3117 // Restarting the DPMS should not lose the timestamp.
3118 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003119 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003120
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003121 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3122 mContext.binder.callingUid = 1234567;
3123 mContext.callerPermissions.add(permission.MANAGE_USERS);
3124 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3125 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3126
3127 // System can retrieve the timestamp.
3128 mContext.binder.clearCallingIdentity();
3129 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3130
3131 // Removing the device owner should clear the timestamp.
3132 clearDeviceOwner();
3133 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003134 }
3135
3136 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3137 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3138 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003139 mContext.packageName = admin1.getPackageName();
3140 mContext.applicationInfo = new ApplicationInfo();
3141 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3142 .thenReturn(Color.WHITE);
3143 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3144 anyObject())).thenReturn(Color.WHITE);
3145
3146 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3147 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003148 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
3149 when(getServices().iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003150 .thenReturn(true);
3151
3152 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003153 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003154
3155 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3156 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003157 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003158
3159 // Enabling logging should not change the timestamp.
3160 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003161 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003162
3163 // Retrieving the logs should update the timestamp.
3164 final long beforeRetrieval = System.currentTimeMillis();
3165 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003166 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003167 final long afterRetrieval = System.currentTimeMillis();
3168 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3169 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3170
3171 // Checking the timestamp again should not change it.
3172 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003173 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003174
3175 // Retrieving the logs again should update the timestamp.
3176 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003177 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003178 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3179
3180 // Disabling logging should not change the timestamp.
3181 Thread.sleep(2);
3182 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003183 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003184
3185 // Restarting the DPMS should not lose the timestamp.
3186 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003187 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3188
3189 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3190 mContext.binder.callingUid = 1234567;
3191 mContext.callerPermissions.add(permission.MANAGE_USERS);
3192 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3193 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3194
3195 // System can retrieve the timestamp.
3196 mContext.binder.clearCallingIdentity();
3197 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3198
3199 // Removing the device owner should clear the timestamp.
3200 clearDeviceOwner();
3201 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003202 }
3203
Tony Mak2f26b792016-11-28 17:54:51 +00003204 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3205 // Setup device owner.
3206 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3207 setupDeviceOwner();
3208
3209 // Only device owner is setup, the result list should be empty.
3210 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3211 MoreAsserts.assertEmpty(targetUsers);
3212
3213 // Setup a managed profile managed by the same admin.
3214 final int MANAGED_PROFILE_USER_ID = 15;
3215 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3216 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3217
3218 // Add a secondary user, it should never talk with.
3219 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003220 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003221
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003222 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3223 // other.
3224 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3225 MoreAsserts.assertEmpty(targetUsers);
3226
3227 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3228 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3229 MoreAsserts.assertEmpty(targetUsers);
3230
3231 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003232 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003233 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3234 dpm.setAffiliationIds(admin1, userAffiliationIds);
3235
3236 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3237 dpm.setAffiliationIds(admin1, userAffiliationIds);
3238
Tony Mak2f26b792016-11-28 17:54:51 +00003239 // Calling from device owner admin, the result list should just contain the managed
3240 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003241 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003242 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3243 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3244
3245 // Calling from managed profile admin, the result list should just contain the system
3246 // user id.
3247 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3248 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3249 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003250
3251 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003252 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003253
3254 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3255 // to each other.
3256 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3257 MoreAsserts.assertEmpty(targetUsers);
3258
3259 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3260 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3261 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003262 }
3263
3264 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3265 // Setup a device owner.
3266 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3267 setupDeviceOwner();
3268
3269 // Set up a managed profile managed by different package.
3270 final int MANAGED_PROFILE_USER_ID = 15;
3271 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3272 final ComponentName adminDifferentPackage =
3273 new ComponentName("another.package", "whatever.class");
3274 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3275
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003276 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003277 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003278 dpm.setAffiliationIds(admin1, userAffiliationIds);
3279
3280 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3281 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3282
Tony Mak2f26b792016-11-28 17:54:51 +00003283 // Calling from device owner admin, we should get zero bind device admin target users as
3284 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003285 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003286 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3287 MoreAsserts.assertEmpty(targetUsers);
3288
3289 // Calling from managed profile admin, we should still get zero target users for the same
3290 // reason.
3291 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3292 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3293 MoreAsserts.assertEmpty(targetUsers);
3294 }
3295
Esteban Talaverabdcada92017-02-01 14:20:06 +00003296 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3297 // Setup a device owner.
3298 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3299 setupDeviceOwner();
3300 // Lock task packages are updated when loading user data.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003301 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003302 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3303
3304 // Set up a managed profile managed by different package (package name shouldn't matter)
3305 final int MANAGED_PROFILE_USER_ID = 15;
3306 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3307 final ComponentName adminDifferentPackage =
3308 new ComponentName("another.package", "whatever.class");
3309 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003310 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003311 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3312
3313 // The DO can still set lock task packages
3314 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3315 final String[] doPackages = {"doPackage1", "doPackage2"};
3316 dpm.setLockTaskPackages(admin1, doPackages);
3317 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3318 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3319 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003320 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003321 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3322
3323 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3324 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3325 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003326 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3327 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3328 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3329 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003330 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3331
3332 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003333 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003334 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3335 dpm.setAffiliationIds(admin1, userAffiliationIds);
3336
3337 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3338 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3339
3340 // Now the managed profile can set lock task packages.
3341 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3342 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3343 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3344 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003345 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003346 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3347
3348 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003349 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003350 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3351 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003352 verify(getServices().iactivityManager, times(2))
Esteban Talaverabdcada92017-02-01 14:20:06 +00003353 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3354
3355 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3356 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3357 }
3358
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003359 public void testIsDeviceManaged() throws Exception {
3360 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3361 setupDeviceOwner();
3362
3363 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3364 // find out that the device has a device owner.
3365 assertTrue(dpm.isDeviceManaged());
3366 mContext.binder.callingUid = 1234567;
3367 mContext.callerPermissions.add(permission.MANAGE_USERS);
3368 assertTrue(dpm.isDeviceManaged());
3369 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3370 mContext.binder.clearCallingIdentity();
3371 assertTrue(dpm.isDeviceManaged());
3372
3373 clearDeviceOwner();
3374
3375 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3376 // not have a device owner.
3377 mContext.binder.callingUid = 1234567;
3378 mContext.callerPermissions.add(permission.MANAGE_USERS);
3379 assertFalse(dpm.isDeviceManaged());
3380 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3381 mContext.binder.clearCallingIdentity();
3382 assertFalse(dpm.isDeviceManaged());
3383 }
3384
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003385 public void testDeviceOwnerOrganizationName() throws Exception {
3386 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3387 setupDeviceOwner();
3388
3389 dpm.setOrganizationName(admin1, "organization");
3390
3391 // Device owner can retrieve organization managing the device.
3392 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3393
3394 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3395 mContext.binder.callingUid = 1234567;
3396 mContext.callerPermissions.add(permission.MANAGE_USERS);
3397 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3398 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3399
3400 // System can retrieve organization managing the device.
3401 mContext.binder.clearCallingIdentity();
3402 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3403
3404 // Removing the device owner clears the organization managing the device.
3405 clearDeviceOwner();
3406 assertNull(dpm.getDeviceOwnerOrganizationName());
3407 }
3408
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003409 public void testWipeDataManagedProfile() throws Exception {
3410 final int MANAGED_PROFILE_USER_ID = 15;
3411 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3412 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3413 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3414
3415 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003416 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003417 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3418
3419 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003420 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003421 MANAGED_PROFILE_USER_ID);
3422 }
3423
3424 public void testWipeDataManagedProfileDisallowed() throws Exception {
3425 final int MANAGED_PROFILE_USER_ID = 15;
3426 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3427 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3428
3429 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003430 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003431 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3432
Pavel Grafov75c0a892017-05-18 17:28:27 +01003433 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003434 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3435 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3436 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3437 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003438 // The PO is not allowed to remove the profile if the user restriction was set on the
3439 // profile by the system
3440 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3441 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003442 }
3443
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003444 public void testWipeDataDeviceOwner() throws Exception {
3445 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003446 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003447 UserManager.DISALLOW_FACTORY_RESET,
3448 UserHandle.SYSTEM))
3449 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3450
3451 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003452 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003453 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3454 /*wipeEuicc=*/ eq(false));
3455 }
3456
3457 public void testWipeEuiccDataEnabled() throws Exception {
3458 setDeviceOwner();
3459 when(getServices().userManager.getUserRestrictionSource(
3460 UserManager.DISALLOW_FACTORY_RESET,
3461 UserHandle.SYSTEM))
3462 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3463
3464 dpm.wipeData(WIPE_EUICC);
3465 verify(getServices().recoverySystem).rebootWipeUserData(
3466 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3467 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003468 }
3469
3470 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3471 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003472 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003473 UserManager.DISALLOW_FACTORY_RESET,
3474 UserHandle.SYSTEM))
3475 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003476 // The DO is not allowed to wipe the device if the user restriction was set
3477 // by the system
3478 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3479 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003480 }
3481
3482 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3483 final int MANAGED_PROFILE_USER_ID = 15;
3484 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3485 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3486
3487 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003488 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003489 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3490
Pavel Grafov75c0a892017-05-18 17:28:27 +01003491 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003492 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3493 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3494 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3495
3496 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3497 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3498
3499 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3500 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3501 // Failed password attempts on the parent user are taken into account, as there isn't a
3502 // separate work challenge.
3503 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3504 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3505 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3506
3507 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3508 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003509 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003510 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003511 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003512 }
3513
3514 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3515 throws Exception {
3516 final int MANAGED_PROFILE_USER_ID = 15;
3517 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3518 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3519
3520 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003521 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003522 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3523
Pavel Grafov75c0a892017-05-18 17:28:27 +01003524 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003525 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3526 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3527 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3528
3529 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3530 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3531
3532 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3533 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3534 // Failed password attempts on the parent user are taken into account, as there isn't a
3535 // separate work challenge.
3536 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3537 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3538 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3539
3540 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3541 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003542 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003543 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003544 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003545 }
3546
3547 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3548 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003549 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003550 UserManager.DISALLOW_FACTORY_RESET,
3551 UserHandle.SYSTEM))
3552 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3553
3554 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3555
3556 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3557 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3558 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3559 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3560 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3561
3562 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3563 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003564 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003565 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3566 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003567 }
3568
3569 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3570 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003571 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003572 UserManager.DISALLOW_FACTORY_RESET,
3573 UserHandle.SYSTEM))
3574 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3575
3576 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3577
3578 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3579 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3580 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3581 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3582 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3583
3584 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003585 verifyZeroInteractions(getServices().recoverySystem);
3586 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003587 .removeUserEvenWhenDisallowed(anyInt());
3588 }
3589
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003590 public void testGetPermissionGrantState() throws Exception {
3591 final String permission = "some.permission";
3592 final String app1 = "com.example.app1";
3593 final String app2 = "com.example.app2";
3594
Pavel Grafov75c0a892017-05-18 17:28:27 +01003595 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003596 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003597 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003598 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003599 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003600 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3601 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003602 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003603 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003604 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003605 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003606 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003607 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3608
3609 // System can retrieve permission grant state.
3610 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003611 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003612 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3613 dpm.getPermissionGrantState(null, app1, permission));
3614 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3615 dpm.getPermissionGrantState(null, app2, permission));
3616
3617 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003618 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3619 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003620 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3621 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003622
3623 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003624 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3625 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003626 setAsProfileOwner(admin1);
3627 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3628 dpm.getPermissionGrantState(admin1, app1, permission));
3629 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3630 dpm.getPermissionGrantState(admin1, app2, permission));
3631 }
3632
Rubin Xuaab7a412016-12-30 21:13:29 +00003633 public void testResetPasswordWithToken() throws Exception {
3634 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3635 setupDeviceOwner();
3636 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003637 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3638 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3639
Rubin Xuaab7a412016-12-30 21:13:29 +00003640 // test adding a token
3641 final byte[] token = new byte[32];
3642 final long handle = 123456;
3643 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003644 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003645 .thenReturn(handle);
3646 assertTrue(dpm.setResetPasswordToken(admin1, token));
3647
3648 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003649 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003650 .thenReturn(true);
3651 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3652
3653 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003654 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xuaab7a412016-12-30 21:13:29 +00003655 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3656 eq(UserHandle.USER_SYSTEM)))
3657 .thenReturn(true);
3658 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3659
3660 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003661 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003662 .thenReturn(true);
3663 assertTrue(dpm.clearResetPasswordToken(admin1));
3664 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003665
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003666 public void testIsActivePasswordSufficient() throws Exception {
3667 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3668 mContext.packageName = admin1.getPackageName();
3669 setupDeviceOwner();
3670
3671 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3672 dpm.setPasswordMinimumLength(admin1, 8);
3673 dpm.setPasswordMinimumLetters(admin1, 6);
3674 dpm.setPasswordMinimumLowerCase(admin1, 3);
3675 dpm.setPasswordMinimumUpperCase(admin1, 1);
3676 dpm.setPasswordMinimumNonLetter(admin1, 1);
3677 dpm.setPasswordMinimumNumeric(admin1, 1);
3678 dpm.setPasswordMinimumSymbols(admin1, 0);
3679
3680 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3681 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3682 8, 2,
3683 6, 1,
3684 0, 1);
3685
3686 setActivePasswordState(passwordMetricsNoSymbols);
3687 assertTrue(dpm.isActivePasswordSufficient());
3688
3689 initializeDpms();
3690 reset(mContext.spiedContext);
3691 assertTrue(dpm.isActivePasswordSufficient());
3692
3693 // This call simulates the user entering the password for the first time after a reboot.
3694 // This causes password metrics to be reloaded into memory. Until this happens,
3695 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3696 // even if the DPC changes password requirements so that the password no longer meets the
3697 // requirements. This is a known limitation of the current implementation of
3698 // isActivePasswordSufficient() - see b/34218769.
3699 setActivePasswordState(passwordMetricsNoSymbols);
3700 assertTrue(dpm.isActivePasswordSufficient());
3701
3702 dpm.setPasswordMinimumSymbols(admin1, 1);
3703 // This assertion would fail if we had not called setActivePasswordState() again after
3704 // initializeDpms() - see previous comment.
3705 assertFalse(dpm.isActivePasswordSufficient());
3706
3707 initializeDpms();
3708 reset(mContext.spiedContext);
3709 assertFalse(dpm.isActivePasswordSufficient());
3710
3711 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3712 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3713 7, 2,
3714 5, 1,
3715 1, 2);
3716
3717 setActivePasswordState(passwordMetricsWithSymbols);
3718 assertTrue(dpm.isActivePasswordSufficient());
3719 }
3720
Pavel Grafov75c0a892017-05-18 17:28:27 +01003721 private void setActivePasswordState(PasswordMetrics passwordMetrics)
3722 throws Exception {
3723 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003724 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003725
Pavel Grafov75c0a892017-05-18 17:28:27 +01003726 dpm.setActivePasswordState(passwordMetrics, userHandle);
3727 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003728
Pavel Grafov75c0a892017-05-18 17:28:27 +01003729 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3730 intent.setComponent(admin1);
3731 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3732
3733 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3734 MockUtils.checkIntent(intent),
3735 MockUtils.checkUserHandle(userHandle));
3736
3737 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
3738 // let it finish with system uid, otherwise it will throw and crash.
3739 flushTasks();
3740
3741 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003742 }
3743
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003744 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3745 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3746 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3747 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3748 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3749 DpmMockContext.SYSTEM_UID);
3750 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3751 DpmMockContext.SYSTEM_UID);
3752
3753 // Set up a device owner.
3754 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003755 setupDeviceOwner();
3756
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003757 // First and second user set IMEs manually.
3758 mContext.binder.callingUid = firstUserSystemUid;
3759 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3760 mContext.binder.callingUid = secondUserSystemUid;
3761 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003762
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003763 // Device owner changes IME for first user.
3764 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003765 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003766 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003767 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003768 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003769 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003770 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003771 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3772 mContext.binder.callingUid = firstUserSystemUid;
3773 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3774 mContext.binder.callingUid = secondUserSystemUid;
3775 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003776
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003777 // Second user changes IME manually.
3778 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3779 mContext.binder.callingUid = firstUserSystemUid;
3780 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3781 mContext.binder.callingUid = secondUserSystemUid;
3782 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003783
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003784 // First user changes IME manually.
3785 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3786 mContext.binder.callingUid = firstUserSystemUid;
3787 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3788 mContext.binder.callingUid = secondUserSystemUid;
3789 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003790
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003791 // Device owner changes IME for first user again.
3792 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003793 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003794 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003795 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003796 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003797 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003798 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3799 mContext.binder.callingUid = firstUserSystemUid;
3800 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3801 mContext.binder.callingUid = secondUserSystemUid;
3802 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003803
3804 // Restarting the DPMS should not lose information.
3805 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003806 mContext.binder.callingUid = firstUserSystemUid;
3807 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3808 mContext.binder.callingUid = secondUserSystemUid;
3809 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003810
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003811 // Device owner can find out whether it set the current IME itself.
3812 mContext.binder.callingUid = deviceOwnerUid;
3813 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003814
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003815 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003816 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003817 mContext.binder.callingUid = firstUserSystemUid;
3818 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3819 mContext.binder.callingUid = secondUserSystemUid;
3820 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003821 }
3822
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003823 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3824 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3825 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3826 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3827 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3828 DpmMockContext.SYSTEM_UID);
3829 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3830 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003831
3832 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003833 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003834 setupProfileOwner();
3835
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003836 // First and second user set IMEs manually.
3837 mContext.binder.callingUid = firstUserSystemUid;
3838 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3839 mContext.binder.callingUid = secondUserSystemUid;
3840 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003841
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003842 // Profile owner changes IME for second user.
3843 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003844 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003845 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003846 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003847 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003848 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003849 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003850 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3851 mContext.binder.callingUid = firstUserSystemUid;
3852 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3853 mContext.binder.callingUid = secondUserSystemUid;
3854 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003855
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003856 // First user changes IME manually.
3857 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3858 mContext.binder.callingUid = firstUserSystemUid;
3859 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3860 mContext.binder.callingUid = secondUserSystemUid;
3861 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003862
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003863 // Second user changes IME manually.
3864 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3865 mContext.binder.callingUid = firstUserSystemUid;
3866 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3867 mContext.binder.callingUid = secondUserSystemUid;
3868 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003869
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003870 // Profile owner changes IME for second user again.
3871 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003872 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003873 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003874 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003875 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003876 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003877 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3878 mContext.binder.callingUid = firstUserSystemUid;
3879 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3880 mContext.binder.callingUid = secondUserSystemUid;
3881 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003882
3883 // Restarting the DPMS should not lose information.
3884 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003885 mContext.binder.callingUid = firstUserSystemUid;
3886 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3887 mContext.binder.callingUid = secondUserSystemUid;
3888 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003889
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003890 // Profile owner can find out whether it set the current IME itself.
3891 mContext.binder.callingUid = profileOwnerUid;
3892 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003893
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003894 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003895 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003896 mContext.binder.callingUid = firstUserSystemUid;
3897 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3898 mContext.binder.callingUid = secondUserSystemUid;
3899 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003900 }
Rubin Xuaab7a412016-12-30 21:13:29 +00003901
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003902 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
3903 throws Exception {
3904 // Set up a device owner.
3905 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3906 setupDeviceOwner();
3907 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3908 }
3909
3910 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
3911 throws Exception {
3912 // Set up a profile owner.
3913 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3914 setupProfileOwner();
3915 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3916 }
3917
3918 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
3919 int adminUid) throws Exception {
3920 mContext.binder.callingUid = adminUid;
3921 final int userId = UserHandle.getUserId(adminUid);
3922
3923 final String packageName = "some.package";
3924 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
3925 admin1, Collections.singletonList(packageName)));
3926 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3927
3928 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3929 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
3930
3931 // Attempt to set to empty list (which means no listener is whitelisted)
3932 mContext.binder.callingUid = adminUid;
3933 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01003934 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003935 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3936
3937 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3938 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
3939 }
3940
3941 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
3942 // Set up a managed profile
3943 final int MANAGED_PROFILE_USER_ID = 15;
3944 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3945 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3946 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3947
3948 final String permittedListener = "some.package";
3949 setupPackageInPackageManager(
3950 permittedListener,
3951 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3952 /*appId=*/ 12345, /*flags=*/ 0);
3953
3954 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
3955 admin1, Collections.singletonList(permittedListener)));
3956
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003957 // isNotificationListenerServicePermitted should throw if not called from System.
3958 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3959 () -> dpms.isNotificationListenerServicePermitted(
3960 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003961
3962 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3963 assertTrue(dpms.isNotificationListenerServicePermitted(
3964 permittedListener, MANAGED_PROFILE_USER_ID));
3965 }
3966
3967 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
3968 throws Exception {
3969 // Set up a managed profile
3970 final int MANAGED_PROFILE_USER_ID = 15;
3971 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3972 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3973 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3974
3975 final String permittedListener = "permitted.package";
3976 int appId = 12345;
3977 setupPackageInPackageManager(
3978 permittedListener,
3979 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3980 appId, /*flags=*/ 0);
3981
3982 final String notPermittedListener = "not.permitted.package";
3983 setupPackageInPackageManager(
3984 notPermittedListener,
3985 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3986 ++appId, /*flags=*/ 0);
3987
3988 final String systemListener = "system.package";
3989 setupPackageInPackageManager(
3990 systemListener,
3991 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3992 ++appId, ApplicationInfo.FLAG_SYSTEM);
3993
3994 // By default all packages are allowed
3995 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3996
3997 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3998 assertTrue(dpms.isNotificationListenerServicePermitted(
3999 permittedListener, MANAGED_PROFILE_USER_ID));
4000 assertTrue(dpms.isNotificationListenerServicePermitted(
4001 notPermittedListener, MANAGED_PROFILE_USER_ID));
4002 assertTrue(dpms.isNotificationListenerServicePermitted(
4003 systemListener, MANAGED_PROFILE_USER_ID));
4004
4005 // Setting only one package in the whitelist
4006 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4007 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4008 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004009 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004010 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4011 assertEquals(1, permittedListeners.size());
4012 assertEquals(permittedListener, permittedListeners.get(0));
4013
4014 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4015 assertTrue(dpms.isNotificationListenerServicePermitted(
4016 permittedListener, MANAGED_PROFILE_USER_ID));
4017 assertFalse(dpms.isNotificationListenerServicePermitted(
4018 notPermittedListener, MANAGED_PROFILE_USER_ID));
4019 // System packages are always allowed (even if not in the whitelist)
4020 assertTrue(dpms.isNotificationListenerServicePermitted(
4021 systemListener, MANAGED_PROFILE_USER_ID));
4022
4023 // Setting an empty whitelist - only system listeners allowed
4024 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4025 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004026 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004027 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4028
4029 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4030 assertFalse(dpms.isNotificationListenerServicePermitted(
4031 permittedListener, MANAGED_PROFILE_USER_ID));
4032 assertFalse(dpms.isNotificationListenerServicePermitted(
4033 notPermittedListener, MANAGED_PROFILE_USER_ID));
4034 // System packages are always allowed (even if not in the whitelist)
4035 assertTrue(dpms.isNotificationListenerServicePermitted(
4036 systemListener, MANAGED_PROFILE_USER_ID));
4037
4038 // Setting a null whitelist - all listeners allowed
4039 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4040 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4041 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4042
4043 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4044 assertTrue(dpms.isNotificationListenerServicePermitted(
4045 permittedListener, MANAGED_PROFILE_USER_ID));
4046 assertTrue(dpms.isNotificationListenerServicePermitted(
4047 notPermittedListener, MANAGED_PROFILE_USER_ID));
4048 assertTrue(dpms.isNotificationListenerServicePermitted(
4049 systemListener, MANAGED_PROFILE_USER_ID));
4050 }
4051
4052 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4053 throws Exception {
4054 // Set up a managed profile
4055 final int MANAGED_PROFILE_USER_ID = 15;
4056 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4057 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4058 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4059
4060 final String nonSystemPackage = "non.system.package";
4061 int appId = 12345;
4062 setupPackageInPackageManager(
4063 nonSystemPackage,
4064 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4065 appId, /*flags=*/ 0);
4066
4067 final String systemListener = "system.package";
4068 setupPackageInPackageManager(
4069 systemListener,
4070 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4071 ++appId, ApplicationInfo.FLAG_SYSTEM);
4072
4073 // By default all packages are allowed (for all profiles)
4074 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4075
4076 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4077 assertTrue(dpms.isNotificationListenerServicePermitted(
4078 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4079 assertTrue(dpms.isNotificationListenerServicePermitted(
4080 systemListener, MANAGED_PROFILE_USER_ID));
4081 assertTrue(dpms.isNotificationListenerServicePermitted(
4082 nonSystemPackage, UserHandle.USER_SYSTEM));
4083 assertTrue(dpms.isNotificationListenerServicePermitted(
4084 systemListener, UserHandle.USER_SYSTEM));
4085
4086 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4087 // all allowed in primary profile
4088 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4089 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004090 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004091 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4092
4093 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4094 assertFalse(dpms.isNotificationListenerServicePermitted(
4095 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4096 assertTrue(dpms.isNotificationListenerServicePermitted(
4097 systemListener, MANAGED_PROFILE_USER_ID));
4098 assertTrue(dpms.isNotificationListenerServicePermitted(
4099 nonSystemPackage, UserHandle.USER_SYSTEM));
4100 assertTrue(dpms.isNotificationListenerServicePermitted(
4101 systemListener, UserHandle.USER_SYSTEM));
4102 }
4103
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004104 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004105 mServiceContext.packageName = mRealTestContext.getPackageName();
4106 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4107 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004108 setDeviceOwner();
4109
Pavel Grafov75c0a892017-05-18 17:28:27 +01004110 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004111 }
4112
4113 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004114 mServiceContext.packageName = mRealTestContext.getPackageName();
4115 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4116 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004117 setAsProfileOwner(admin1);
4118
Pavel Grafov75c0a892017-05-18 17:28:27 +01004119 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4120 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004121 }
4122
4123 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004124 mServiceContext.packageName = mRealTestContext.getPackageName();
4125 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4126 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004127 setAsProfileOwner(admin1);
4128
Pavel Grafov75c0a892017-05-18 17:28:27 +01004129 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4130 caller.packageName = "com.example.delegate";
4131 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4132 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004133
Pavel Grafov75c0a892017-05-18 17:28:27 +01004134 // Make caller a delegated cert installer.
4135 runAsCaller(mAdmin1Context, dpms,
4136 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004137
4138 verifyCanGetOwnerInstalledCaCerts(null, caller);
4139 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004140 }
4141
Robin Lee2c68dad2017-03-17 12:50:24 +00004142 private void verifyCanGetOwnerInstalledCaCerts(
4143 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004144 final String alias = "cert";
4145 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004146
4147 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004148 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004149 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4150 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004151 }
4152 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4153
4154 // caller: device admin or delegated certificate installer
4155 callerContext.applicationInfo = new ApplicationInfo();
4156 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4157
4158 // system_server
4159 final DpmMockContext serviceContext = mContext;
4160 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004161 getServices().addPackageContext(callerUser, admin1Context);
4162 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004163
4164 // Install a CA cert.
4165 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004166 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004167 .thenReturn(alias);
4168 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004169 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004170 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004171 });
4172
Pavel Grafov75c0a892017-05-18 17:28:27 +01004173 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4174 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4175 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004176 flushTasks();
4177
Robin Lee2c68dad2017-03-17 12:50:24 +00004178 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4179
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004180 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004181 runAsCaller(admin1Context, dpms, (dpm) -> {
4182 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004183 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004184 ownerInstalledCaCerts.addAll(installedCaCerts);
4185 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004186
4187 // Restarting the DPMS should not lose information.
4188 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004189 runAsCaller(admin1Context, dpms, (dpm) ->
4190 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004191
4192 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004193 runAsCaller(serviceContext, dpms, (dpm) -> {
4194 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004195
Robin Lee2c68dad2017-03-17 12:50:24 +00004196 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004197 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004198 });
4199
Pavel Grafov75c0a892017-05-18 17:28:27 +01004200 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4201 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4202 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004203 flushTasks();
4204
4205 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4206 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004207 runAsCaller(admin1Context, dpms, (dpm) -> {
4208 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4209 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004210 }
4211
Robin Lee2c68dad2017-03-17 12:50:24 +00004212 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4213 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004214 final String alias = "cert";
4215 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004216
4217 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004218 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004219 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4220 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004221 }
4222 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4223
4224 // caller: device admin or delegated certificate installer
4225 callerContext.applicationInfo = new ApplicationInfo();
4226 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4227
4228 // system_server
4229 final DpmMockContext serviceContext = mContext;
4230 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004231 getServices().addPackageContext(callerUser, admin1Context);
4232 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004233
4234 // Install a CA cert as caller
4235 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004236 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004237 .thenReturn(alias);
4238 assertTrue(dpm.installCaCert(callerName, caCert));
4239 });
4240
4241 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004242 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004243 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004244 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4245 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4246 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004247 flushTasks();
4248
Robin Lee2c68dad2017-03-17 12:50:24 +00004249 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004250 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004251
4252 runAsCaller(serviceContext, dpms, (dpm) -> {
4253 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4254 assertNotNull(ownerInstalledCaCerts);
4255 assertTrue(ownerInstalledCaCerts.isEmpty());
4256 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004257 }
4258
Victor Chang3e794af2016-03-04 13:48:17 +00004259 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004260 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004261 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4262 dpms.notifyChangeToContentObserver(
4263 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4264 }
4265
4266 private void assertProvisioningAllowed(String action, boolean expected) {
4267 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4268 dpm.isProvisioningAllowed(action));
4269 }
Tony Mak2f26b792016-11-28 17:54:51 +00004270
Nicolas Prevot45d29072017-01-18 16:11:19 +00004271 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4272 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004273 final String previousPackageName = mContext.packageName;
4274 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004275
4276 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4277 mContext.packageName = packageName;
4278 mMockContext.binder.callingUid = uid;
4279 assertProvisioningAllowed(action, expected);
4280
4281 // Set the previous package name / calling uid to go back to the initial state.
4282 mContext.packageName = previousPackageName;
4283 mMockContext.binder.callingUid = previousUid;
4284 }
4285
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004286 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004287 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4288 }
4289
4290 private void assertCheckProvisioningPreCondition(
4291 String action, String packageName, int provisioningCondition) {
4292 assertEquals("checkProvisioningPreCondition("
4293 + action + ", " + packageName + ") returning unexpected result",
4294 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004295 }
4296
Tony Mak2f26b792016-11-28 17:54:51 +00004297 /**
4298 * Setup a managed profile with the specified admin and its uid.
4299 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4300 * @param adminUid uid of the admin package.
4301 * @param copyFromAdmin package information for {@code admin} will be built based on this
4302 * component's information.
4303 */
4304 private void addManagedProfile(
4305 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4306 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004307 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004308 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4309 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4310 dpm.setActiveAdmin(admin, false, userId);
4311 assertTrue(dpm.setProfileOwner(admin, null, userId));
4312 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4313 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004314
4315 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004316 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004317 */
Robin Leeabaa0692017-02-20 20:54:22 +00004318 private static StringParceledListSlice asSlice(String[] s) {
4319 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004320 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004321
4322 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004323 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4324 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004325
Robin Lee2c68dad2017-03-17 12:50:24 +00004326 // We can't let exceptions happen on the background thread. Throw them here if they happen
4327 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004328 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004329 }
Victor Chang3e794af2016-03-04 13:48:17 +00004330}