blob: 6de3395e6fdfe475d882fc9827e76b413af12a53 [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;
Benjamin Franz714f77b2017-08-01 14:18:35 +010061import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000062import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000063import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010064import android.graphics.Color;
65import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080066import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080067import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070068import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080069import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070070import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070071import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010072import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080073import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010074import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000075import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080076import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000077import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010078import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070079import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070080
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010081import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000082import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000083import com.android.server.LocalServices;
84import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000085import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000086
Robin Lee7f5c91c2017-02-08 21:27:02 +000087import org.hamcrest.BaseMatcher;
88import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070089import org.mockito.invocation.InvocationOnMock;
90import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070091
Makoto Onukic8a5a552015-11-19 14:29:12 -080092import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000093import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000094import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070095import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070096import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070097import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010098import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000099import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700101/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700102 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000103 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700104 m FrameworksServicesTests &&
105 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000106 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800108 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700109
110 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000111 *
112 * , or:
113 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700114 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000115@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100116@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000118 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
119 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
120 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100121 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
122 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000123
Pavel Grafov75c0a892017-05-18 17:28:27 +0100124 // TODO replace all instances of this with explicit {@link #mServiceContext}.
125 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700126 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100127
128 private DpmMockContext mServiceContext;
129 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700130 public DevicePolicyManager dpm;
131 public DevicePolicyManagerServiceTestable dpms;
132
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100133 /*
134 * The CA cert below is the content of cacert.pem as generated by:
135 *
136 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
137 */
138 private static final String TEST_CA =
139 "-----BEGIN CERTIFICATE-----\n" +
140 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
141 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
142 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
143 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
144 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
145 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
146 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
147 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
148 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
149 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
150 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
151 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
152 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
153 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
154 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
155 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
156 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
157 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
158 "wQ==\n" +
159 "-----END CERTIFICATE-----\n";
160
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700161 @Override
162 protected void setUp() throws Exception {
163 super.setUp();
164
165 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100166 mServiceContext = mContext;
167 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
168 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700169 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100170 doReturn(Collections.singletonList(new ResolveInfo()))
171 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
172 any(Intent.class),
173 anyInt(),
174 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700175
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800176 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100177 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800178
Makoto Onukia52562c2015-10-01 16:12:31 -0700179 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700180
Makoto Onukid932f762015-09-29 16:53:38 -0700181 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
182 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
183 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800184 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700185
Pavel Grafov75c0a892017-05-18 17:28:27 +0100186 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
187 mAdmin1Context.packageName = admin1.getPackageName();
188 mAdmin1Context.applicationInfo = new ApplicationInfo();
189 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
190
Makoto Onukib643fb02015-09-22 15:03:44 -0700191 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700192 }
193
Robin Lee2c68dad2017-03-17 12:50:24 +0000194 @Override
195 protected void tearDown() throws Exception {
196 flushTasks();
197 super.tearDown();
198 }
199
Makoto Onukia52562c2015-10-01 16:12:31 -0700200 private void initializeDpms() {
201 // Need clearCallingIdentity() to pass permission checks.
202 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100203 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700204
Pavel Grafov75c0a892017-05-18 17:28:27 +0100205 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
206 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
207 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700208
Pavel Grafov75c0a892017-05-18 17:28:27 +0100209 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700210
Pavel Grafov75c0a892017-05-18 17:28:27 +0100211 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700212 }
213
Makoto Onukib643fb02015-09-22 15:03:44 -0700214 private void setUpUserManager() {
215 // Emulate UserManager.set/getApplicationRestriction().
216 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
217
218 // UM.setApplicationRestrictions() will save to appRestrictions.
219 doAnswer(new Answer<Void>() {
220 @Override
221 public Void answer(InvocationOnMock invocation) throws Throwable {
222 String pkg = (String) invocation.getArguments()[0];
223 Bundle bundle = (Bundle) invocation.getArguments()[1];
224 UserHandle user = (UserHandle) invocation.getArguments()[2];
225
226 appRestrictions.put(Pair.create(pkg, user), bundle);
227
228 return null;
229 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100230 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100231 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700232
233 // UM.getApplicationRestrictions() will read from appRestrictions.
234 doAnswer(new Answer<Bundle>() {
235 @Override
236 public Bundle answer(InvocationOnMock invocation) throws Throwable {
237 String pkg = (String) invocation.getArguments()[0];
238 UserHandle user = (UserHandle) invocation.getArguments()[1];
239
240 return appRestrictions.get(Pair.create(pkg, user));
241 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100242 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700243 anyString(), any(UserHandle.class));
244
Makoto Onukid932f762015-09-29 16:53:38 -0700245 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100246 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700247 }
248
249 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100250 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700251
Pavel Grafov75c0a892017-05-18 17:28:27 +0100252 mServiceContext.binder.callingUid =
253 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
254 runAsCaller(mServiceContext, dpms, dpm -> {
255 // PO needs to be a DA.
256 dpm.setActiveAdmin(admin, /*replace=*/ false);
257 // Fire!
258 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
259 // Check
260 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
261 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700262
Pavel Grafov75c0a892017-05-18 17:28:27 +0100263 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700264 }
265
266 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100267 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700268 .thenReturn(false);
269
270 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100271 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700272
273 // If the device has no DPMS feature, it shouldn't register the local service.
274 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
275 }
276
277 /**
278 * Caller doesn't have proper permissions.
279 */
280 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700281 // 1. Failure cases.
282
283 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100284 assertExpectException(SecurityException.class, /* messageRegex= */ null,
285 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700286
287 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
288 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100289
290 assertExpectException(SecurityException.class, /* messageRegex= */ null,
291 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700292 }
293
Makoto Onukif76b06a2015-09-22 15:03:44 -0700294 /**
295 * Test for:
296 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800297 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700298 * {@link DevicePolicyManager#isAdminActive}
299 * {@link DevicePolicyManager#isAdminActiveAsUser}
300 * {@link DevicePolicyManager#getActiveAdmins}
301 * {@link DevicePolicyManager#getActiveAdminsAsUser}
302 */
303 public void testSetActiveAdmin() throws Exception {
304 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700305 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
306
Makoto Onukif76b06a2015-09-22 15:03:44 -0700307 // 2. Call the API.
308 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700309
310 // 3. Verify internal calls.
311
312 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700313 verify(mContext.spiedContext).sendBroadcastAsUser(
314 MockUtils.checkIntentAction(
315 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
316 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
317 verify(mContext.spiedContext).sendBroadcastAsUser(
318 MockUtils.checkIntentAction(
319 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700320 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
321
Pavel Grafov75c0a892017-05-18 17:28:27 +0100322 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700323 eq(admin1.getPackageName()),
324 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
325 eq(PackageManager.DONT_KILL_APP),
326 eq(DpmMockContext.CALLER_USER_HANDLE),
327 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700328
329 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700330
331 // Make sure it's active admin1.
332 assertTrue(dpm.isAdminActive(admin1));
333 assertFalse(dpm.isAdminActive(admin2));
334 assertFalse(dpm.isAdminActive(admin3));
335
336 // But not admin1 for a different user.
337
338 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
339 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
340 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
341
342 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
343 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
344
345 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
346
347 // Next, add one more admin.
348 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700349 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700350 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700351
352 dpm.setActiveAdmin(admin2, /* replace =*/ false);
353
354 // Now we have two admins.
355 assertTrue(dpm.isAdminActive(admin1));
356 assertTrue(dpm.isAdminActive(admin2));
357 assertFalse(dpm.isAdminActive(admin3));
358
359 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
360 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100361 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700362 eq(admin1.getPackageName()),
363 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
364 eq(PackageManager.DONT_KILL_APP),
365 eq(DpmMockContext.CALLER_USER_HANDLE),
366 anyString());
367
368 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100369 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
370 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700371
372 // 5. Add the same admin1 again with replace, which should succeed.
373 dpm.setActiveAdmin(admin1, /* replace =*/ true);
374
375 // TODO make sure it's replaced.
376
377 // 6. Test getActiveAdmins()
378 List<ComponentName> admins = dpm.getActiveAdmins();
379 assertEquals(2, admins.size());
380 assertEquals(admin1, admins.get(0));
381 assertEquals(admin2, admins.get(1));
382
383 // Another user has no admins.
384 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
385
386 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
387 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
388
389 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
390 }
391
Makoto Onukid932f762015-09-29 16:53:38 -0700392 public void testSetActiveAdmin_multiUsers() throws Exception {
393
394 final int ANOTHER_USER_ID = 100;
395 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
396
Pavel Grafov75c0a892017-05-18 17:28:27 +0100397 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700398
399 // Set up pacakge manager for the other user.
400 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700401
402 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
403
404 dpm.setActiveAdmin(admin1, /* replace =*/ false);
405
406 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
407 dpm.setActiveAdmin(admin2, /* replace =*/ false);
408
409
410 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
411 assertTrue(dpm.isAdminActive(admin1));
412 assertFalse(dpm.isAdminActive(admin2));
413
414 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
415 assertFalse(dpm.isAdminActive(admin1));
416 assertTrue(dpm.isAdminActive(admin2));
417 }
418
Makoto Onukif76b06a2015-09-22 15:03:44 -0700419 /**
420 * Test for:
421 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800422 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700423 */
424 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
425 // 1. Make sure the caller has proper permissions.
426 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
427
428 dpm.setActiveAdmin(admin1, /* replace =*/ false);
429 assertTrue(dpm.isAdminActive(admin1));
430
431 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100432 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
433 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700434 }
435
436 /**
437 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800438 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
439 * BIND_DEVICE_ADMIN.
440 */
441 public void testSetActiveAdmin_permissionCheck() throws Exception {
442 // 1. Make sure the caller has proper permissions.
443 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
444
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100445 assertExpectException(IllegalArgumentException.class,
446 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
447 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800448 assertFalse(dpm.isAdminActive(adminNoPerm));
449
450 // Change the target API level to MNC. Now it can be set as DA.
451 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
452 VERSION_CODES.M);
453 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
454 assertTrue(dpm.isAdminActive(adminNoPerm));
455
456 // TODO Test the "load from the file" case where DA will still be loaded even without
457 // BIND_DEVICE_ADMIN and target API is N.
458 }
459
460 /**
461 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700462 * {@link DevicePolicyManager#removeActiveAdmin}
463 */
464 public void testRemoveActiveAdmin_SecurityException() {
465 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
466
467 // Add admin.
468
469 dpm.setActiveAdmin(admin1, /* replace =*/ false);
470
471 assertTrue(dpm.isAdminActive(admin1));
472
473 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
474
475 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100476 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
477 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700478
479 // Try to remove active admin with a different caller userid should fail too, without
480 // having MANAGE_DEVICE_ADMINS.
481 mContext.callerPermissions.clear();
482
Makoto Onukid932f762015-09-29 16:53:38 -0700483 // Change the caller, and call into DPMS directly with a different user-id.
484
Makoto Onukif76b06a2015-09-22 15:03:44 -0700485 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100486 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
487 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700488 }
489
490 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800491 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
492 * (because we can't send the remove broadcast).
493 */
494 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
495 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
496
497 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
498
499 // Add admin.
500
501 dpm.setActiveAdmin(admin1, /* replace =*/ false);
502
503 assertTrue(dpm.isAdminActive(admin1));
504
505 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
506
507 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100508 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800509 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100510 assertExpectException(IllegalStateException.class,
511 /* messageRegex= */ "User must be running and unlocked",
512 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800513
514 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
515
516 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100517 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800518 .thenReturn(true);
519
520 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700521 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800522 }
523
524 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700525 * Test for:
526 * {@link DevicePolicyManager#removeActiveAdmin}
527 */
Makoto Onukid932f762015-09-29 16:53:38 -0700528 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700529 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
530
531 // Add admin1.
532
533 dpm.setActiveAdmin(admin1, /* replace =*/ false);
534
535 assertTrue(dpm.isAdminActive(admin1));
536 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
537
538 // Different user, but should work, because caller has proper permissions.
539 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700540
541 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700542 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700543
544 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700545 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700546
547 // TODO DO Still can't be removed in this case.
548 }
549
550 /**
551 * Test for:
552 * {@link DevicePolicyManager#removeActiveAdmin}
553 */
554 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
555 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
556 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
557
558 // Add admin1.
559
560 dpm.setActiveAdmin(admin1, /* replace =*/ false);
561
562 assertTrue(dpm.isAdminActive(admin1));
563 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
564
565 // Broadcast from saveSettingsLocked().
566 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
567 MockUtils.checkIntentAction(
568 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
569 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
570
571 // Remove. No permissions, but same user, so it'll work.
572 mContext.callerPermissions.clear();
573 dpm.removeActiveAdmin(admin1);
574
Makoto Onukif76b06a2015-09-22 15:03:44 -0700575 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
576 MockUtils.checkIntentAction(
577 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
578 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
579 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700580 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700581 eq(dpms.mHandler),
582 eq(Activity.RESULT_OK),
583 isNull(String.class),
584 isNull(Bundle.class));
585
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700586 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700587
588 // Again broadcast from saveSettingsLocked().
589 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
590 MockUtils.checkIntentAction(
591 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
592 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
593
594 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700595 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700596
597 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000598 * Test for: @{link DevicePolicyManager#setActivePasswordState}
599 *
600 * Validates that when the password for a user changes, the notification broadcast intent
601 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
602 * addition to ones in the original user.
603 */
604 public void testSetActivePasswordState_sendToProfiles() throws Exception {
605 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
606
607 final int MANAGED_PROFILE_USER_ID = 78;
608 final int MANAGED_PROFILE_ADMIN_UID =
609 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
610
611 // Setup device owner.
612 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
613 mContext.packageName = admin1.getPackageName();
614 setupDeviceOwner();
615
616 // Add a managed profile belonging to the system user.
617 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
618
619 // Change the parent user's password.
620 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
621
622 // Both the device owner and the managed profile owner should receive this broadcast.
623 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
624 intent.setComponent(admin1);
625 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
626
627 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
628 MockUtils.checkIntent(intent),
629 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
630 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
631 MockUtils.checkIntent(intent),
632 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
633 }
634
635 /**
636 * Test for: @{link DevicePolicyManager#setActivePasswordState}
637 *
638 * Validates that when the password for a managed profile changes, the notification broadcast
639 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
640 * its parent.
641 */
642 public void testSetActivePasswordState_notSentToParent() throws Exception {
643 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
644
645 final int MANAGED_PROFILE_USER_ID = 78;
646 final int MANAGED_PROFILE_ADMIN_UID =
647 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
648
649 // Setup device owner.
650 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
651 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100652 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000653 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
654 setupDeviceOwner();
655
656 // Add a managed profile belonging to the system user.
657 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
658
659 // Change the profile's password.
660 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
661
662 // Both the device owner and the managed profile owner should receive this broadcast.
663 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
664 intent.setComponent(admin1);
665 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
666
667 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
668 MockUtils.checkIntent(intent),
669 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
670 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
671 MockUtils.checkIntent(intent),
672 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
673 }
674 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000675 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700676 */
677 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000678 setDeviceOwner();
679
680 // Try to set a profile owner on the same user, which should fail.
681 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
682 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100683 assertExpectException(IllegalStateException.class,
684 /* messageRegex= */ "already has a device owner",
685 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000686
687 // DO admin can't be deactivated.
688 dpm.removeActiveAdmin(admin1);
689 assertTrue(dpm.isAdminActive(admin1));
690
691 // TODO Test getDeviceOwnerName() too. To do so, we need to change
692 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
693 }
694
695 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700696 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800697 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700698 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
699 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
700
Makoto Onukid932f762015-09-29 16:53:38 -0700701 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700702 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
703
Makoto Onukid932f762015-09-29 16:53:38 -0700704 // Make sure admin1 is installed on system user.
705 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700706
Makoto Onukic8a5a552015-11-19 14:29:12 -0800707 // Check various get APIs.
708 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
709
Makoto Onukib643fb02015-09-22 15:03:44 -0700710 // DO needs to be an DA.
711 dpm.setActiveAdmin(admin1, /* replace =*/ false);
712
713 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700714 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700715
Makoto Onukic8a5a552015-11-19 14:29:12 -0800716 // getDeviceOwnerComponent should return the admin1 component.
717 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
718 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
719
720 // Check various get APIs.
721 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
722
723 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
724 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
725 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
726 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
727
728 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
729
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000730 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100731 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000732 eq(admin1.getPackageName()));
733
Makoto Onukib643fb02015-09-22 15:03:44 -0700734 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100735 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700736 eq(UserHandle.USER_SYSTEM), eq(false));
737
738 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
739 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
740 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
741
Makoto Onukic8a5a552015-11-19 14:29:12 -0800742 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700743 }
744
Makoto Onukic8a5a552015-11-19 14:29:12 -0800745 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
746 final int origCallingUser = mContext.binder.callingUid;
747 final List origPermissions = new ArrayList(mContext.callerPermissions);
748 mContext.callerPermissions.clear();
749
750 mContext.callerPermissions.add(permission.MANAGE_USERS);
751
752 mContext.binder.callingUid = Process.SYSTEM_UID;
753
754 // TODO Test getDeviceOwnerName() too. To do so, we need to change
755 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
756 if (hasDeviceOwner) {
757 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
758 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
759 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
760
761 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
762 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
763 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
764 } else {
765 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
766 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
767 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
768
769 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
770 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
771 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
772 }
773
774 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
775 if (hasDeviceOwner) {
776 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
777 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
778 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
779
780 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
781 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
782 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
783 } else {
784 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
785 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
786 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
787
788 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
789 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
790 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
791 }
792
793 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
794 // Still with MANAGE_USERS.
795 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
796 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
797 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
798
799 if (hasDeviceOwner) {
800 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
801 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
802 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
803 } else {
804 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
805 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
806 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
807 }
808
809 mContext.binder.callingUid = Process.SYSTEM_UID;
810 mContext.callerPermissions.remove(permission.MANAGE_USERS);
811 // System can still call "OnAnyUser" without MANAGE_USERS.
812 if (hasDeviceOwner) {
813 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
814 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
815 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
816
817 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
818 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
819 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
820 } else {
821 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
822 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
823 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
824
825 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
826 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
827 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
828 }
829
830 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
831 // Still no MANAGE_USERS.
832 if (hasDeviceOwner) {
833 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
834 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
835 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
836 } else {
837 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
838 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
839 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
840 }
841
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100842 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
843 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
844 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
845 dpm::getDeviceOwnerComponentOnAnyUser);
846 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
847 dpm::getDeviceOwnerUserId);
848 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
849 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800850
851 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
852 // Still no MANAGE_USERS.
853 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
854 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
855 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
856
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100857 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
858 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
859 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
860 dpm::getDeviceOwnerComponentOnAnyUser);
861 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
862 dpm::getDeviceOwnerUserId);
863 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
864 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800865
866 // Restore.
867 mContext.binder.callingUid = origCallingUser;
868 mContext.callerPermissions.addAll(origPermissions);
869 }
870
871
Makoto Onukib643fb02015-09-22 15:03:44 -0700872 /**
873 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
874 */
875 public void testSetDeviceOwner_noSuchPackage() {
876 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800877 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700878 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
879 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
880
881 // Call from a process on the system user.
882 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
883
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100884 assertExpectException(IllegalArgumentException.class,
885 /* messageRegex= */ "Invalid component",
886 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -0700887 }
888
889 public void testSetDeviceOwner_failures() throws Exception {
890 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
891 }
892
Makoto Onukia52562c2015-10-01 16:12:31 -0700893 public void testClearDeviceOwner() throws Exception {
894 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800895 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700896 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
897 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
898
899 // Set admin1 as a DA to the secondary user.
900 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
901
902 dpm.setActiveAdmin(admin1, /* replace =*/ false);
903
904 // Set admin 1 as the DO to the system user.
905
906 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
907 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
908 dpm.setActiveAdmin(admin1, /* replace =*/ false);
909 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
910
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000911 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100912 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000913 eq(admin1.getPackageName()));
914
Makoto Onukic8a5a552015-11-19 14:29:12 -0800915 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700916
Makoto Onuki90b89652016-01-28 14:44:18 -0800917 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100918 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000919 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800920
921 assertTrue(dpm.isAdminActive(admin1));
922 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
923
Makoto Onukia52562c2015-10-01 16:12:31 -0700924 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100925 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -0700926
927 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100928 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
929 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800930
931 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100932 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100933 assertExpectException(IllegalStateException.class,
934 /* messageRegex= */ "User must be running and unlocked",
935 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800936
Pavel Grafov75c0a892017-05-18 17:28:27 +0100937 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
938 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700939 dpm.clearDeviceOwnerApp(admin1.getPackageName());
940
941 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800942 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700943
Pavel Grafov75c0a892017-05-18 17:28:27 +0100944 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000945 eq(false),
946 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
947
Pavel Grafov75c0a892017-05-18 17:28:27 +0100948 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -0800949 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100950 eq(null),
951 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800952
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700953 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100954
955 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
956 // and once for clearing it.
957 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
958 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
959 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700960 // TODO Check other calls.
961 }
962
963 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
964 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800965 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700966 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
967 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
968
969 // Set admin1 as a DA to the secondary user.
970 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
971
972 dpm.setActiveAdmin(admin1, /* replace =*/ false);
973
974 // Set admin 1 as the DO to the system user.
975
976 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
977 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
978 dpm.setActiveAdmin(admin1, /* replace =*/ false);
979 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
980
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000981 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100982 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000983 eq(admin1.getPackageName()));
984
Makoto Onukic8a5a552015-11-19 14:29:12 -0800985 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700986
987 // Now call clear from the secondary user, which should throw.
988 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
989
990 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100991 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700992 eq(admin1.getPackageName()),
993 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100994 assertExpectException(SecurityException.class,
995 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
996 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -0700997
Makoto Onukic8a5a552015-11-19 14:29:12 -0800998 // DO shouldn't be removed.
999 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001000 }
1001
Makoto Onukib643fb02015-09-22 15:03:44 -07001002 public void testSetProfileOwner() throws Exception {
1003 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001004
Makoto Onuki90b89652016-01-28 14:44:18 -08001005 // PO admin can't be deactivated.
1006 dpm.removeActiveAdmin(admin1);
1007 assertTrue(dpm.isAdminActive(admin1));
1008
Makoto Onuki803d6752015-10-30 12:58:39 -07001009 // Try setting DO on the same user, which should fail.
1010 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001011 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1012 runAsCaller(mServiceContext, dpms, dpm -> {
1013 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001014 assertExpectException(IllegalStateException.class,
1015 /* messageRegex= */ "already has a profile owner",
1016 () -> dpm.setDeviceOwner(admin2, "owner-name",
1017 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001018 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001019 }
1020
Makoto Onuki90b89652016-01-28 14:44:18 -08001021 public void testClearProfileOwner() throws Exception {
1022 setAsProfileOwner(admin1);
1023
1024 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1025
1026 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1027 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1028
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001029 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001030 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001031 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001032 assertExpectException(IllegalStateException.class,
1033 /* messageRegex= */ "User must be running and unlocked",
1034 () -> dpm.clearProfileOwner(admin1));
1035
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001036 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001037 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001038 dpm.clearProfileOwner(admin1);
1039
1040 // Check
1041 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001042 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001043 }
1044
Makoto Onukib643fb02015-09-22 15:03:44 -07001045 public void testSetProfileOwner_failures() throws Exception {
1046 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1047 }
1048
Makoto Onukia52562c2015-10-01 16:12:31 -07001049 public void testGetDeviceOwnerAdminLocked() throws Exception {
1050 checkDeviceOwnerWithMultipleDeviceAdmins();
1051 }
1052
1053 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1054 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1055 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1056 // make sure it gets the right component from the right user.
1057
1058 final int ANOTHER_USER_ID = 100;
1059 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1060
Pavel Grafov75c0a892017-05-18 17:28:27 +01001061 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001062
1063 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001064 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001065 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1066 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1067
1068 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1069
Pavel Grafov75c0a892017-05-18 17:28:27 +01001070 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001071
Makoto Onukia52562c2015-10-01 16:12:31 -07001072 // Make sure the admin packge is installed to each user.
1073 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1074 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1075
1076 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1077 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1078
1079 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1080
1081
1082 // Set active admins to the users.
1083 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1084 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1085
1086 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1087 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1088
1089 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1090
1091 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001092 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001093 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1094
Makoto Onukic8a5a552015-11-19 14:29:12 -08001095 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001096
1097 // Then check getDeviceOwnerAdminLocked().
1098 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1099 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1100 }
1101
1102 /**
1103 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001104 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1105 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001106 *
1107 * We didn't use to persist the DO component class name, but now we do, and the above method
1108 * finds the right component from a package name upon migration.
1109 */
1110 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001111 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001112 checkDeviceOwnerWithMultipleDeviceAdmins();
1113
1114 // Overwrite the device owner setting and clears the clas name.
1115 dpms.mOwners.setDeviceOwner(
1116 new ComponentName(admin2.getPackageName(), ""),
1117 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1118 dpms.mOwners.writeDeviceOwner();
1119
1120 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001121 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001122
1123 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001124 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001125 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001126 initializeDpms();
1127
1128 // Now the DO component name is a full name.
1129 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1130 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001131 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001132 }
1133
Makoto Onukib643fb02015-09-22 15:03:44 -07001134 public void testSetGetApplicationRestriction() {
1135 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001136 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001137
1138 {
1139 Bundle rest = new Bundle();
1140 rest.putString("KEY_STRING", "Foo1");
1141 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1142 }
1143
1144 {
1145 Bundle rest = new Bundle();
1146 rest.putString("KEY_STRING", "Foo2");
1147 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1148 }
1149
1150 {
1151 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1152 assertNotNull(returned);
1153 assertEquals(returned.size(), 1);
1154 assertEquals(returned.get("KEY_STRING"), "Foo1");
1155 }
1156
1157 {
1158 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1159 assertNotNull(returned);
1160 assertEquals(returned.size(), 1);
1161 assertEquals(returned.get("KEY_STRING"), "Foo2");
1162 }
1163
1164 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1165 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1166 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001167
Edman Anjosf9946772016-11-28 16:35:15 +01001168 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001169 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1170 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001171 *
1172 * @param packageName the name of the package to be setup
1173 * @param appId the application ID to be given to the package
1174 * @return the UID of the package as known by the mock package manager
1175 */
1176 private int setupPackageInPackageManager(final String packageName, final int appId)
1177 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001178 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001179 ApplicationInfo.FLAG_HAS_CODE);
1180 }
1181
1182 /**
1183 * Setup a package in the package manager mock. Useful for faking installed applications.
1184 *
1185 * @param packageName the name of the package to be setup
1186 * @param userId the user id where the package will be "installed"
1187 * @param appId the application ID to be given to the package
1188 * @param flags flags to set in the ApplicationInfo for this package
1189 * @return the UID of the package as known by the mock package manager
1190 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001191 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1192 int flags) throws Exception {
1193 final int uid = UserHandle.getUid(userId, appId);
1194 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001195 final PackageInfo pi = new PackageInfo();
1196 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001197 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001198 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001199 eq(packageName),
1200 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001201 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001202 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001203 eq(packageName),
1204 anyInt(),
1205 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001206 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001207 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001208 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001209 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001210 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001211 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001212 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001213 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001214 return uid;
1215 }
1216
Robin Lee7f5c91c2017-02-08 21:27:02 +00001217 public void testCertificateDisclosure() throws Exception {
1218 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1219 final UserHandle user = UserHandle.of(userId);
1220
1221 mContext.applicationInfo = new ApplicationInfo();
1222 mContext.callerPermissions.add(permission.MANAGE_USERS);
1223 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001224 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001225 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1226
Robin Leeabaa0692017-02-20 20:54:22 +00001227 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1228 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001229
1230 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1231 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1232
1233 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001234 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001235 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001236 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001237 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001238 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001239 .cancelAsUser(anyString(), anyInt(), eq(user));
1240
1241 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001242 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001243 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001244 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1245 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001246 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001247 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001248 .notifyAsUser(anyString(), anyInt(), argThat(
1249 new BaseMatcher<Notification>() {
1250 @Override
1251 public boolean matches(Object item) {
1252 final Notification noti = (Notification) item;
1253 return TEST_STRING.equals(
1254 noti.extras.getString(Notification.EXTRA_TITLE));
1255 }
1256 @Override
1257 public void describeTo(Description description) {
1258 description.appendText(
1259 "Notification{title=\"" + TEST_STRING + "\"}");
1260 }
1261 }), eq(user));
1262 }
1263
Edman Anjosf9946772016-11-28 16:35:15 +01001264 /**
1265 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1266 * privileges can acually be exercised by a delegate are not covered here.
1267 */
1268 public void testDelegation() throws Exception {
1269 setAsProfileOwner(admin1);
1270
1271 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1272
1273 // Given two packages
1274 final String CERT_DELEGATE = "com.delegate.certs";
1275 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1276 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1277 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1278 20989);
1279
1280 // On delegation
1281 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1282 mContext.packageName = admin1.getPackageName();
1283 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1284 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1285
1286 // DPMS correctly stores and retrieves the delegates
1287 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1288 assertEquals(2, policy.mDelegationMap.size());
1289 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1290 DELEGATION_CERT_INSTALL);
1291 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1292 DELEGATION_CERT_INSTALL);
1293 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1294 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1295 DELEGATION_APP_RESTRICTIONS);
1296 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1297 DELEGATION_APP_RESTRICTIONS);
1298 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1299
1300 // On calling install certificate APIs from an unauthorized process
1301 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1302 mContext.packageName = RESTRICTIONS_DELEGATE;
1303
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001304 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1305 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001306
1307 // On calling install certificate APIs from an authorized process
1308 mContext.binder.callingUid = CERT_DELEGATE_UID;
1309 mContext.packageName = CERT_DELEGATE;
1310
1311 // DPMS executes without a SecurityException
1312 try {
1313 dpm.installCaCert(null, null);
1314 } catch (SecurityException unexpected) {
1315 fail("Threw SecurityException on authorized access");
1316 } catch (NullPointerException expected) {
1317 }
1318
1319 // On removing a delegate
1320 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1321 mContext.packageName = admin1.getPackageName();
1322 dpm.setCertInstallerPackage(admin1, null);
1323
1324 // DPMS does not allow access to ex-delegate
1325 mContext.binder.callingUid = CERT_DELEGATE_UID;
1326 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001327 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1328 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001329
1330 // But still allows access to other existing delegates
1331 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1332 mContext.packageName = RESTRICTIONS_DELEGATE;
1333 try {
1334 dpm.getApplicationRestrictions(null, "pkg");
1335 } catch (SecurityException expected) {
1336 fail("Threw SecurityException on authorized access");
1337 }
1338 }
1339
Esteban Talaverabf60f722015-12-10 16:26:44 +00001340 public void testApplicationRestrictionsManagingApp() throws Exception {
1341 setAsProfileOwner(admin1);
1342
Rubin Xued1928a2016-02-11 17:23:06 +00001343 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001344 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001345 final String nonDelegateExceptionMessageRegex =
1346 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001347 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001348 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1349 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001350
Esteban Talaverabf60f722015-12-10 16:26:44 +00001351 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1352 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001353 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1354 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001355 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001356 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001357 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001358 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1359 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001360
1361 // Check via the profile owner that no restrictions were set.
1362 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001363 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001364 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1365
Rubin Xued1928a2016-02-11 17:23:06 +00001366 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001367 assertExpectException(PackageManager.NameNotFoundException.class,
1368 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1369 () -> dpm.setApplicationRestrictionsManagingPackage(
1370 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001371
Esteban Talaverabf60f722015-12-10 16:26:44 +00001372 // Let appRestrictionsManagerPackage manage app restrictions
1373 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1374 assertEquals(appRestrictionsManagerPackage,
1375 dpm.getApplicationRestrictionsManagingPackage(admin1));
1376
1377 // Now that package should be able to set and retrieve app restrictions.
1378 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001379 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001380 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1381 dpm.setApplicationRestrictions(null, "pkg1", rest);
1382 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1383 assertEquals(1, returned.size(), 1);
1384 assertEquals("Foo1", returned.get("KEY_STRING"));
1385
1386 // The same app running on a separate user shouldn't be able to manage app restrictions.
1387 mContext.binder.callingUid = UserHandle.getUid(
1388 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1389 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001390 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1391 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001392
1393 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1394 // too.
1395 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001396 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001397 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1398 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1399 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1400
1401 // Removing the ability for the package to manage app restrictions.
1402 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1403 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1404 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001405 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001406 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001407 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1408 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001409 }
1410
Makoto Onukia4f11972015-10-01 13:19:58 -07001411 public void testSetUserRestriction_asDo() throws Exception {
1412 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001413 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001414 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1415 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1416
1417 // First, set DO.
1418
1419 // Call from a process on the system user.
1420 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1421
1422 // Make sure admin1 is installed on system user.
1423 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001424
1425 // Call.
1426 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001427 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001428 UserHandle.USER_SYSTEM));
1429
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001430 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001431 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001432 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001433 DpmTestUtils.assertRestrictions(
1434 DpmTestUtils.newRestrictions(defaultRestrictions),
1435 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1436 );
1437 DpmTestUtils.assertRestrictions(
1438 DpmTestUtils.newRestrictions(defaultRestrictions),
1439 dpm.getUserRestrictions(admin1)
1440 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001441 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001442 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001443 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001444 eq(true) /* isDeviceOwner */,
1445 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001446 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001447 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001448
1449 for (String restriction : defaultRestrictions) {
1450 dpm.clearUserRestriction(admin1, restriction);
1451 }
1452
Esteban Talavera548a04b2016-12-20 15:22:30 +00001453 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001454 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001455
1456 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001457 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001458 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001459 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1460 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001461 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001462
Makoto Onukia4f11972015-10-01 13:19:58 -07001463 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001464 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001465 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001466 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1467 UserManager.DISALLOW_ADD_USER),
1468 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001469 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001470
Makoto Onuki068c54a2015-10-13 14:34:03 -07001471 DpmTestUtils.assertRestrictions(
1472 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001473 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001474 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1475 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001476 DpmTestUtils.assertRestrictions(
1477 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001478 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001479 dpm.getUserRestrictions(admin1)
1480 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001481
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001482 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001483 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001484 eq(UserHandle.USER_SYSTEM),
1485 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001486 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001487 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001488
Makoto Onuki068c54a2015-10-13 14:34:03 -07001489 DpmTestUtils.assertRestrictions(
1490 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1491 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1492 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001493 DpmTestUtils.assertRestrictions(
1494 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1495 dpm.getUserRestrictions(admin1)
1496 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001497
1498 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001499 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001500 eq(UserHandle.USER_SYSTEM),
1501 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001502 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001503 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001504
Esteban Talavera548a04b2016-12-20 15:22:30 +00001505 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001506
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001507 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1508 // DO sets them, the scope is global.
1509 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001510 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001511 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001512 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001513 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001514 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001515 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1516 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001517 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001518
1519 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1520 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001521 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001522
1523 // More tests.
1524 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001525 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001526 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001527 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1528 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001529 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001530
1531 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001532 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001533 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001534 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001535 UserManager.DISALLOW_ADD_USER),
1536 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001537 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001538
1539 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001540 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001541 eq(UserHandle.USER_SYSTEM),
1542 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001543 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001544 UserManager.DISALLOW_ADD_USER),
1545 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001546 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001547
1548 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1549 // locally.
1550 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001551 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001552
1553 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1554 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1555 dpm.setCameraDisabled(admin2, true);
1556
Pavel Grafov75c0a892017-05-18 17:28:27 +01001557 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001558 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001559 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001560 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001561 UserManager.DISALLOW_ADD_USER),
1562 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001563 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001564 // TODO Make sure restrictions are written to the file.
1565 }
1566
1567 public void testSetUserRestriction_asPo() {
1568 setAsProfileOwner(admin1);
1569
Makoto Onuki068c54a2015-10-13 14:34:03 -07001570 DpmTestUtils.assertRestrictions(
1571 DpmTestUtils.newRestrictions(),
1572 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1573 .ensureUserRestrictions()
1574 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001575
1576 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001577 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001578 eq(DpmMockContext.CALLER_USER_HANDLE),
1579 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001580 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001581 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001582
Makoto Onukia4f11972015-10-01 13:19:58 -07001583 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001584 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001585 eq(DpmMockContext.CALLER_USER_HANDLE),
1586 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1587 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001588 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001589 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001590
Makoto Onuki068c54a2015-10-13 14:34:03 -07001591 DpmTestUtils.assertRestrictions(
1592 DpmTestUtils.newRestrictions(
1593 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1594 UserManager.DISALLOW_OUTGOING_CALLS
1595 ),
1596 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1597 .ensureUserRestrictions()
1598 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001599 DpmTestUtils.assertRestrictions(
1600 DpmTestUtils.newRestrictions(
1601 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1602 UserManager.DISALLOW_OUTGOING_CALLS
1603 ),
1604 dpm.getUserRestrictions(admin1)
1605 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001606
1607 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001608 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001609 eq(DpmMockContext.CALLER_USER_HANDLE),
1610 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001611 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001612 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001613
1614 DpmTestUtils.assertRestrictions(
1615 DpmTestUtils.newRestrictions(
1616 UserManager.DISALLOW_OUTGOING_CALLS
1617 ),
1618 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1619 .ensureUserRestrictions()
1620 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001621 DpmTestUtils.assertRestrictions(
1622 DpmTestUtils.newRestrictions(
1623 UserManager.DISALLOW_OUTGOING_CALLS
1624 ),
1625 dpm.getUserRestrictions(admin1)
1626 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001627
1628 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001629 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001630 eq(DpmMockContext.CALLER_USER_HANDLE),
1631 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001632 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001633 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001634
Makoto Onuki068c54a2015-10-13 14:34:03 -07001635 DpmTestUtils.assertRestrictions(
1636 DpmTestUtils.newRestrictions(),
1637 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1638 .ensureUserRestrictions()
1639 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001640 DpmTestUtils.assertRestrictions(
1641 DpmTestUtils.newRestrictions(),
1642 dpm.getUserRestrictions(admin1)
1643 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001644
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001645 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1646 // though when DO sets them they'll be applied globally.
1647 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001648 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001650 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001651 eq(DpmMockContext.CALLER_USER_HANDLE),
1652 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1653 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001654 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001655 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001656
1657 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001658 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001659 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001660 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001661 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001662 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001663 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001664
Makoto Onukia4f11972015-10-01 13:19:58 -07001665 // TODO Make sure restrictions are written to the file.
1666 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001667
Esteban Talavera548a04b2016-12-20 15:22:30 +00001668
1669 public void testDefaultEnabledUserRestrictions() throws Exception {
1670 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1671 mContext.callerPermissions.add(permission.MANAGE_USERS);
1672 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1673 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1674
1675 // First, set DO.
1676
1677 // Call from a process on the system user.
1678 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1679
1680 // Make sure admin1 is installed on system user.
1681 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1682
1683 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1684 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1685 UserHandle.USER_SYSTEM));
1686
1687 // Check that the user restrictions that are enabled by default are set. Then unset them.
1688 String[] defaultRestrictions = UserRestrictionsUtils
1689 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1690 assertTrue(defaultRestrictions.length > 0);
1691 DpmTestUtils.assertRestrictions(
1692 DpmTestUtils.newRestrictions(defaultRestrictions),
1693 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1694 );
1695 DpmTestUtils.assertRestrictions(
1696 DpmTestUtils.newRestrictions(defaultRestrictions),
1697 dpm.getUserRestrictions(admin1)
1698 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001699 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001700 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001701 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001702 eq(true) /* isDeviceOwner */,
1703 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001704 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001705 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001706
1707 for (String restriction : defaultRestrictions) {
1708 dpm.clearUserRestriction(admin1, restriction);
1709 }
1710
1711 assertNoDeviceOwnerRestrictions();
1712
1713 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001714 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001715 initializeDpms();
1716 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1717 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1718
1719 assertNoDeviceOwnerRestrictions();
1720
1721 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1722 // is set as it wasn't enabled during setDeviceOwner.
1723 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1724 assertFalse(UserRestrictionsUtils
1725 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1726 UserRestrictionsUtils
1727 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1728 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001729 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001730 initializeDpms();
1731 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1732 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1733
1734 DpmTestUtils.assertRestrictions(
1735 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1736 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1737 );
1738 DpmTestUtils.assertRestrictions(
1739 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1740 dpm.getUserRestrictions(admin1)
1741 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001742 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001743 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001744 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001745 eq(true) /* isDeviceOwner */,
1746 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001747 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001748 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001749
1750 // Remove the restriction.
1751 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1752
1753 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1754 initializeDpms();
1755 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1756 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1757 assertNoDeviceOwnerRestrictions();
1758 } finally {
1759 UserRestrictionsUtils
1760 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1761 }
1762 }
1763
1764 private void assertNoDeviceOwnerRestrictions() {
1765 DpmTestUtils.assertRestrictions(
1766 DpmTestUtils.newRestrictions(),
1767 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1768 );
1769 DpmTestUtils.assertRestrictions(
1770 DpmTestUtils.newRestrictions(),
1771 dpm.getUserRestrictions(admin1)
1772 );
1773 }
1774
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001775 public void testGetMacAddress() throws Exception {
1776 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1777 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1778 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1779
1780 // In this test, change the caller user to "system".
1781 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1782
1783 // Make sure admin1 is installed on system user.
1784 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1785
1786 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001787 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1788 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001789
1790 // DO needs to be an DA.
1791 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1792 assertTrue(dpm.isAdminActive(admin1));
1793
1794 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001795 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1796 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001797
1798 // Test 3. Caller has PO, but not DO.
1799 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001800 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1801 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001802
1803 // Remove PO.
1804 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001805 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001806 // Test 4, Caller is DO now.
1807 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1808
1809 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001810 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001811
1812 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001813 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001814 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001815
1816 // 4-3. With a real MAC address.
1817 final WifiInfo wi = new WifiInfo();
1818 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001819 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001820 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001821 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001822
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001823 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001824 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1825 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1826
1827 // In this test, change the caller user to "system".
1828 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1829
1830 // Make sure admin1 is installed on system user.
1831 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1832
1833 // Set admin1 as DA.
1834 dpm.setActiveAdmin(admin1, false);
1835 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001836 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1837 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001838
1839 // Set admin1 as PO.
1840 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001841 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1842 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001843
1844 // Remove PO and add DO.
1845 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001846 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001847 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1848
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001849 // admin1 is DO.
1850 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001851 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001852 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
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 dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001857 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001858 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001859 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1860 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001861
1862 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001863 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001864 dpm.reboot(admin1);
1865 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001866
1867 public void testSetGetSupportText() {
1868 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1869 dpm.setActiveAdmin(admin1, true);
1870 dpm.setActiveAdmin(admin2, true);
1871 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1872
1873 // Null default support messages.
1874 {
1875 assertNull(dpm.getLongSupportMessage(admin1));
1876 assertNull(dpm.getShortSupportMessage(admin1));
1877 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1878 assertNull(dpm.getShortSupportMessageForUser(admin1,
1879 DpmMockContext.CALLER_USER_HANDLE));
1880 assertNull(dpm.getLongSupportMessageForUser(admin1,
1881 DpmMockContext.CALLER_USER_HANDLE));
1882 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1883 }
1884
1885 // Only system can call the per user versions.
1886 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001887 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1888 () -> dpm.getShortSupportMessageForUser(admin1,
1889 DpmMockContext.CALLER_USER_HANDLE));
1890 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1891 () -> dpm.getLongSupportMessageForUser(admin1,
1892 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00001893 }
1894
1895 // Can't set message for admin in another uid.
1896 {
1897 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001898 assertExpectException(SecurityException.class,
1899 /* messageRegex= */ "is not owned by uid",
1900 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00001901 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1902 }
1903
1904 // Set/Get short returns what it sets and other admins text isn't changed.
1905 {
1906 final String supportText = "Some text to test with.";
1907 dpm.setShortSupportMessage(admin1, supportText);
1908 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1909 assertNull(dpm.getLongSupportMessage(admin1));
1910 assertNull(dpm.getShortSupportMessage(admin2));
1911
1912 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1913 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1914 DpmMockContext.CALLER_USER_HANDLE));
1915 assertNull(dpm.getShortSupportMessageForUser(admin2,
1916 DpmMockContext.CALLER_USER_HANDLE));
1917 assertNull(dpm.getLongSupportMessageForUser(admin1,
1918 DpmMockContext.CALLER_USER_HANDLE));
1919 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1920
1921 dpm.setShortSupportMessage(admin1, null);
1922 assertNull(dpm.getShortSupportMessage(admin1));
1923 }
1924
1925 // Set/Get long returns what it sets and other admins text isn't changed.
1926 {
1927 final String supportText = "Some text to test with.\nWith more text.";
1928 dpm.setLongSupportMessage(admin1, supportText);
1929 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1930 assertNull(dpm.getShortSupportMessage(admin1));
1931 assertNull(dpm.getLongSupportMessage(admin2));
1932
1933 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1934 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1935 DpmMockContext.CALLER_USER_HANDLE));
1936 assertNull(dpm.getLongSupportMessageForUser(admin2,
1937 DpmMockContext.CALLER_USER_HANDLE));
1938 assertNull(dpm.getShortSupportMessageForUser(admin1,
1939 DpmMockContext.CALLER_USER_HANDLE));
1940 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1941
1942 dpm.setLongSupportMessage(admin1, null);
1943 assertNull(dpm.getLongSupportMessage(admin1));
1944 }
1945 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001946
phweiss73145f42017-01-17 19:06:38 +01001947 public void testCreateAdminSupportIntent() throws Exception {
1948 // Setup device owner.
1949 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1950 setupDeviceOwner();
1951
1952 // Nonexisting permission returns null
1953 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
1954 assertNull(intent);
1955
1956 // Existing permission that is not set returns null
1957 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1958 assertNull(intent);
1959
1960 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01001961 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01001962 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1963 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1964 .thenReturn(true);
1965 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1966 assertNull(intent);
1967
1968 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01001969 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01001970 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1971 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1972 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
1973 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1974 assertNotNull(intent);
1975 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
1976 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
1977 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001978 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01001979 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
1980 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1981
1982 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
1983 // user restrictions
1984
1985 // Camera is not disabled
1986 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1987 assertNull(intent);
1988
1989 // Camera is disabled
1990 dpm.setCameraDisabled(admin1, true);
1991 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1992 assertNotNull(intent);
1993 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
1994 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1995
1996 // Screen capture is not disabled
1997 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1998 assertNull(intent);
1999
2000 // Screen capture is disabled
2001 dpm.setScreenCaptureDisabled(admin1, true);
2002 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2003 assertNotNull(intent);
2004 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2005 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2006
2007 // Same checks for different user
2008 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2009 // Camera should be disabled by device owner
2010 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2011 assertNotNull(intent);
2012 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2013 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2014 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2015 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2016 // ScreenCapture should not be disabled by device owner
2017 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2018 assertNull(intent);
2019 }
2020
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002021 /**
2022 * Test for:
2023 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002024 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002025 * {@link DevicePolicyManager#isAffiliatedUser}
2026 */
2027 public void testUserAffiliation() throws Exception {
2028 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2029 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2030 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2031
2032 // Check that the system user is unaffiliated.
2033 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2034 assertFalse(dpm.isAffiliatedUser());
2035
2036 // Set a device owner on the system user. Check that the system user becomes affiliated.
2037 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2038 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2039 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2040 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002041 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002042
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002043 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002044 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2045 setAsProfileOwner(admin2);
2046 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002047 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002048
2049 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2050 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002051 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002052 userAffiliationIds.add("red");
2053 userAffiliationIds.add("green");
2054 userAffiliationIds.add("blue");
2055 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002056 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002057 assertFalse(dpm.isAffiliatedUser());
2058
2059 // Have the device owner specify a set of affiliation ids that do not intersect with those
2060 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002061 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002062 deviceAffiliationIds.add("cyan");
2063 deviceAffiliationIds.add("yellow");
2064 deviceAffiliationIds.add("magenta");
2065 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2066 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002067 MoreAsserts.assertContentsInAnyOrder(
2068 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002069 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2070 assertFalse(dpm.isAffiliatedUser());
2071
2072 // Have the profile owner specify a set of affiliation ids that intersect with those
2073 // specified by the device owner. Check that the test user becomes affiliated.
2074 userAffiliationIds.add("yellow");
2075 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002076 MoreAsserts.assertContentsInAnyOrder(
2077 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002078 assertTrue(dpm.isAffiliatedUser());
2079
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002080 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002081 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002082 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002083 assertFalse(dpm.isAffiliatedUser());
2084
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002085 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2086 dpm.setAffiliationIds(admin2, userAffiliationIds);
2087 assertTrue(dpm.isAffiliatedUser());
2088 dpm.clearProfileOwner(admin2);
2089 assertFalse(dpm.isAffiliatedUser());
2090
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002091 // Check that the system user remains affiliated.
2092 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2093 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002094
2095 // Clear the device owner - the user becomes unaffiliated.
2096 clearDeviceOwner();
2097 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002098 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002099
2100 public void testGetUserProvisioningState_defaultResult() {
2101 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2102 }
2103
2104 public void testSetUserProvisioningState_permission() throws Exception {
2105 setupProfileOwner();
2106 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2107
2108 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2109 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2110 }
2111
2112 public void testSetUserProvisioningState_unprivileged() throws Exception {
2113 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002114 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2115 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2116 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002117 }
2118
2119 public void testSetUserProvisioningState_noManagement() {
2120 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002121 assertExpectException(IllegalStateException.class,
2122 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2123 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2124 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002125 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2126 }
2127
2128 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2129 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2130 setupDeviceOwner();
2131 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2132
2133 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2134 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2135 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2136 }
2137
2138 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2139 throws Exception {
2140 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2141 setupDeviceOwner();
2142 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2143
2144 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2145 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2146 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2147 }
2148
2149 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2150 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2151 setupDeviceOwner();
2152 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2153
2154 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2155 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2156 }
2157
2158 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2159 throws Exception {
2160 setupProfileOwner();
2161 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2162
2163 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2164 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2165 DevicePolicyManager.STATE_USER_UNMANAGED);
2166 }
2167
2168 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2169 throws Exception {
2170 setupProfileOwner();
2171 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2172
2173 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2174 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2175 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2176 }
2177
2178 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2179 setupProfileOwner();
2180 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2181
2182 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2183 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2184 }
2185
2186 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2187 setupProfileOwner();
2188 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2189
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002190 assertExpectException(IllegalStateException.class,
2191 /* messageRegex= */ "Cannot move to user provisioning state",
2192 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2193 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2194 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002195 }
2196
2197 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2198 throws Exception {
2199 setupProfileOwner();
2200 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2201
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002202 assertExpectException(IllegalStateException.class,
2203 /* messageRegex= */ "Cannot move to user provisioning state",
2204 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2205 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2206 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002207 }
2208
2209 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2210 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2211 for (int state : states) {
2212 dpm.setUserProvisioningState(state, userId);
2213 assertEquals(state, dpm.getUserProvisioningState());
2214 }
2215 }
2216
2217 private void setupProfileOwner() throws Exception {
2218 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2219
2220 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2221 dpm.setActiveAdmin(admin1, false);
2222 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2223
2224 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2225 }
2226
2227 private void setupDeviceOwner() throws Exception {
2228 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2229
2230 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2231 dpm.setActiveAdmin(admin1, false);
2232 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2233
2234 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2235 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002236
2237 public void testSetMaximumTimeToLock() {
2238 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2239
2240 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2241 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2242
Pavel Grafov75c0a892017-05-18 17:28:27 +01002243 reset(getServices().powerManagerInternal);
2244 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002245
2246 dpm.setMaximumTimeToLock(admin1, 0);
2247 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002248 reset(getServices().powerManagerInternal);
2249 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002250
2251 dpm.setMaximumTimeToLock(admin1, 1);
2252 verifyScreenTimeoutCall(1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002253 reset(getServices().powerManagerInternal);
2254 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002255
2256 dpm.setMaximumTimeToLock(admin2, 10);
2257 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002258 reset(getServices().powerManagerInternal);
2259 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002260
2261 dpm.setMaximumTimeToLock(admin1, 5);
2262 verifyScreenTimeoutCall(5, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002263 reset(getServices().powerManagerInternal);
2264 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002265
2266 dpm.setMaximumTimeToLock(admin2, 4);
2267 verifyScreenTimeoutCall(4, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002268 reset(getServices().powerManagerInternal);
2269 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002270
2271 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002272 reset(getServices().powerManagerInternal);
2273 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002274
2275 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2276 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002277 reset(getServices().powerManagerInternal);
2278 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002279
2280 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2281 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002282 reset(getServices().powerManagerInternal);
2283 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002284
2285 dpm.setMaximumTimeToLock(admin2, 10);
2286 verifyScreenTimeoutCall(10, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002287 reset(getServices().powerManagerInternal);
2288 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002289
2290 // There's no restriction; shold be set to MAX.
2291 dpm.setMaximumTimeToLock(admin2, 0);
2292 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2293 }
2294
Michal Karpinski943aabd2016-10-06 11:09:25 +01002295 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2296 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2297 setupDeviceOwner();
2298 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2299
Michal Karpinskid084ca52017-01-18 15:54:18 +00002300 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2301 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2302 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2303 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2304 - ONE_MINUTE;
2305
2306 // verify that the minimum timeout cannot be modified on user builds (system property is
2307 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002308 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002309
2310 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2311 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2312 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2313
Pavel Grafov75c0a892017-05-18 17:28:27 +01002314 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002315
2316 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002317 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002318
Michal Karpinskid084ca52017-01-18 15:54:18 +00002319 // reset to default (0 means the admin is not participating, so default should be returned)
2320 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002321
2322 // aggregation should be the default if unset by any admin
2323 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2324 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2325
2326 // admin not participating by default
2327 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2328
2329 //clamping from the top
2330 dpm.setRequiredStrongAuthTimeout(admin1,
2331 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2332 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2333 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2334 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2335 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2336
Michal Karpinskid084ca52017-01-18 15:54:18 +00002337 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002338 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2339 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2340 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2341 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2342
2343 // clamping from the bottom
2344 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2345 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2346 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2347
Michal Karpinskid084ca52017-01-18 15:54:18 +00002348 // values within range
2349 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2350 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2351 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2352
2353 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2354 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2355 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002356
2357 // reset to default
2358 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2359 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2360 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2361 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2362
2363 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002364 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2365 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002366 }
2367
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002368 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2369 boolean shouldStayOnWhilePluggedInBeCleared) {
2370 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002371 verify(getServices().powerManagerInternal, times(0))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002372 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2373 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002374 verify(getServices().powerManagerInternal, times(1))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002375 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2376 }
2377 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2378 // UnfinishedVerificationException.
2379 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002380
Esteban Talavera01576862016-12-15 11:16:44 +00002381 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002382 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002383 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002384 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002385 .thenReturn(false);
2386 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002387 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2388 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002389 .thenReturn(true);
2390 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2391
2392 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002393 }
Victor Chang3e794af2016-03-04 13:48:17 +00002394
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002395 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2396 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002397 mContext.packageName = admin1.getPackageName();
2398 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002399 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2400 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2401 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2402 false);
2403 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2404 }
2405
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002406 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2407 setup_DeviceAdminFeatureOff();
2408 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2409 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2410 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2411 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2412 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2413 assertCheckProvisioningPreCondition(
2414 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2415 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2416 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2417 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2418 }
2419
Esteban Talavera01576862016-12-15 11:16:44 +00002420 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002421 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002422 .thenReturn(false);
2423 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002424 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2425 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002426 .thenReturn(true);
2427 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2428
2429 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002430 }
Victor Chang3e794af2016-03-04 13:48:17 +00002431
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002432 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2433 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002434 mContext.packageName = admin1.getPackageName();
2435 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002436 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2437 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2438 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2439 false);
2440 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2441
2442 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002443 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002444 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2445 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2446 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2447 true);
2448 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2449 }
2450
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002451 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2452 setup_ManagedProfileFeatureOff();
2453 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2454 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2455 DevicePolicyManager.CODE_OK);
2456 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2457 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2458 assertCheckProvisioningPreCondition(
2459 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2460 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2461 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2462 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2463
2464 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002465 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002466 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2467 DevicePolicyManager.CODE_OK);
2468 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2469 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2470 assertCheckProvisioningPreCondition(
2471 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2472 DevicePolicyManager.CODE_OK);
2473 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2474 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2475 }
2476
Esteban Talavera01576862016-12-15 11:16:44 +00002477 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002478 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002479 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002480 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2481 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002482 .thenReturn(true);
2483 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2484
2485 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002486 }
Victor Chang3e794af2016-03-04 13:48:17 +00002487
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002488 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2489 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002490 mContext.packageName = admin1.getPackageName();
2491 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002492 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2493 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2494 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2495 false /* because of non-split user */);
2496 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2497 false /* because of non-split user */);
2498 }
2499
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002500 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002501 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002502 setup_nonSplitUser_firstBoot_primaryUser();
2503 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2504 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2505 DevicePolicyManager.CODE_OK);
2506 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2507 DevicePolicyManager.CODE_OK);
2508 assertCheckProvisioningPreCondition(
2509 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2510 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2511 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2512 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2513 }
2514
Esteban Talavera01576862016-12-15 11:16:44 +00002515 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002516 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002517 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002518 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2519 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002520 .thenReturn(true);
2521 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2522
2523 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002524 }
Victor Chang3e794af2016-03-04 13:48:17 +00002525
Nicolas Prevot45d29072017-01-18 16:11:19 +00002526 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2527 setDeviceOwner();
2528 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2529 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2530 }
2531
2532 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2533 setup_nonSplitUser_withDo_primaryUser();
2534 final int MANAGED_PROFILE_USER_ID = 18;
2535 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2536 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002537 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002538 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002539 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002540 true)).thenReturn(true);
2541 }
2542
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002543 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2544 throws Exception {
2545 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002546 mContext.packageName = admin1.getPackageName();
2547 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002548 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2549 false/* because of completed device setup */);
2550 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2551 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2552 false/* because of non-split user */);
2553 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2554 false/* because of non-split user */);
2555 }
2556
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002557 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2558 throws Exception {
2559 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2560 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2561 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2562 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2563 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2564 DevicePolicyManager.CODE_OK);
2565 assertCheckProvisioningPreCondition(
2566 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2567 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2568 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2569 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2570 }
2571
Nicolas Prevot45d29072017-01-18 16:11:19 +00002572 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2573 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002574 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002575 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2576
2577 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2578 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002579 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002580
2581 // COMP mode is allowed.
2582 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2583 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002584 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002585
Nicolas Prevot45d29072017-01-18 16:11:19 +00002586 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002587 assertCheckProvisioningPreCondition(
2588 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002589 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002590 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002591 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2592 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2593 }
Esteban Talavera01576862016-12-15 11:16:44 +00002594
Nicolas Prevot45d29072017-01-18 16:11:19 +00002595 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2596 setup_nonSplitUser_withDo_primaryUser();
2597 mContext.packageName = admin1.getPackageName();
2598 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2599 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2600 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002601 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002602 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2603 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2604 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002605 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002606 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2607 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2608 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2609 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2610 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002611 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002612 assertCheckProvisioningPreCondition(
2613 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002614 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002615 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002616 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2617 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2618 }
Esteban Talavera01576862016-12-15 11:16:44 +00002619
Nicolas Prevot45d29072017-01-18 16:11:19 +00002620 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2621 throws Exception {
2622 setup_nonSplitUser_withDo_primaryUser();
2623 mContext.packageName = admin1.getPackageName();
2624 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002625 // The DO should not be allowed to initiate provisioning if the restriction is set by
2626 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002627 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002628 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2629 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2630 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002631 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002632 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2633 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2634 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2635 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2636 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002637 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2638
2639 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002640 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002641 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002642 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002643 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2644 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2645 }
2646
2647 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2648 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2649 mContext.packageName = admin1.getPackageName();
2650 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2651
2652 // We can delete the managed profile to create a new one, so provisioning is allowed.
2653 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2654 DevicePolicyManager.CODE_OK);
2655 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2656 assertCheckProvisioningPreCondition(
2657 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2658 DpmMockContext.ANOTHER_PACKAGE_NAME,
2659 DevicePolicyManager.CODE_OK);
2660 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2661 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2662 }
2663
2664 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2665 throws Exception {
2666 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2667 mContext.packageName = admin1.getPackageName();
2668 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002669 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002670 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2671 eq(UserHandle.SYSTEM)))
2672 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002673 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002674 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2675 eq(UserHandle.SYSTEM)))
2676 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002677
2678 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002679 assertCheckProvisioningPreCondition(
2680 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2681 DpmMockContext.ANOTHER_PACKAGE_NAME,
2682 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2683 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2684 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002685
2686 // But the device owner can still do it because it has set the restriction itself.
2687 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2688 DevicePolicyManager.CODE_OK);
2689 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002690 }
2691
2692 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002693 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002694 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002695 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2696 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002697 .thenReturn(false);
2698 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2699
2700 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002701 }
Victor Chang3e794af2016-03-04 13:48:17 +00002702
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002703 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2704 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002705 mContext.packageName = admin1.getPackageName();
2706 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002707 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2708 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2709 false /* because canAddMoreManagedProfiles returns false */);
2710 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2711 true);
2712 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2713 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002714 }
2715
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002716 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2717 throws Exception {
2718 setup_splitUser_firstBoot_systemUser();
2719 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2720 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2721 DevicePolicyManager.CODE_OK);
2722 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002723 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002724 assertCheckProvisioningPreCondition(
2725 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2726 DevicePolicyManager.CODE_OK);
2727 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2728 DevicePolicyManager.CODE_SYSTEM_USER);
2729 }
2730
Esteban Talavera01576862016-12-15 11:16:44 +00002731 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002732 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002733 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002734 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2735 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002736 .thenReturn(false);
2737 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2738
2739 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002740 }
Victor Chang3e794af2016-03-04 13:48:17 +00002741
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002742 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2743 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002744 mContext.packageName = admin1.getPackageName();
2745 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002746 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2747 true/* it's undefined behavior. Can be changed into false in the future */);
2748 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2749 false /* because canAddMoreManagedProfiles returns false */);
2750 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2751 true/* it's undefined behavior. Can be changed into false in the future */);
2752 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2753 false/* because calling uid is system user */);
2754 }
2755
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002756 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2757 throws Exception {
2758 setup_splitUser_afterDeviceSetup_systemUser();
2759 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2760 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2761 DevicePolicyManager.CODE_OK);
2762 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002763 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002764 assertCheckProvisioningPreCondition(
2765 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2766 DevicePolicyManager.CODE_OK);
2767 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2768 DevicePolicyManager.CODE_SYSTEM_USER);
2769 }
2770
Esteban Talavera01576862016-12-15 11:16:44 +00002771 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002772 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002773 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002774 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2775 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002776 true)).thenReturn(true);
2777 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2778
2779 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002780 }
Victor Chang3e794af2016-03-04 13:48:17 +00002781
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002782 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2783 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002784 mContext.packageName = admin1.getPackageName();
2785 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002786 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2787 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2788 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2789 true);
2790 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002791 }
2792
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002793 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002794 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002795 setup_splitUser_firstBoot_primaryUser();
2796 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2797 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2798 DevicePolicyManager.CODE_OK);
2799 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2800 DevicePolicyManager.CODE_OK);
2801 assertCheckProvisioningPreCondition(
2802 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2803 DevicePolicyManager.CODE_OK);
2804 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2805 DevicePolicyManager.CODE_OK);
2806 }
2807
Esteban Talavera01576862016-12-15 11:16:44 +00002808 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002809 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002810 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002811 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2812 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002813 true)).thenReturn(true);
2814 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2815
2816 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002817 }
Victor Chang3e794af2016-03-04 13:48:17 +00002818
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002819 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2820 throws Exception {
2821 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002822 mContext.packageName = admin1.getPackageName();
2823 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002824 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2825 true/* it's undefined behavior. Can be changed into false in the future */);
2826 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2827 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2828 true/* it's undefined behavior. Can be changed into false in the future */);
2829 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2830 false/* because user setup completed */);
2831 }
2832
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002833 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002834 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002835 setup_splitUser_afterDeviceSetup_primaryUser();
2836 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2837 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2838 DevicePolicyManager.CODE_OK);
2839 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2840 DevicePolicyManager.CODE_OK);
2841 assertCheckProvisioningPreCondition(
2842 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2843 DevicePolicyManager.CODE_OK);
2844 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2845 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2846 }
2847
Esteban Talavera01576862016-12-15 11:16:44 +00002848 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002849 setDeviceOwner();
2850
Pavel Grafov75c0a892017-05-18 17:28:27 +01002851 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002852 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002853 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2854 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002855 .thenReturn(false);
2856 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2857
2858 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002859 }
Victor Chang3e794af2016-03-04 13:48:17 +00002860
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002861 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2862 throws Exception {
2863 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002864 mContext.packageName = admin1.getPackageName();
2865 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002866 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2867 false /* can't provision managed profile on system user */);
2868 }
2869
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002870 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002871 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002872 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2873 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2874 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2875 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2876 }
2877
2878 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002879 setDeviceOwner();
2880
Pavel Grafov75c0a892017-05-18 17:28:27 +01002881 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002882 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002883 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2884 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002885 true)).thenReturn(true);
2886 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2887
2888 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002889 }
Victor Chang3e794af2016-03-04 13:48:17 +00002890
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002891 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2892 throws Exception {
2893 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002894 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2895 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002896 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2897 }
2898
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002899 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002900 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002901 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2902 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002903
2904 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002905 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2906 DevicePolicyManager.CODE_OK);
2907 }
2908
2909 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002910 setDeviceOwner();
2911
Pavel Grafov75c0a892017-05-18 17:28:27 +01002912 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002913 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002914 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2915 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002916 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2917 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002918 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002919 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002920 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002921 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00002922 true)).thenReturn(true);
2923 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2924
2925 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002926 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002927
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002928 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2929 throws Exception {
2930 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002931 mContext.packageName = admin1.getPackageName();
2932 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002933 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2934 }
2935
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002936 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2937 throws Exception {
2938 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2939 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2940 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2941 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2942 }
2943
2944 public void testCheckProvisioningPreCondition_permission() {
2945 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002946 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2947 () -> dpm.checkProvisioningPreCondition(
2948 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002949 }
2950
Victor Chang3577ed22016-08-25 18:49:26 +01002951 public void testForceUpdateUserSetupComplete_permission() {
2952 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002953 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2954 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01002955 }
2956
2957 public void testForceUpdateUserSetupComplete_systemUser() {
2958 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2959 // GIVEN calling from user 20
2960 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002961 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2962 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01002963 }
2964
2965 public void testForceUpdateUserSetupComplete_userbuild() {
2966 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2967 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2968
2969 final int userId = UserHandle.USER_SYSTEM;
2970 // GIVEN userComplete is false in SettingsProvider
2971 setUserSetupCompleteForUser(false, userId);
2972
2973 // GIVEN userComplete is true in DPM
2974 DevicePolicyManagerService.DevicePolicyData userData =
2975 new DevicePolicyManagerService.DevicePolicyData(userId);
2976 userData.mUserSetupComplete = true;
2977 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2978
2979 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01002980 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01002981
2982 assertTrue(dpms.hasUserSetupCompleted());
2983
2984 dpm.forceUpdateUserSetupComplete();
2985
2986 // THEN the state in dpms is not changed
2987 assertTrue(dpms.hasUserSetupCompleted());
2988 }
2989
2990 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2991 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2992 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2993
2994 final int userId = UserHandle.USER_SYSTEM;
2995 // GIVEN userComplete is false in SettingsProvider
2996 setUserSetupCompleteForUser(false, userId);
2997
2998 // GIVEN userComplete is true in DPM
2999 DevicePolicyManagerService.DevicePolicyData userData =
3000 new DevicePolicyManagerService.DevicePolicyData(userId);
3001 userData.mUserSetupComplete = true;
3002 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3003
3004 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003005 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003006
3007 assertTrue(dpms.hasUserSetupCompleted());
3008
3009 dpm.forceUpdateUserSetupComplete();
3010
3011 // THEN the state in dpms is not changed
3012 assertFalse(dpms.hasUserSetupCompleted());
3013 }
3014
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003015 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003016 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003017 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003018
3019 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3020 runAsCaller(mAdmin1Context, dpms, dpm -> {
3021 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3022 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003023 }
3024
3025 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3026 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3027 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003028
3029 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3030 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003031 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003032 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3033 .thenReturn(true);
3034
3035 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003036 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003037
3038 // Enabling logging should not change the timestamp.
3039 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003040 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003041 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003042 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003043 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003044 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003045
3046 // Retrieving the logs should update the timestamp.
3047 final long beforeRetrieval = System.currentTimeMillis();
3048 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003049 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003050 final long afterRetrieval = System.currentTimeMillis();
3051 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3052 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3053
3054 // Retrieving the pre-boot logs should update the timestamp.
3055 Thread.sleep(2);
3056 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003057 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003058 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3059
3060 // Checking the timestamp again should not change it.
3061 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003062 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003063
3064 // Retrieving the logs again should update the timestamp.
3065 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003066 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003067 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3068
3069 // Disabling logging should not change the timestamp.
3070 Thread.sleep(2);
3071 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003072 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003073
3074 // Restarting the DPMS should not lose the timestamp.
3075 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003076 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003077
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003078 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3079 mContext.binder.callingUid = 1234567;
3080 mContext.callerPermissions.add(permission.MANAGE_USERS);
3081 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3082 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3083
3084 // System can retrieve the timestamp.
3085 mContext.binder.clearCallingIdentity();
3086 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3087
3088 // Removing the device owner should clear the timestamp.
3089 clearDeviceOwner();
3090 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003091 }
3092
yuemingwe43cdf72017-10-12 16:52:11 +01003093 public void testSetTime() throws Exception {
3094 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3095 setupDeviceOwner();
3096 dpm.setTime(admin1, 0);
3097 verify(getServices().alarmManager).setTime(0);
3098 }
3099
3100 public void testSetTimeFailWithPO() throws Exception {
3101 setupProfileOwner();
3102 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3103 }
3104
3105 public void testSetTimeWithAutoTimeOn() throws Exception {
3106 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3107 setupDeviceOwner();
3108 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3109 .thenReturn(1);
3110 assertFalse(dpm.setTime(admin1, 0));
3111 }
3112
3113 public void testSetTimeZone() throws Exception {
3114 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3115 setupDeviceOwner();
3116 dpm.setTimeZone(admin1, "Asia/Shanghai");
3117 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3118 }
3119
3120 public void testSetTimeZoneFailWithPO() throws Exception {
3121 setupProfileOwner();
3122 assertExpectException(SecurityException.class, null,
3123 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3124 }
3125
3126 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3127 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3128 setupDeviceOwner();
3129 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3130 .thenReturn(1);
3131 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3132 }
3133
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003134 public void testGetLastBugReportRequestTime() throws Exception {
3135 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3136 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003137
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003138 mContext.packageName = admin1.getPackageName();
3139 mContext.applicationInfo = new ApplicationInfo();
3140 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3141 .thenReturn(Color.WHITE);
3142 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3143 anyObject())).thenReturn(Color.WHITE);
3144
Esteban Talaverad36dd152016-12-15 08:51:45 +00003145 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3146 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003147 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003148
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003149 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003150 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003151
3152 // Requesting a bug report should update the timestamp.
3153 final long beforeRequest = System.currentTimeMillis();
3154 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003155 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003156 final long afterRequest = System.currentTimeMillis();
3157 assertTrue(bugReportRequestTime >= beforeRequest);
3158 assertTrue(bugReportRequestTime <= afterRequest);
3159
3160 // Checking the timestamp again should not change it.
3161 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003162 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003163
3164 // Restarting the DPMS should not lose the timestamp.
3165 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003166 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003167
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003168 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3169 mContext.binder.callingUid = 1234567;
3170 mContext.callerPermissions.add(permission.MANAGE_USERS);
3171 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3172 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3173
3174 // System can retrieve the timestamp.
3175 mContext.binder.clearCallingIdentity();
3176 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3177
3178 // Removing the device owner should clear the timestamp.
3179 clearDeviceOwner();
3180 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003181 }
3182
3183 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3184 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3185 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003186 mContext.packageName = admin1.getPackageName();
3187 mContext.applicationInfo = new ApplicationInfo();
3188 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3189 .thenReturn(Color.WHITE);
3190 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3191 anyObject())).thenReturn(Color.WHITE);
3192
3193 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3194 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003195 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003196 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003197 .thenReturn(true);
3198
3199 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003200 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003201
3202 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3203 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003204 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003205
3206 // Enabling logging should not change the timestamp.
3207 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003208 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003209
3210 // Retrieving the logs should update the timestamp.
3211 final long beforeRetrieval = System.currentTimeMillis();
3212 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003213 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003214 final long afterRetrieval = System.currentTimeMillis();
3215 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3216 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3217
3218 // Checking the timestamp again should not change it.
3219 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003220 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003221
3222 // Retrieving the logs again should update the timestamp.
3223 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003224 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003225 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3226
3227 // Disabling logging should not change the timestamp.
3228 Thread.sleep(2);
3229 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003230 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003231
3232 // Restarting the DPMS should not lose the timestamp.
3233 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003234 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3235
3236 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3237 mContext.binder.callingUid = 1234567;
3238 mContext.callerPermissions.add(permission.MANAGE_USERS);
3239 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3240 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3241
3242 // System can retrieve the timestamp.
3243 mContext.binder.clearCallingIdentity();
3244 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3245
3246 // Removing the device owner should clear the timestamp.
3247 clearDeviceOwner();
3248 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003249 }
3250
Tony Mak2f26b792016-11-28 17:54:51 +00003251 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3252 // Setup device owner.
3253 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3254 setupDeviceOwner();
3255
3256 // Only device owner is setup, the result list should be empty.
3257 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3258 MoreAsserts.assertEmpty(targetUsers);
3259
3260 // Setup a managed profile managed by the same admin.
3261 final int MANAGED_PROFILE_USER_ID = 15;
3262 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3263 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3264
3265 // Add a secondary user, it should never talk with.
3266 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003267 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003268
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003269 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3270 // other.
3271 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3272 MoreAsserts.assertEmpty(targetUsers);
3273
3274 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3275 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3276 MoreAsserts.assertEmpty(targetUsers);
3277
3278 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003279 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003280 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3281 dpm.setAffiliationIds(admin1, userAffiliationIds);
3282
3283 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3284 dpm.setAffiliationIds(admin1, userAffiliationIds);
3285
Tony Mak2f26b792016-11-28 17:54:51 +00003286 // Calling from device owner admin, the result list should just contain the managed
3287 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003288 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003289 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3290 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3291
3292 // Calling from managed profile admin, the result list should just contain the system
3293 // user id.
3294 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3295 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3296 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003297
3298 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003299 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003300
3301 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3302 // to each other.
3303 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3304 MoreAsserts.assertEmpty(targetUsers);
3305
3306 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3307 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3308 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003309 }
3310
3311 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3312 // Setup a device owner.
3313 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3314 setupDeviceOwner();
3315
3316 // Set up a managed profile managed by different package.
3317 final int MANAGED_PROFILE_USER_ID = 15;
3318 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3319 final ComponentName adminDifferentPackage =
3320 new ComponentName("another.package", "whatever.class");
3321 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3322
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003323 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003324 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003325 dpm.setAffiliationIds(admin1, userAffiliationIds);
3326
3327 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3328 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3329
Tony Mak2f26b792016-11-28 17:54:51 +00003330 // Calling from device owner admin, we should get zero bind device admin target users as
3331 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003332 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003333 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3334 MoreAsserts.assertEmpty(targetUsers);
3335
3336 // Calling from managed profile admin, we should still get zero target users for the same
3337 // reason.
3338 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3339 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3340 MoreAsserts.assertEmpty(targetUsers);
3341 }
3342
Charles Hee078db72017-10-19 18:03:20 +01003343 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003344 // Setup a device owner.
3345 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3346 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003347 // Lock task policy is updated when loading user data.
3348 verify(getServices().iactivityManager).updateLockTaskPackages(
3349 UserHandle.USER_SYSTEM, new String[0]);
3350 verify(getServices().iactivityManager).updateLockTaskFeatures(
3351 UserHandle.USER_SYSTEM, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003352
3353 // Set up a managed profile managed by different package (package name shouldn't matter)
3354 final int MANAGED_PROFILE_USER_ID = 15;
3355 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3356 final ComponentName adminDifferentPackage =
3357 new ComponentName("another.package", "whatever.class");
3358 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Charles Hee078db72017-10-19 18:03:20 +01003359 verify(getServices().iactivityManager).updateLockTaskPackages(
3360 MANAGED_PROFILE_USER_ID, new String[0]);
3361 verify(getServices().iactivityManager).updateLockTaskFeatures(
3362 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003363
3364 // The DO can still set lock task packages
3365 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3366 final String[] doPackages = {"doPackage1", "doPackage2"};
3367 dpm.setLockTaskPackages(admin1, doPackages);
3368 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3369 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3370 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Charles Hee078db72017-10-19 18:03:20 +01003371 verify(getServices().iactivityManager).updateLockTaskPackages(
3372 UserHandle.USER_SYSTEM, doPackages);
3373 // And the DO can still set lock task features
3374 final int doFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3375 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3376 dpm.setLockTaskFeatures(admin1, doFlags);
3377 verify(getServices().iactivityManager).updateLockTaskFeatures(
3378 UserHandle.USER_SYSTEM, doFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003379
3380 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3381 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3382 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003383 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3384 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3385 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3386 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003387 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
Charles Hee078db72017-10-19 18:03:20 +01003388 // And it shouldn't be able to setLockTaskFeatures.
3389 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3390 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3391 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3392 () -> dpm.setLockTaskFeatures(adminDifferentPackage, poFlags));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003393
3394 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003395 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003396 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3397 dpm.setAffiliationIds(admin1, userAffiliationIds);
3398
3399 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3400 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3401
3402 // Now the managed profile can set lock task packages.
3403 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3404 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3405 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3406 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003407 verify(getServices().iactivityManager).updateLockTaskPackages(
3408 MANAGED_PROFILE_USER_ID, poPackages);
3409 // And it can set lock task features.
3410 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
3411 verify(getServices().iactivityManager).updateLockTaskFeatures(
3412 MANAGED_PROFILE_USER_ID, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003413
3414 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003415 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003416 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3417 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003418 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3419 MANAGED_PROFILE_USER_ID, new String[0]);
3420 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3421 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003422
3423 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3424 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3425 }
3426
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003427 public void testIsDeviceManaged() throws Exception {
3428 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3429 setupDeviceOwner();
3430
3431 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3432 // find out that the device has a device owner.
3433 assertTrue(dpm.isDeviceManaged());
3434 mContext.binder.callingUid = 1234567;
3435 mContext.callerPermissions.add(permission.MANAGE_USERS);
3436 assertTrue(dpm.isDeviceManaged());
3437 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3438 mContext.binder.clearCallingIdentity();
3439 assertTrue(dpm.isDeviceManaged());
3440
3441 clearDeviceOwner();
3442
3443 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3444 // not have a device owner.
3445 mContext.binder.callingUid = 1234567;
3446 mContext.callerPermissions.add(permission.MANAGE_USERS);
3447 assertFalse(dpm.isDeviceManaged());
3448 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3449 mContext.binder.clearCallingIdentity();
3450 assertFalse(dpm.isDeviceManaged());
3451 }
3452
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003453 public void testDeviceOwnerOrganizationName() throws Exception {
3454 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3455 setupDeviceOwner();
3456
3457 dpm.setOrganizationName(admin1, "organization");
3458
3459 // Device owner can retrieve organization managing the device.
3460 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3461
3462 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3463 mContext.binder.callingUid = 1234567;
3464 mContext.callerPermissions.add(permission.MANAGE_USERS);
3465 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3466 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3467
3468 // System can retrieve organization managing the device.
3469 mContext.binder.clearCallingIdentity();
3470 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3471
3472 // Removing the device owner clears the organization managing the device.
3473 clearDeviceOwner();
3474 assertNull(dpm.getDeviceOwnerOrganizationName());
3475 }
3476
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003477 public void testWipeDataManagedProfile() throws Exception {
3478 final int MANAGED_PROFILE_USER_ID = 15;
3479 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3480 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3481 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3482
3483 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003484 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003485 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003486 // Get mock reason string since we throw an IAE with empty string input.
3487 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3488 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003489
3490 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003491 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003492 MANAGED_PROFILE_USER_ID);
3493 }
3494
3495 public void testWipeDataManagedProfileDisallowed() throws Exception {
3496 final int MANAGED_PROFILE_USER_ID = 15;
3497 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3498 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3499
3500 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003501 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003502 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3503
Pavel Grafov75c0a892017-05-18 17:28:27 +01003504 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003505 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3506 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3507 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003508 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3509 thenReturn("Just a test string.");
3510
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003511 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003512 // The PO is not allowed to remove the profile if the user restriction was set on the
3513 // profile by the system
3514 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3515 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003516 }
3517
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003518 public void testWipeDataDeviceOwner() throws Exception {
3519 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003520 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003521 UserManager.DISALLOW_FACTORY_RESET,
3522 UserHandle.SYSTEM))
3523 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003524 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3525 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003526
3527 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003528 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003529 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3530 /*wipeEuicc=*/ eq(false));
3531 }
3532
3533 public void testWipeEuiccDataEnabled() throws Exception {
3534 setDeviceOwner();
3535 when(getServices().userManager.getUserRestrictionSource(
3536 UserManager.DISALLOW_FACTORY_RESET,
3537 UserHandle.SYSTEM))
3538 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003539 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3540 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003541
3542 dpm.wipeData(WIPE_EUICC);
3543 verify(getServices().recoverySystem).rebootWipeUserData(
3544 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3545 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003546 }
3547
3548 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3549 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003550 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003551 UserManager.DISALLOW_FACTORY_RESET,
3552 UserHandle.SYSTEM))
3553 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003554 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3555 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003556 // The DO is not allowed to wipe the device if the user restriction was set
3557 // by the system
3558 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3559 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003560 }
3561
3562 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3563 final int MANAGED_PROFILE_USER_ID = 15;
3564 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3565 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3566
3567 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003568 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003569 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3570
Pavel Grafov75c0a892017-05-18 17:28:27 +01003571 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003572 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3573 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3574 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3575
3576 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3577 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3578
3579 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3580 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3581 // Failed password attempts on the parent user are taken into account, as there isn't a
3582 // separate work challenge.
3583 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3584 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3585 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3586
3587 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3588 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003589 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003590 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003591 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003592 }
3593
3594 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3595 throws Exception {
3596 final int MANAGED_PROFILE_USER_ID = 15;
3597 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3598 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3599
3600 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003601 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003602 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3603
Pavel Grafov75c0a892017-05-18 17:28:27 +01003604 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003605 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3606 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3607 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3608
3609 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3610 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3611
3612 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3613 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3614 // Failed password attempts on the parent user are taken into account, as there isn't a
3615 // separate work challenge.
3616 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3617 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3618 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3619
3620 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3621 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003622 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003623 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003624 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003625 }
3626
3627 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3628 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003629 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003630 UserManager.DISALLOW_FACTORY_RESET,
3631 UserHandle.SYSTEM))
3632 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3633
3634 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3635
3636 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3637 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3638 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3639 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3640 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3641
3642 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3643 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003644 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003645 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3646 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003647 }
3648
3649 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3650 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003651 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003652 UserManager.DISALLOW_FACTORY_RESET,
3653 UserHandle.SYSTEM))
3654 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3655
3656 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3657
3658 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3659 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3660 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3661 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3662 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3663
3664 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003665 verifyZeroInteractions(getServices().recoverySystem);
3666 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003667 .removeUserEvenWhenDisallowed(anyInt());
3668 }
3669
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003670 public void testGetPermissionGrantState() throws Exception {
3671 final String permission = "some.permission";
3672 final String app1 = "com.example.app1";
3673 final String app2 = "com.example.app2";
3674
Pavel Grafov75c0a892017-05-18 17:28:27 +01003675 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003676 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003677 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003678 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003679 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003680 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3681 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003682 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003683 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003684 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003685 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003686 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003687 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3688
3689 // System can retrieve permission grant state.
3690 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003691 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003692 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3693 dpm.getPermissionGrantState(null, app1, permission));
3694 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3695 dpm.getPermissionGrantState(null, app2, permission));
3696
3697 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003698 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3699 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003700 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3701 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003702
3703 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003704 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3705 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003706 setAsProfileOwner(admin1);
3707 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3708 dpm.getPermissionGrantState(admin1, app1, permission));
3709 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3710 dpm.getPermissionGrantState(admin1, app2, permission));
3711 }
3712
Rubin Xuaab7a412016-12-30 21:13:29 +00003713 public void testResetPasswordWithToken() throws Exception {
3714 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3715 setupDeviceOwner();
3716 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003717 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3718 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3719
Rubin Xuaab7a412016-12-30 21:13:29 +00003720 // test adding a token
3721 final byte[] token = new byte[32];
3722 final long handle = 123456;
3723 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003724 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003725 .thenReturn(handle);
3726 assertTrue(dpm.setResetPasswordToken(admin1, token));
3727
3728 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003729 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003730 .thenReturn(true);
3731 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3732
3733 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003734 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01003735 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
3736 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00003737 eq(UserHandle.USER_SYSTEM)))
3738 .thenReturn(true);
3739 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3740
3741 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003742 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003743 .thenReturn(true);
3744 assertTrue(dpm.clearResetPasswordToken(admin1));
3745 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003746
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003747 public void testIsActivePasswordSufficient() throws Exception {
3748 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3749 mContext.packageName = admin1.getPackageName();
3750 setupDeviceOwner();
3751
3752 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3753 dpm.setPasswordMinimumLength(admin1, 8);
3754 dpm.setPasswordMinimumLetters(admin1, 6);
3755 dpm.setPasswordMinimumLowerCase(admin1, 3);
3756 dpm.setPasswordMinimumUpperCase(admin1, 1);
3757 dpm.setPasswordMinimumNonLetter(admin1, 1);
3758 dpm.setPasswordMinimumNumeric(admin1, 1);
3759 dpm.setPasswordMinimumSymbols(admin1, 0);
3760
3761 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3762 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3763 8, 2,
3764 6, 1,
3765 0, 1);
3766
3767 setActivePasswordState(passwordMetricsNoSymbols);
3768 assertTrue(dpm.isActivePasswordSufficient());
3769
3770 initializeDpms();
3771 reset(mContext.spiedContext);
3772 assertTrue(dpm.isActivePasswordSufficient());
3773
3774 // This call simulates the user entering the password for the first time after a reboot.
3775 // This causes password metrics to be reloaded into memory. Until this happens,
3776 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3777 // even if the DPC changes password requirements so that the password no longer meets the
3778 // requirements. This is a known limitation of the current implementation of
3779 // isActivePasswordSufficient() - see b/34218769.
3780 setActivePasswordState(passwordMetricsNoSymbols);
3781 assertTrue(dpm.isActivePasswordSufficient());
3782
3783 dpm.setPasswordMinimumSymbols(admin1, 1);
3784 // This assertion would fail if we had not called setActivePasswordState() again after
3785 // initializeDpms() - see previous comment.
3786 assertFalse(dpm.isActivePasswordSufficient());
3787
3788 initializeDpms();
3789 reset(mContext.spiedContext);
3790 assertFalse(dpm.isActivePasswordSufficient());
3791
3792 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3793 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3794 7, 2,
3795 5, 1,
3796 1, 2);
3797
3798 setActivePasswordState(passwordMetricsWithSymbols);
3799 assertTrue(dpm.isActivePasswordSufficient());
3800 }
3801
Pavel Grafov75c0a892017-05-18 17:28:27 +01003802 private void setActivePasswordState(PasswordMetrics passwordMetrics)
3803 throws Exception {
3804 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003805 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003806
Pavel Grafov75c0a892017-05-18 17:28:27 +01003807 dpm.setActivePasswordState(passwordMetrics, userHandle);
3808 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003809
Pavel Grafov75c0a892017-05-18 17:28:27 +01003810 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3811 intent.setComponent(admin1);
3812 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3813
3814 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3815 MockUtils.checkIntent(intent),
3816 MockUtils.checkUserHandle(userHandle));
3817
3818 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
3819 // let it finish with system uid, otherwise it will throw and crash.
3820 flushTasks();
3821
3822 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003823 }
3824
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003825 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3826 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3827 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3828 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3829 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3830 DpmMockContext.SYSTEM_UID);
3831 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3832 DpmMockContext.SYSTEM_UID);
3833
3834 // Set up a device owner.
3835 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003836 setupDeviceOwner();
3837
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003838 // First and second user set IMEs manually.
3839 mContext.binder.callingUid = firstUserSystemUid;
3840 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3841 mContext.binder.callingUid = secondUserSystemUid;
3842 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003843
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003844 // Device owner changes IME for first user.
3845 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003846 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003847 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003848 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003849 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003850 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003851 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003852 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3853 mContext.binder.callingUid = firstUserSystemUid;
3854 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3855 mContext.binder.callingUid = secondUserSystemUid;
3856 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003857
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003858 // Second user changes IME manually.
3859 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3860 mContext.binder.callingUid = firstUserSystemUid;
3861 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3862 mContext.binder.callingUid = secondUserSystemUid;
3863 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003864
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003865 // First user changes IME manually.
3866 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3867 mContext.binder.callingUid = firstUserSystemUid;
3868 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3869 mContext.binder.callingUid = secondUserSystemUid;
3870 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003871
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003872 // Device owner changes IME for first user again.
3873 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003874 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003875 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003876 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003877 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003878 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003879 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3880 mContext.binder.callingUid = firstUserSystemUid;
3881 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3882 mContext.binder.callingUid = secondUserSystemUid;
3883 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003884
3885 // Restarting the DPMS should not lose information.
3886 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003887 mContext.binder.callingUid = firstUserSystemUid;
3888 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3889 mContext.binder.callingUid = secondUserSystemUid;
3890 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003891
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003892 // Device owner can find out whether it set the current IME itself.
3893 mContext.binder.callingUid = deviceOwnerUid;
3894 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003895
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003896 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003897 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003898 mContext.binder.callingUid = firstUserSystemUid;
3899 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3900 mContext.binder.callingUid = secondUserSystemUid;
3901 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003902 }
3903
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003904 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3905 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3906 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3907 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3908 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3909 DpmMockContext.SYSTEM_UID);
3910 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3911 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003912
3913 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003914 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003915 setupProfileOwner();
3916
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003917 // First and second user set IMEs manually.
3918 mContext.binder.callingUid = firstUserSystemUid;
3919 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3920 mContext.binder.callingUid = secondUserSystemUid;
3921 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003922
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003923 // Profile owner changes IME for second user.
3924 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003925 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003926 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003927 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003928 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003929 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003930 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003931 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3932 mContext.binder.callingUid = firstUserSystemUid;
3933 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3934 mContext.binder.callingUid = secondUserSystemUid;
3935 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003936
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003937 // First user changes IME manually.
3938 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3939 mContext.binder.callingUid = firstUserSystemUid;
3940 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3941 mContext.binder.callingUid = secondUserSystemUid;
3942 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003943
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003944 // Second user changes IME manually.
3945 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3946 mContext.binder.callingUid = firstUserSystemUid;
3947 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3948 mContext.binder.callingUid = secondUserSystemUid;
3949 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003950
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003951 // Profile owner changes IME for second user again.
3952 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003953 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003954 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003955 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003956 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003957 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003958 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3959 mContext.binder.callingUid = firstUserSystemUid;
3960 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3961 mContext.binder.callingUid = secondUserSystemUid;
3962 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003963
3964 // Restarting the DPMS should not lose information.
3965 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003966 mContext.binder.callingUid = firstUserSystemUid;
3967 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3968 mContext.binder.callingUid = secondUserSystemUid;
3969 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003970
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003971 // Profile owner can find out whether it set the current IME itself.
3972 mContext.binder.callingUid = profileOwnerUid;
3973 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003974
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003975 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003976 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003977 mContext.binder.callingUid = firstUserSystemUid;
3978 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3979 mContext.binder.callingUid = secondUserSystemUid;
3980 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003981 }
Rubin Xuaab7a412016-12-30 21:13:29 +00003982
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003983 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
3984 throws Exception {
3985 // Set up a device owner.
3986 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3987 setupDeviceOwner();
3988 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3989 }
3990
3991 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
3992 throws Exception {
3993 // Set up a profile owner.
3994 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3995 setupProfileOwner();
3996 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3997 }
3998
3999 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4000 int adminUid) throws Exception {
4001 mContext.binder.callingUid = adminUid;
4002 final int userId = UserHandle.getUserId(adminUid);
4003
4004 final String packageName = "some.package";
4005 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4006 admin1, Collections.singletonList(packageName)));
4007 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4008
4009 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4010 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4011
4012 // Attempt to set to empty list (which means no listener is whitelisted)
4013 mContext.binder.callingUid = adminUid;
4014 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004015 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004016 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4017
4018 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4019 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4020 }
4021
4022 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4023 // Set up a managed profile
4024 final int MANAGED_PROFILE_USER_ID = 15;
4025 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4026 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4027 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4028
4029 final String permittedListener = "some.package";
4030 setupPackageInPackageManager(
4031 permittedListener,
4032 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4033 /*appId=*/ 12345, /*flags=*/ 0);
4034
4035 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4036 admin1, Collections.singletonList(permittedListener)));
4037
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004038 // isNotificationListenerServicePermitted should throw if not called from System.
4039 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4040 () -> dpms.isNotificationListenerServicePermitted(
4041 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004042
4043 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4044 assertTrue(dpms.isNotificationListenerServicePermitted(
4045 permittedListener, MANAGED_PROFILE_USER_ID));
4046 }
4047
4048 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4049 throws Exception {
4050 // Set up a managed profile
4051 final int MANAGED_PROFILE_USER_ID = 15;
4052 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4053 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4054 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4055
4056 final String permittedListener = "permitted.package";
4057 int appId = 12345;
4058 setupPackageInPackageManager(
4059 permittedListener,
4060 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4061 appId, /*flags=*/ 0);
4062
4063 final String notPermittedListener = "not.permitted.package";
4064 setupPackageInPackageManager(
4065 notPermittedListener,
4066 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4067 ++appId, /*flags=*/ 0);
4068
4069 final String systemListener = "system.package";
4070 setupPackageInPackageManager(
4071 systemListener,
4072 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4073 ++appId, ApplicationInfo.FLAG_SYSTEM);
4074
4075 // By default all packages are allowed
4076 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4077
4078 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4079 assertTrue(dpms.isNotificationListenerServicePermitted(
4080 permittedListener, MANAGED_PROFILE_USER_ID));
4081 assertTrue(dpms.isNotificationListenerServicePermitted(
4082 notPermittedListener, MANAGED_PROFILE_USER_ID));
4083 assertTrue(dpms.isNotificationListenerServicePermitted(
4084 systemListener, MANAGED_PROFILE_USER_ID));
4085
4086 // Setting only one package in the whitelist
4087 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4088 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4089 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004090 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004091 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4092 assertEquals(1, permittedListeners.size());
4093 assertEquals(permittedListener, permittedListeners.get(0));
4094
4095 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4096 assertTrue(dpms.isNotificationListenerServicePermitted(
4097 permittedListener, MANAGED_PROFILE_USER_ID));
4098 assertFalse(dpms.isNotificationListenerServicePermitted(
4099 notPermittedListener, MANAGED_PROFILE_USER_ID));
4100 // System packages are always allowed (even if not in the whitelist)
4101 assertTrue(dpms.isNotificationListenerServicePermitted(
4102 systemListener, MANAGED_PROFILE_USER_ID));
4103
4104 // Setting an empty whitelist - only system listeners allowed
4105 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4106 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004107 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004108 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4109
4110 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4111 assertFalse(dpms.isNotificationListenerServicePermitted(
4112 permittedListener, MANAGED_PROFILE_USER_ID));
4113 assertFalse(dpms.isNotificationListenerServicePermitted(
4114 notPermittedListener, MANAGED_PROFILE_USER_ID));
4115 // System packages are always allowed (even if not in the whitelist)
4116 assertTrue(dpms.isNotificationListenerServicePermitted(
4117 systemListener, MANAGED_PROFILE_USER_ID));
4118
4119 // Setting a null whitelist - all listeners allowed
4120 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4121 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4122 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4123
4124 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4125 assertTrue(dpms.isNotificationListenerServicePermitted(
4126 permittedListener, MANAGED_PROFILE_USER_ID));
4127 assertTrue(dpms.isNotificationListenerServicePermitted(
4128 notPermittedListener, MANAGED_PROFILE_USER_ID));
4129 assertTrue(dpms.isNotificationListenerServicePermitted(
4130 systemListener, MANAGED_PROFILE_USER_ID));
4131 }
4132
4133 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4134 throws Exception {
4135 // Set up a managed profile
4136 final int MANAGED_PROFILE_USER_ID = 15;
4137 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4138 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4139 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4140
4141 final String nonSystemPackage = "non.system.package";
4142 int appId = 12345;
4143 setupPackageInPackageManager(
4144 nonSystemPackage,
4145 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4146 appId, /*flags=*/ 0);
4147
4148 final String systemListener = "system.package";
4149 setupPackageInPackageManager(
4150 systemListener,
4151 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4152 ++appId, ApplicationInfo.FLAG_SYSTEM);
4153
4154 // By default all packages are allowed (for all profiles)
4155 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4156
4157 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4158 assertTrue(dpms.isNotificationListenerServicePermitted(
4159 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4160 assertTrue(dpms.isNotificationListenerServicePermitted(
4161 systemListener, MANAGED_PROFILE_USER_ID));
4162 assertTrue(dpms.isNotificationListenerServicePermitted(
4163 nonSystemPackage, UserHandle.USER_SYSTEM));
4164 assertTrue(dpms.isNotificationListenerServicePermitted(
4165 systemListener, UserHandle.USER_SYSTEM));
4166
4167 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4168 // all allowed in primary profile
4169 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4170 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004171 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004172 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4173
4174 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4175 assertFalse(dpms.isNotificationListenerServicePermitted(
4176 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4177 assertTrue(dpms.isNotificationListenerServicePermitted(
4178 systemListener, MANAGED_PROFILE_USER_ID));
4179 assertTrue(dpms.isNotificationListenerServicePermitted(
4180 nonSystemPackage, UserHandle.USER_SYSTEM));
4181 assertTrue(dpms.isNotificationListenerServicePermitted(
4182 systemListener, UserHandle.USER_SYSTEM));
4183 }
4184
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004185 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004186 mServiceContext.packageName = mRealTestContext.getPackageName();
4187 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4188 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004189 setDeviceOwner();
4190
Pavel Grafov75c0a892017-05-18 17:28:27 +01004191 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004192 }
4193
4194 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004195 mServiceContext.packageName = mRealTestContext.getPackageName();
4196 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4197 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004198 setAsProfileOwner(admin1);
4199
Pavel Grafov75c0a892017-05-18 17:28:27 +01004200 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4201 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004202 }
4203
4204 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004205 mServiceContext.packageName = mRealTestContext.getPackageName();
4206 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4207 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004208 setAsProfileOwner(admin1);
4209
Pavel Grafov75c0a892017-05-18 17:28:27 +01004210 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4211 caller.packageName = "com.example.delegate";
4212 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4213 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004214
Pavel Grafov75c0a892017-05-18 17:28:27 +01004215 // Make caller a delegated cert installer.
4216 runAsCaller(mAdmin1Context, dpms,
4217 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004218
4219 verifyCanGetOwnerInstalledCaCerts(null, caller);
4220 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004221 }
4222
Robin Lee2c68dad2017-03-17 12:50:24 +00004223 private void verifyCanGetOwnerInstalledCaCerts(
4224 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004225 final String alias = "cert";
4226 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004227
4228 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004229 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004230 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4231 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004232 }
4233 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4234
4235 // caller: device admin or delegated certificate installer
4236 callerContext.applicationInfo = new ApplicationInfo();
4237 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4238
4239 // system_server
4240 final DpmMockContext serviceContext = mContext;
4241 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004242 getServices().addPackageContext(callerUser, admin1Context);
4243 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004244
4245 // Install a CA cert.
4246 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004247 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004248 .thenReturn(alias);
4249 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004250 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004251 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004252 });
4253
Pavel Grafov75c0a892017-05-18 17:28:27 +01004254 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4255 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4256 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004257 flushTasks();
4258
Robin Lee2c68dad2017-03-17 12:50:24 +00004259 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4260
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004261 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004262 runAsCaller(admin1Context, dpms, (dpm) -> {
4263 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004264 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004265 ownerInstalledCaCerts.addAll(installedCaCerts);
4266 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004267
4268 // Restarting the DPMS should not lose information.
4269 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004270 runAsCaller(admin1Context, dpms, (dpm) ->
4271 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004272
4273 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004274 runAsCaller(serviceContext, dpms, (dpm) -> {
4275 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004276
Robin Lee2c68dad2017-03-17 12:50:24 +00004277 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004278 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004279 });
4280
Pavel Grafov75c0a892017-05-18 17:28:27 +01004281 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4282 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4283 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004284 flushTasks();
4285
4286 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4287 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004288 runAsCaller(admin1Context, dpms, (dpm) -> {
4289 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4290 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004291 }
4292
Robin Lee2c68dad2017-03-17 12:50:24 +00004293 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4294 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004295 final String alias = "cert";
4296 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004297
4298 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004299 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004300 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4301 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004302 }
4303 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4304
4305 // caller: device admin or delegated certificate installer
4306 callerContext.applicationInfo = new ApplicationInfo();
4307 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4308
4309 // system_server
4310 final DpmMockContext serviceContext = mContext;
4311 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004312 getServices().addPackageContext(callerUser, admin1Context);
4313 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004314
4315 // Install a CA cert as caller
4316 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004317 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004318 .thenReturn(alias);
4319 assertTrue(dpm.installCaCert(callerName, caCert));
4320 });
4321
4322 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004323 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004324 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004325 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4326 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4327 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004328 flushTasks();
4329
Robin Lee2c68dad2017-03-17 12:50:24 +00004330 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004331 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004332
4333 runAsCaller(serviceContext, dpms, (dpm) -> {
4334 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4335 assertNotNull(ownerInstalledCaCerts);
4336 assertTrue(ownerInstalledCaCerts.isEmpty());
4337 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004338 }
4339
Victor Chang3e794af2016-03-04 13:48:17 +00004340 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004341 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004342 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4343 dpms.notifyChangeToContentObserver(
4344 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4345 }
4346
4347 private void assertProvisioningAllowed(String action, boolean expected) {
4348 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4349 dpm.isProvisioningAllowed(action));
4350 }
Tony Mak2f26b792016-11-28 17:54:51 +00004351
Nicolas Prevot45d29072017-01-18 16:11:19 +00004352 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4353 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004354 final String previousPackageName = mContext.packageName;
4355 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004356
4357 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4358 mContext.packageName = packageName;
4359 mMockContext.binder.callingUid = uid;
4360 assertProvisioningAllowed(action, expected);
4361
4362 // Set the previous package name / calling uid to go back to the initial state.
4363 mContext.packageName = previousPackageName;
4364 mMockContext.binder.callingUid = previousUid;
4365 }
4366
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004367 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004368 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4369 }
4370
4371 private void assertCheckProvisioningPreCondition(
4372 String action, String packageName, int provisioningCondition) {
4373 assertEquals("checkProvisioningPreCondition("
4374 + action + ", " + packageName + ") returning unexpected result",
4375 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004376 }
4377
Tony Mak2f26b792016-11-28 17:54:51 +00004378 /**
4379 * Setup a managed profile with the specified admin and its uid.
4380 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4381 * @param adminUid uid of the admin package.
4382 * @param copyFromAdmin package information for {@code admin} will be built based on this
4383 * component's information.
4384 */
4385 private void addManagedProfile(
4386 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4387 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004388 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004389 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4390 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4391 dpm.setActiveAdmin(admin, false, userId);
4392 assertTrue(dpm.setProfileOwner(admin, null, userId));
4393 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4394 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004395
4396 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004397 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004398 */
Robin Leeabaa0692017-02-20 20:54:22 +00004399 private static StringParceledListSlice asSlice(String[] s) {
4400 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004401 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004402
4403 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004404 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4405 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004406
Robin Lee2c68dad2017-03-17 12:50:24 +00004407 // We can't let exceptions happen on the background thread. Throw them here if they happen
4408 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004409 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004410 }
Victor Chang3e794af2016-03-04 13:48:17 +00004411}