blob: 70e4b6dff84c64a78822a717b9a19dbd74cc6cb3 [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;
37import static org.mockito.Mockito.never;
38import static org.mockito.Mockito.nullable;
39import static org.mockito.Mockito.reset;
40import static org.mockito.Mockito.timeout;
41import static org.mockito.Mockito.times;
42import static org.mockito.Mockito.verify;
43import static org.mockito.Mockito.verifyZeroInteractions;
44import static org.mockito.Mockito.when;
45import static org.mockito.hamcrest.MockitoHamcrest.argThat;
46
Makoto Onukif76b06a2015-09-22 15:03:44 -070047import android.Manifest.permission;
48import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000049import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070050import android.app.admin.DeviceAdminReceiver;
51import android.app.admin.DevicePolicyManager;
52import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010053import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070054import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070055import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000056import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000057import android.content.pm.ApplicationInfo;
58import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070059import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010060import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000061import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000062import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010063import android.graphics.Color;
64import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080065import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080066import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070067import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080068import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070069import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070070import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010071import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080072import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010073import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000074import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080075import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000076import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010077import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070078import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070079
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010080import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000081import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000082import com.android.server.LocalServices;
83import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000084import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000085
Robin Lee7f5c91c2017-02-08 21:27:02 +000086import org.hamcrest.BaseMatcher;
87import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070088import org.mockito.invocation.InvocationOnMock;
89import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070090
Makoto Onukic8a5a552015-11-19 14:29:12 -080091import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000092import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000093import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070094import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070096import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010097import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000098import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070099
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700101 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000102 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103 m FrameworksServicesTests &&
104 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000105 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800107 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108
109 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000110 *
111 * , or:
112 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000114@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100115@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000117 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
118 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
119 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100120 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
121 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000122
Pavel Grafov75c0a892017-05-18 17:28:27 +0100123 // TODO replace all instances of this with explicit {@link #mServiceContext}.
124 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700125 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100126
127 private DpmMockContext mServiceContext;
128 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700129 public DevicePolicyManager dpm;
130 public DevicePolicyManagerServiceTestable dpms;
131
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100132 /*
133 * The CA cert below is the content of cacert.pem as generated by:
134 *
135 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
136 */
137 private static final String TEST_CA =
138 "-----BEGIN CERTIFICATE-----\n" +
139 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
140 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
141 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
142 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
143 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
144 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
145 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
146 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
147 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
148 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
149 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
150 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
151 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
152 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
153 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
154 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
155 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
156 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
157 "wQ==\n" +
158 "-----END CERTIFICATE-----\n";
159
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700160 @Override
161 protected void setUp() throws Exception {
162 super.setUp();
163
164 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100165 mServiceContext = mContext;
166 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
167 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700168 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100169 doReturn(Collections.singletonList(new ResolveInfo()))
170 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
171 any(Intent.class),
172 anyInt(),
173 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700174
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800175 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100176 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800177
Makoto Onukia52562c2015-10-01 16:12:31 -0700178 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700179
Makoto Onukid932f762015-09-29 16:53:38 -0700180 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
181 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
182 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800183 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700184
Pavel Grafov75c0a892017-05-18 17:28:27 +0100185 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
186 mAdmin1Context.packageName = admin1.getPackageName();
187 mAdmin1Context.applicationInfo = new ApplicationInfo();
188 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
189
Makoto Onukib643fb02015-09-22 15:03:44 -0700190 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700191 }
192
Robin Lee2c68dad2017-03-17 12:50:24 +0000193 @Override
194 protected void tearDown() throws Exception {
195 flushTasks();
196 super.tearDown();
197 }
198
Makoto Onukia52562c2015-10-01 16:12:31 -0700199 private void initializeDpms() {
200 // Need clearCallingIdentity() to pass permission checks.
201 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100202 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700203
Pavel Grafov75c0a892017-05-18 17:28:27 +0100204 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
205 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
206 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700207
Pavel Grafov75c0a892017-05-18 17:28:27 +0100208 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700209
Pavel Grafov75c0a892017-05-18 17:28:27 +0100210 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700211 }
212
Makoto Onukib643fb02015-09-22 15:03:44 -0700213 private void setUpUserManager() {
214 // Emulate UserManager.set/getApplicationRestriction().
215 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
216
217 // UM.setApplicationRestrictions() will save to appRestrictions.
218 doAnswer(new Answer<Void>() {
219 @Override
220 public Void answer(InvocationOnMock invocation) throws Throwable {
221 String pkg = (String) invocation.getArguments()[0];
222 Bundle bundle = (Bundle) invocation.getArguments()[1];
223 UserHandle user = (UserHandle) invocation.getArguments()[2];
224
225 appRestrictions.put(Pair.create(pkg, user), bundle);
226
227 return null;
228 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100229 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100230 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700231
232 // UM.getApplicationRestrictions() will read from appRestrictions.
233 doAnswer(new Answer<Bundle>() {
234 @Override
235 public Bundle answer(InvocationOnMock invocation) throws Throwable {
236 String pkg = (String) invocation.getArguments()[0];
237 UserHandle user = (UserHandle) invocation.getArguments()[1];
238
239 return appRestrictions.get(Pair.create(pkg, user));
240 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100241 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700242 anyString(), any(UserHandle.class));
243
Makoto Onukid932f762015-09-29 16:53:38 -0700244 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100245 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700246 }
247
248 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100249 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700250
Pavel Grafov75c0a892017-05-18 17:28:27 +0100251 mServiceContext.binder.callingUid =
252 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
253 runAsCaller(mServiceContext, dpms, dpm -> {
254 // PO needs to be a DA.
255 dpm.setActiveAdmin(admin, /*replace=*/ false);
256 // Fire!
257 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
258 // Check
259 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
260 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700261
Pavel Grafov75c0a892017-05-18 17:28:27 +0100262 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700263 }
264
265 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100266 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700267 .thenReturn(false);
268
269 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100270 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700271
272 // If the device has no DPMS feature, it shouldn't register the local service.
273 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
274 }
275
276 /**
277 * Caller doesn't have proper permissions.
278 */
279 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700280 // 1. Failure cases.
281
282 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100283 assertExpectException(SecurityException.class, /* messageRegex= */ null,
284 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700285
286 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
287 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100288
289 assertExpectException(SecurityException.class, /* messageRegex= */ null,
290 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700291 }
292
Makoto Onukif76b06a2015-09-22 15:03:44 -0700293 /**
294 * Test for:
295 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800296 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700297 * {@link DevicePolicyManager#isAdminActive}
298 * {@link DevicePolicyManager#isAdminActiveAsUser}
299 * {@link DevicePolicyManager#getActiveAdmins}
300 * {@link DevicePolicyManager#getActiveAdminsAsUser}
301 */
302 public void testSetActiveAdmin() throws Exception {
303 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700304 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
305
Makoto Onukif76b06a2015-09-22 15:03:44 -0700306 // 2. Call the API.
307 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700308
309 // 3. Verify internal calls.
310
311 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700312 verify(mContext.spiedContext).sendBroadcastAsUser(
313 MockUtils.checkIntentAction(
314 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
315 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
316 verify(mContext.spiedContext).sendBroadcastAsUser(
317 MockUtils.checkIntentAction(
318 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700319 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
320
Pavel Grafov75c0a892017-05-18 17:28:27 +0100321 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700322 eq(admin1.getPackageName()),
323 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
324 eq(PackageManager.DONT_KILL_APP),
325 eq(DpmMockContext.CALLER_USER_HANDLE),
326 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700327
328 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700329
330 // Make sure it's active admin1.
331 assertTrue(dpm.isAdminActive(admin1));
332 assertFalse(dpm.isAdminActive(admin2));
333 assertFalse(dpm.isAdminActive(admin3));
334
335 // But not admin1 for a different user.
336
337 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
338 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
339 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
340
341 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
342 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
343
344 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
345
346 // Next, add one more admin.
347 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700348 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700349 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700350
351 dpm.setActiveAdmin(admin2, /* replace =*/ false);
352
353 // Now we have two admins.
354 assertTrue(dpm.isAdminActive(admin1));
355 assertTrue(dpm.isAdminActive(admin2));
356 assertFalse(dpm.isAdminActive(admin3));
357
358 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
359 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100360 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700361 eq(admin1.getPackageName()),
362 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
363 eq(PackageManager.DONT_KILL_APP),
364 eq(DpmMockContext.CALLER_USER_HANDLE),
365 anyString());
366
367 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100368 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
369 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700370
371 // 5. Add the same admin1 again with replace, which should succeed.
372 dpm.setActiveAdmin(admin1, /* replace =*/ true);
373
374 // TODO make sure it's replaced.
375
376 // 6. Test getActiveAdmins()
377 List<ComponentName> admins = dpm.getActiveAdmins();
378 assertEquals(2, admins.size());
379 assertEquals(admin1, admins.get(0));
380 assertEquals(admin2, admins.get(1));
381
382 // Another user has no admins.
383 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
384
385 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
386 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
387
388 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
389 }
390
Makoto Onukid932f762015-09-29 16:53:38 -0700391 public void testSetActiveAdmin_multiUsers() throws Exception {
392
393 final int ANOTHER_USER_ID = 100;
394 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
395
Pavel Grafov75c0a892017-05-18 17:28:27 +0100396 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700397
398 // Set up pacakge manager for the other user.
399 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700400
401 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
402
403 dpm.setActiveAdmin(admin1, /* replace =*/ false);
404
405 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
406 dpm.setActiveAdmin(admin2, /* replace =*/ false);
407
408
409 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
410 assertTrue(dpm.isAdminActive(admin1));
411 assertFalse(dpm.isAdminActive(admin2));
412
413 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
414 assertFalse(dpm.isAdminActive(admin1));
415 assertTrue(dpm.isAdminActive(admin2));
416 }
417
Makoto Onukif76b06a2015-09-22 15:03:44 -0700418 /**
419 * Test for:
420 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800421 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700422 */
423 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
424 // 1. Make sure the caller has proper permissions.
425 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
426
427 dpm.setActiveAdmin(admin1, /* replace =*/ false);
428 assertTrue(dpm.isAdminActive(admin1));
429
430 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100431 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
432 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700433 }
434
435 /**
436 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800437 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
438 * BIND_DEVICE_ADMIN.
439 */
440 public void testSetActiveAdmin_permissionCheck() throws Exception {
441 // 1. Make sure the caller has proper permissions.
442 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
443
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100444 assertExpectException(IllegalArgumentException.class,
445 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
446 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800447 assertFalse(dpm.isAdminActive(adminNoPerm));
448
449 // Change the target API level to MNC. Now it can be set as DA.
450 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
451 VERSION_CODES.M);
452 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
453 assertTrue(dpm.isAdminActive(adminNoPerm));
454
455 // TODO Test the "load from the file" case where DA will still be loaded even without
456 // BIND_DEVICE_ADMIN and target API is N.
457 }
458
459 /**
460 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700461 * {@link DevicePolicyManager#removeActiveAdmin}
462 */
463 public void testRemoveActiveAdmin_SecurityException() {
464 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
465
466 // Add admin.
467
468 dpm.setActiveAdmin(admin1, /* replace =*/ false);
469
470 assertTrue(dpm.isAdminActive(admin1));
471
472 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
473
474 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100475 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
476 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700477
478 // Try to remove active admin with a different caller userid should fail too, without
479 // having MANAGE_DEVICE_ADMINS.
480 mContext.callerPermissions.clear();
481
Makoto Onukid932f762015-09-29 16:53:38 -0700482 // Change the caller, and call into DPMS directly with a different user-id.
483
Makoto Onukif76b06a2015-09-22 15:03:44 -0700484 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100485 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
486 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700487 }
488
489 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800490 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
491 * (because we can't send the remove broadcast).
492 */
493 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
494 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
495
496 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
497
498 // Add admin.
499
500 dpm.setActiveAdmin(admin1, /* replace =*/ false);
501
502 assertTrue(dpm.isAdminActive(admin1));
503
504 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
505
506 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100507 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800508 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100509 assertExpectException(IllegalStateException.class,
510 /* messageRegex= */ "User must be running and unlocked",
511 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800512
513 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
514
515 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100516 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800517 .thenReturn(true);
518
519 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700520 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800521 }
522
523 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700524 * Test for:
525 * {@link DevicePolicyManager#removeActiveAdmin}
526 */
Makoto Onukid932f762015-09-29 16:53:38 -0700527 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700528 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
529
530 // Add admin1.
531
532 dpm.setActiveAdmin(admin1, /* replace =*/ false);
533
534 assertTrue(dpm.isAdminActive(admin1));
535 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
536
537 // Different user, but should work, because caller has proper permissions.
538 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700539
540 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700541 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700542
543 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700544 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700545
546 // TODO DO Still can't be removed in this case.
547 }
548
549 /**
550 * Test for:
551 * {@link DevicePolicyManager#removeActiveAdmin}
552 */
553 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
554 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
555 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
556
557 // Add admin1.
558
559 dpm.setActiveAdmin(admin1, /* replace =*/ false);
560
561 assertTrue(dpm.isAdminActive(admin1));
562 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
563
564 // Broadcast from saveSettingsLocked().
565 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
566 MockUtils.checkIntentAction(
567 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
568 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
569
570 // Remove. No permissions, but same user, so it'll work.
571 mContext.callerPermissions.clear();
572 dpm.removeActiveAdmin(admin1);
573
Makoto Onukif76b06a2015-09-22 15:03:44 -0700574 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
575 MockUtils.checkIntentAction(
576 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
577 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
578 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700579 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700580 eq(dpms.mHandler),
581 eq(Activity.RESULT_OK),
582 isNull(String.class),
583 isNull(Bundle.class));
584
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700585 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700586
587 // Again broadcast from saveSettingsLocked().
588 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
589 MockUtils.checkIntentAction(
590 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
591 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
592
593 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700594 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700595
596 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000597 * Test for: @{link DevicePolicyManager#setActivePasswordState}
598 *
599 * Validates that when the password for a user changes, the notification broadcast intent
600 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
601 * addition to ones in the original user.
602 */
603 public void testSetActivePasswordState_sendToProfiles() throws Exception {
604 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
605
606 final int MANAGED_PROFILE_USER_ID = 78;
607 final int MANAGED_PROFILE_ADMIN_UID =
608 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
609
610 // Setup device owner.
611 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
612 mContext.packageName = admin1.getPackageName();
613 setupDeviceOwner();
614
615 // Add a managed profile belonging to the system user.
616 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
617
618 // Change the parent user's password.
619 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
620
621 // Both the device owner and the managed profile owner should receive this broadcast.
622 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
623 intent.setComponent(admin1);
624 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
625
626 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
627 MockUtils.checkIntent(intent),
628 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
629 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
630 MockUtils.checkIntent(intent),
631 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
632 }
633
634 /**
635 * Test for: @{link DevicePolicyManager#setActivePasswordState}
636 *
637 * Validates that when the password for a managed profile changes, the notification broadcast
638 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
639 * its parent.
640 */
641 public void testSetActivePasswordState_notSentToParent() throws Exception {
642 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
643
644 final int MANAGED_PROFILE_USER_ID = 78;
645 final int MANAGED_PROFILE_ADMIN_UID =
646 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
647
648 // Setup device owner.
649 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
650 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100651 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000652 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
653 setupDeviceOwner();
654
655 // Add a managed profile belonging to the system user.
656 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
657
658 // Change the profile's password.
659 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
660
661 // Both the device owner and the managed profile owner should receive this broadcast.
662 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
663 intent.setComponent(admin1);
664 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
665
666 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
667 MockUtils.checkIntent(intent),
668 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
669 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
670 MockUtils.checkIntent(intent),
671 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
672 }
673 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000674 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700675 */
676 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000677 setDeviceOwner();
678
679 // Try to set a profile owner on the same user, which should fail.
680 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
681 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100682 assertExpectException(IllegalStateException.class,
683 /* messageRegex= */ "already has a device owner",
684 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000685
686 // DO admin can't be deactivated.
687 dpm.removeActiveAdmin(admin1);
688 assertTrue(dpm.isAdminActive(admin1));
689
690 // TODO Test getDeviceOwnerName() too. To do so, we need to change
691 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
692 }
693
694 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700695 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800696 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700697 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
698 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
699
Makoto Onukid932f762015-09-29 16:53:38 -0700700 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700701 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
702
Makoto Onukid932f762015-09-29 16:53:38 -0700703 // Make sure admin1 is installed on system user.
704 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700705
Makoto Onukic8a5a552015-11-19 14:29:12 -0800706 // Check various get APIs.
707 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
708
Makoto Onukib643fb02015-09-22 15:03:44 -0700709 // DO needs to be an DA.
710 dpm.setActiveAdmin(admin1, /* replace =*/ false);
711
712 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700713 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700714
Makoto Onukic8a5a552015-11-19 14:29:12 -0800715 // getDeviceOwnerComponent should return the admin1 component.
716 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
717 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
718
719 // Check various get APIs.
720 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
721
722 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
723 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
724 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
725 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
726
727 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
728
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000729 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100730 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000731 eq(admin1.getPackageName()));
732
Makoto Onukib643fb02015-09-22 15:03:44 -0700733 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100734 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700735 eq(UserHandle.USER_SYSTEM), eq(false));
736
737 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
738 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
739 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
740
Makoto Onukic8a5a552015-11-19 14:29:12 -0800741 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700742 }
743
Makoto Onukic8a5a552015-11-19 14:29:12 -0800744 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
745 final int origCallingUser = mContext.binder.callingUid;
746 final List origPermissions = new ArrayList(mContext.callerPermissions);
747 mContext.callerPermissions.clear();
748
749 mContext.callerPermissions.add(permission.MANAGE_USERS);
750
751 mContext.binder.callingUid = Process.SYSTEM_UID;
752
753 // TODO Test getDeviceOwnerName() too. To do so, we need to change
754 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
755 if (hasDeviceOwner) {
756 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
757 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
758 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
759
760 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
761 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
762 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
763 } else {
764 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
765 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
766 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
767
768 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
769 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
770 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
771 }
772
773 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
774 if (hasDeviceOwner) {
775 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
776 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
777 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
778
779 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
780 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
781 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
782 } else {
783 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
784 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
785 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
786
787 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
788 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
789 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
790 }
791
792 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
793 // Still with MANAGE_USERS.
794 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
795 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
796 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
797
798 if (hasDeviceOwner) {
799 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
800 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
801 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
802 } else {
803 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
804 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
805 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
806 }
807
808 mContext.binder.callingUid = Process.SYSTEM_UID;
809 mContext.callerPermissions.remove(permission.MANAGE_USERS);
810 // System can still call "OnAnyUser" without MANAGE_USERS.
811 if (hasDeviceOwner) {
812 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
813 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
814 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
815
816 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
817 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
818 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
819 } else {
820 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
821 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
822 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
823
824 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
825 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
826 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
827 }
828
829 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
830 // Still no MANAGE_USERS.
831 if (hasDeviceOwner) {
832 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
833 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
834 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
835 } else {
836 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
837 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
838 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
839 }
840
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100841 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
842 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
843 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
844 dpm::getDeviceOwnerComponentOnAnyUser);
845 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
846 dpm::getDeviceOwnerUserId);
847 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
848 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800849
850 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
851 // Still no MANAGE_USERS.
852 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
853 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
854 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
855
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100856 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
857 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
858 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
859 dpm::getDeviceOwnerComponentOnAnyUser);
860 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
861 dpm::getDeviceOwnerUserId);
862 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
863 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800864
865 // Restore.
866 mContext.binder.callingUid = origCallingUser;
867 mContext.callerPermissions.addAll(origPermissions);
868 }
869
870
Makoto Onukib643fb02015-09-22 15:03:44 -0700871 /**
872 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
873 */
874 public void testSetDeviceOwner_noSuchPackage() {
875 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800876 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700877 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
878 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
879
880 // Call from a process on the system user.
881 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
882
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100883 assertExpectException(IllegalArgumentException.class,
884 /* messageRegex= */ "Invalid component",
885 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -0700886 }
887
888 public void testSetDeviceOwner_failures() throws Exception {
889 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
890 }
891
Makoto Onukia52562c2015-10-01 16:12:31 -0700892 public void testClearDeviceOwner() throws Exception {
893 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800894 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700895 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
896 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
897
898 // Set admin1 as a DA to the secondary user.
899 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
900
901 dpm.setActiveAdmin(admin1, /* replace =*/ false);
902
903 // Set admin 1 as the DO to the system user.
904
905 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
906 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
907 dpm.setActiveAdmin(admin1, /* replace =*/ false);
908 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
909
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000910 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100911 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000912 eq(admin1.getPackageName()));
913
Makoto Onukic8a5a552015-11-19 14:29:12 -0800914 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700915
Makoto Onuki90b89652016-01-28 14:44:18 -0800916 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100917 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000918 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800919
920 assertTrue(dpm.isAdminActive(admin1));
921 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
922
Makoto Onukia52562c2015-10-01 16:12:31 -0700923 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100924 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -0700925
926 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100927 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
928 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800929
930 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100931 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100932 assertExpectException(IllegalStateException.class,
933 /* messageRegex= */ "User must be running and unlocked",
934 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800935
Pavel Grafov75c0a892017-05-18 17:28:27 +0100936 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
937 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700938 dpm.clearDeviceOwnerApp(admin1.getPackageName());
939
940 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800941 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700942
Pavel Grafov75c0a892017-05-18 17:28:27 +0100943 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000944 eq(false),
945 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
946
Pavel Grafov75c0a892017-05-18 17:28:27 +0100947 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -0800948 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100949 eq(null),
950 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800951
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700952 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100953
954 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
955 // and once for clearing it.
956 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
957 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
958 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700959 // TODO Check other calls.
960 }
961
962 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
963 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800964 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700965 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
966 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
967
968 // Set admin1 as a DA to the secondary user.
969 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
970
971 dpm.setActiveAdmin(admin1, /* replace =*/ false);
972
973 // Set admin 1 as the DO to the system user.
974
975 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
976 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
977 dpm.setActiveAdmin(admin1, /* replace =*/ false);
978 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
979
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000980 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100981 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000982 eq(admin1.getPackageName()));
983
Makoto Onukic8a5a552015-11-19 14:29:12 -0800984 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700985
986 // Now call clear from the secondary user, which should throw.
987 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
988
989 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100990 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700991 eq(admin1.getPackageName()),
992 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100993 assertExpectException(SecurityException.class,
994 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
995 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -0700996
Makoto Onukic8a5a552015-11-19 14:29:12 -0800997 // DO shouldn't be removed.
998 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700999 }
1000
Makoto Onukib643fb02015-09-22 15:03:44 -07001001 public void testSetProfileOwner() throws Exception {
1002 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001003
Makoto Onuki90b89652016-01-28 14:44:18 -08001004 // PO admin can't be deactivated.
1005 dpm.removeActiveAdmin(admin1);
1006 assertTrue(dpm.isAdminActive(admin1));
1007
Makoto Onuki803d6752015-10-30 12:58:39 -07001008 // Try setting DO on the same user, which should fail.
1009 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001010 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1011 runAsCaller(mServiceContext, dpms, dpm -> {
1012 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001013 assertExpectException(IllegalStateException.class,
1014 /* messageRegex= */ "already has a profile owner",
1015 () -> dpm.setDeviceOwner(admin2, "owner-name",
1016 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001017 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001018 }
1019
Makoto Onuki90b89652016-01-28 14:44:18 -08001020 public void testClearProfileOwner() throws Exception {
1021 setAsProfileOwner(admin1);
1022
1023 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1024
1025 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1026 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1027
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001028 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001029 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001030 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001031 assertExpectException(IllegalStateException.class,
1032 /* messageRegex= */ "User must be running and unlocked",
1033 () -> dpm.clearProfileOwner(admin1));
1034
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001035 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001036 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001037 dpm.clearProfileOwner(admin1);
1038
1039 // Check
1040 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001041 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001042 }
1043
Makoto Onukib643fb02015-09-22 15:03:44 -07001044 public void testSetProfileOwner_failures() throws Exception {
1045 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1046 }
1047
Makoto Onukia52562c2015-10-01 16:12:31 -07001048 public void testGetDeviceOwnerAdminLocked() throws Exception {
1049 checkDeviceOwnerWithMultipleDeviceAdmins();
1050 }
1051
1052 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1053 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1054 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1055 // make sure it gets the right component from the right user.
1056
1057 final int ANOTHER_USER_ID = 100;
1058 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1059
Pavel Grafov75c0a892017-05-18 17:28:27 +01001060 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001061
1062 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001063 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001064 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1065 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1066
1067 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1068
Pavel Grafov75c0a892017-05-18 17:28:27 +01001069 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001070
Makoto Onukia52562c2015-10-01 16:12:31 -07001071 // Make sure the admin packge is installed to each user.
1072 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1073 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1074
1075 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1076 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1077
1078 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1079
1080
1081 // Set active admins to the users.
1082 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1083 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1084
1085 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1086 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1087
1088 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1089
1090 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001091 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001092 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1093
Makoto Onukic8a5a552015-11-19 14:29:12 -08001094 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001095
1096 // Then check getDeviceOwnerAdminLocked().
1097 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1098 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1099 }
1100
1101 /**
1102 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001103 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1104 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001105 *
1106 * We didn't use to persist the DO component class name, but now we do, and the above method
1107 * finds the right component from a package name upon migration.
1108 */
1109 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001110 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001111 checkDeviceOwnerWithMultipleDeviceAdmins();
1112
1113 // Overwrite the device owner setting and clears the clas name.
1114 dpms.mOwners.setDeviceOwner(
1115 new ComponentName(admin2.getPackageName(), ""),
1116 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1117 dpms.mOwners.writeDeviceOwner();
1118
1119 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001120 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001121
1122 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001123 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001124 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001125 initializeDpms();
1126
1127 // Now the DO component name is a full name.
1128 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1129 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001130 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001131 }
1132
Makoto Onukib643fb02015-09-22 15:03:44 -07001133 public void testSetGetApplicationRestriction() {
1134 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001135 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001136
1137 {
1138 Bundle rest = new Bundle();
1139 rest.putString("KEY_STRING", "Foo1");
1140 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1141 }
1142
1143 {
1144 Bundle rest = new Bundle();
1145 rest.putString("KEY_STRING", "Foo2");
1146 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1147 }
1148
1149 {
1150 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1151 assertNotNull(returned);
1152 assertEquals(returned.size(), 1);
1153 assertEquals(returned.get("KEY_STRING"), "Foo1");
1154 }
1155
1156 {
1157 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1158 assertNotNull(returned);
1159 assertEquals(returned.size(), 1);
1160 assertEquals(returned.get("KEY_STRING"), "Foo2");
1161 }
1162
1163 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1164 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1165 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001166
Edman Anjosf9946772016-11-28 16:35:15 +01001167 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001168 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1169 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001170 *
1171 * @param packageName the name of the package to be setup
1172 * @param appId the application ID to be given to the package
1173 * @return the UID of the package as known by the mock package manager
1174 */
1175 private int setupPackageInPackageManager(final String packageName, final int appId)
1176 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001177 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001178 ApplicationInfo.FLAG_HAS_CODE);
1179 }
1180
1181 /**
1182 * Setup a package in the package manager mock. Useful for faking installed applications.
1183 *
1184 * @param packageName the name of the package to be setup
1185 * @param userId the user id where the package will be "installed"
1186 * @param appId the application ID to be given to the package
1187 * @param flags flags to set in the ApplicationInfo for this package
1188 * @return the UID of the package as known by the mock package manager
1189 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001190 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1191 int flags) throws Exception {
1192 final int uid = UserHandle.getUid(userId, appId);
1193 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001194 final PackageInfo pi = new PackageInfo();
1195 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001196 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001197 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001198 eq(packageName),
1199 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001200 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001201 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001202 eq(packageName),
1203 anyInt(),
1204 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001205 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001206 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001207 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001208 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001209 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001210 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001211 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001212 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001213 return uid;
1214 }
1215
Robin Lee7f5c91c2017-02-08 21:27:02 +00001216 public void testCertificateDisclosure() throws Exception {
1217 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1218 final UserHandle user = UserHandle.of(userId);
1219
1220 mContext.applicationInfo = new ApplicationInfo();
1221 mContext.callerPermissions.add(permission.MANAGE_USERS);
1222 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001223 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001224 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1225
Robin Leeabaa0692017-02-20 20:54:22 +00001226 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1227 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001228
1229 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1230 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1231
1232 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001233 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001234 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001235 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001236 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001237 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001238 .cancelAsUser(anyString(), anyInt(), eq(user));
1239
1240 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001241 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001242 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001243 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1244 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001245 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001246 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001247 .notifyAsUser(anyString(), anyInt(), argThat(
1248 new BaseMatcher<Notification>() {
1249 @Override
1250 public boolean matches(Object item) {
1251 final Notification noti = (Notification) item;
1252 return TEST_STRING.equals(
1253 noti.extras.getString(Notification.EXTRA_TITLE));
1254 }
1255 @Override
1256 public void describeTo(Description description) {
1257 description.appendText(
1258 "Notification{title=\"" + TEST_STRING + "\"}");
1259 }
1260 }), eq(user));
1261 }
1262
Edman Anjosf9946772016-11-28 16:35:15 +01001263 /**
1264 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1265 * privileges can acually be exercised by a delegate are not covered here.
1266 */
1267 public void testDelegation() throws Exception {
1268 setAsProfileOwner(admin1);
1269
1270 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1271
1272 // Given two packages
1273 final String CERT_DELEGATE = "com.delegate.certs";
1274 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1275 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1276 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1277 20989);
1278
1279 // On delegation
1280 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1281 mContext.packageName = admin1.getPackageName();
1282 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1283 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1284
1285 // DPMS correctly stores and retrieves the delegates
1286 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1287 assertEquals(2, policy.mDelegationMap.size());
1288 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1289 DELEGATION_CERT_INSTALL);
1290 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1291 DELEGATION_CERT_INSTALL);
1292 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1293 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1294 DELEGATION_APP_RESTRICTIONS);
1295 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1296 DELEGATION_APP_RESTRICTIONS);
1297 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1298
1299 // On calling install certificate APIs from an unauthorized process
1300 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1301 mContext.packageName = RESTRICTIONS_DELEGATE;
1302
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001303 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1304 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001305
1306 // On calling install certificate APIs from an authorized process
1307 mContext.binder.callingUid = CERT_DELEGATE_UID;
1308 mContext.packageName = CERT_DELEGATE;
1309
1310 // DPMS executes without a SecurityException
1311 try {
1312 dpm.installCaCert(null, null);
1313 } catch (SecurityException unexpected) {
1314 fail("Threw SecurityException on authorized access");
1315 } catch (NullPointerException expected) {
1316 }
1317
1318 // On removing a delegate
1319 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1320 mContext.packageName = admin1.getPackageName();
1321 dpm.setCertInstallerPackage(admin1, null);
1322
1323 // DPMS does not allow access to ex-delegate
1324 mContext.binder.callingUid = CERT_DELEGATE_UID;
1325 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001326 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1327 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001328
1329 // But still allows access to other existing delegates
1330 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1331 mContext.packageName = RESTRICTIONS_DELEGATE;
1332 try {
1333 dpm.getApplicationRestrictions(null, "pkg");
1334 } catch (SecurityException expected) {
1335 fail("Threw SecurityException on authorized access");
1336 }
1337 }
1338
Esteban Talaverabf60f722015-12-10 16:26:44 +00001339 public void testApplicationRestrictionsManagingApp() throws Exception {
1340 setAsProfileOwner(admin1);
1341
Rubin Xued1928a2016-02-11 17:23:06 +00001342 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001343 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001344 final String nonDelegateExceptionMessageRegex =
1345 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001346 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001347 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1348 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001349
Esteban Talaverabf60f722015-12-10 16:26:44 +00001350 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1351 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001352 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1353 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001354 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001355 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001356 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001357 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1358 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001359
1360 // Check via the profile owner that no restrictions were set.
1361 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001362 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001363 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1364
Rubin Xued1928a2016-02-11 17:23:06 +00001365 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001366 assertExpectException(PackageManager.NameNotFoundException.class,
1367 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1368 () -> dpm.setApplicationRestrictionsManagingPackage(
1369 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001370
Esteban Talaverabf60f722015-12-10 16:26:44 +00001371 // Let appRestrictionsManagerPackage manage app restrictions
1372 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1373 assertEquals(appRestrictionsManagerPackage,
1374 dpm.getApplicationRestrictionsManagingPackage(admin1));
1375
1376 // Now that package should be able to set and retrieve app restrictions.
1377 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001378 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001379 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1380 dpm.setApplicationRestrictions(null, "pkg1", rest);
1381 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1382 assertEquals(1, returned.size(), 1);
1383 assertEquals("Foo1", returned.get("KEY_STRING"));
1384
1385 // The same app running on a separate user shouldn't be able to manage app restrictions.
1386 mContext.binder.callingUid = UserHandle.getUid(
1387 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1388 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001389 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1390 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001391
1392 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1393 // too.
1394 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001395 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001396 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1397 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1398 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1399
1400 // Removing the ability for the package to manage app restrictions.
1401 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1402 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1403 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001404 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001405 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001406 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1407 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001408 }
1409
Makoto Onukia4f11972015-10-01 13:19:58 -07001410 public void testSetUserRestriction_asDo() throws Exception {
1411 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001412 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001413 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1414 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1415
1416 // First, set DO.
1417
1418 // Call from a process on the system user.
1419 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1420
1421 // Make sure admin1 is installed on system user.
1422 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001423
1424 // Call.
1425 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001426 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001427 UserHandle.USER_SYSTEM));
1428
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001429 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001430 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001431 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001432 DpmTestUtils.assertRestrictions(
1433 DpmTestUtils.newRestrictions(defaultRestrictions),
1434 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1435 );
1436 DpmTestUtils.assertRestrictions(
1437 DpmTestUtils.newRestrictions(defaultRestrictions),
1438 dpm.getUserRestrictions(admin1)
1439 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001440 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001441 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001442 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001443 eq(true) /* isDeviceOwner */,
1444 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001445 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001446 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001447
1448 for (String restriction : defaultRestrictions) {
1449 dpm.clearUserRestriction(admin1, restriction);
1450 }
1451
Esteban Talavera548a04b2016-12-20 15:22:30 +00001452 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001453 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001454
1455 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001456 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001457 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001458 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1459 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001460 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001461
Makoto Onukia4f11972015-10-01 13:19:58 -07001462 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001463 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001464 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001465 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1466 UserManager.DISALLOW_ADD_USER),
1467 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001468 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001469
Makoto Onuki068c54a2015-10-13 14:34:03 -07001470 DpmTestUtils.assertRestrictions(
1471 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001472 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001473 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1474 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001475 DpmTestUtils.assertRestrictions(
1476 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001477 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001478 dpm.getUserRestrictions(admin1)
1479 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001480
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001481 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001482 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001483 eq(UserHandle.USER_SYSTEM),
1484 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001485 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001486 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001487
Makoto Onuki068c54a2015-10-13 14:34:03 -07001488 DpmTestUtils.assertRestrictions(
1489 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1490 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1491 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001492 DpmTestUtils.assertRestrictions(
1493 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1494 dpm.getUserRestrictions(admin1)
1495 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001496
1497 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001498 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001499 eq(UserHandle.USER_SYSTEM),
1500 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001501 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001502 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001503
Esteban Talavera548a04b2016-12-20 15:22:30 +00001504 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001505
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001506 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1507 // DO sets them, the scope is global.
1508 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001509 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001510 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001511 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001512 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001513 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001514 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1515 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001516 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001517
1518 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1519 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001520 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001521
1522 // More tests.
1523 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001524 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001525 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001526 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1527 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001528 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001529
1530 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001531 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001532 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001533 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001534 UserManager.DISALLOW_ADD_USER),
1535 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001536 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001537
1538 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001539 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001540 eq(UserHandle.USER_SYSTEM),
1541 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001542 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001543 UserManager.DISALLOW_ADD_USER),
1544 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001545 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001546
1547 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1548 // locally.
1549 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001550 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001551
1552 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1553 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1554 dpm.setCameraDisabled(admin2, true);
1555
Pavel Grafov75c0a892017-05-18 17:28:27 +01001556 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001557 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001558 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001559 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001560 UserManager.DISALLOW_ADD_USER),
1561 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001562 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001563 // TODO Make sure restrictions are written to the file.
1564 }
1565
1566 public void testSetUserRestriction_asPo() {
1567 setAsProfileOwner(admin1);
1568
Makoto Onuki068c54a2015-10-13 14:34:03 -07001569 DpmTestUtils.assertRestrictions(
1570 DpmTestUtils.newRestrictions(),
1571 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1572 .ensureUserRestrictions()
1573 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001574
1575 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001576 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001577 eq(DpmMockContext.CALLER_USER_HANDLE),
1578 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001579 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001580 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001581
Makoto Onukia4f11972015-10-01 13:19:58 -07001582 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001583 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001584 eq(DpmMockContext.CALLER_USER_HANDLE),
1585 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1586 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001587 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001588 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001589
Makoto Onuki068c54a2015-10-13 14:34:03 -07001590 DpmTestUtils.assertRestrictions(
1591 DpmTestUtils.newRestrictions(
1592 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1593 UserManager.DISALLOW_OUTGOING_CALLS
1594 ),
1595 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1596 .ensureUserRestrictions()
1597 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001598 DpmTestUtils.assertRestrictions(
1599 DpmTestUtils.newRestrictions(
1600 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1601 UserManager.DISALLOW_OUTGOING_CALLS
1602 ),
1603 dpm.getUserRestrictions(admin1)
1604 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001605
1606 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001607 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001608 eq(DpmMockContext.CALLER_USER_HANDLE),
1609 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001610 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001611 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001612
1613 DpmTestUtils.assertRestrictions(
1614 DpmTestUtils.newRestrictions(
1615 UserManager.DISALLOW_OUTGOING_CALLS
1616 ),
1617 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1618 .ensureUserRestrictions()
1619 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001620 DpmTestUtils.assertRestrictions(
1621 DpmTestUtils.newRestrictions(
1622 UserManager.DISALLOW_OUTGOING_CALLS
1623 ),
1624 dpm.getUserRestrictions(admin1)
1625 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001626
1627 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001628 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001629 eq(DpmMockContext.CALLER_USER_HANDLE),
1630 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001631 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001632 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001633
Makoto Onuki068c54a2015-10-13 14:34:03 -07001634 DpmTestUtils.assertRestrictions(
1635 DpmTestUtils.newRestrictions(),
1636 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1637 .ensureUserRestrictions()
1638 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001639 DpmTestUtils.assertRestrictions(
1640 DpmTestUtils.newRestrictions(),
1641 dpm.getUserRestrictions(admin1)
1642 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001643
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001644 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1645 // though when DO sets them they'll be applied globally.
1646 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001647 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001648 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001649 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650 eq(DpmMockContext.CALLER_USER_HANDLE),
1651 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1652 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001653 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001654 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001655
1656 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001657 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001658 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001659 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001660 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001661 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001662 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001663
Makoto Onukia4f11972015-10-01 13:19:58 -07001664 // TODO Make sure restrictions are written to the file.
1665 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001666
Esteban Talavera548a04b2016-12-20 15:22:30 +00001667
1668 public void testDefaultEnabledUserRestrictions() throws Exception {
1669 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1670 mContext.callerPermissions.add(permission.MANAGE_USERS);
1671 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1672 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1673
1674 // First, set DO.
1675
1676 // Call from a process on the system user.
1677 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1678
1679 // Make sure admin1 is installed on system user.
1680 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1681
1682 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1683 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1684 UserHandle.USER_SYSTEM));
1685
1686 // Check that the user restrictions that are enabled by default are set. Then unset them.
1687 String[] defaultRestrictions = UserRestrictionsUtils
1688 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1689 assertTrue(defaultRestrictions.length > 0);
1690 DpmTestUtils.assertRestrictions(
1691 DpmTestUtils.newRestrictions(defaultRestrictions),
1692 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1693 );
1694 DpmTestUtils.assertRestrictions(
1695 DpmTestUtils.newRestrictions(defaultRestrictions),
1696 dpm.getUserRestrictions(admin1)
1697 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001698 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001699 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001700 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001701 eq(true) /* isDeviceOwner */,
1702 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001703 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001704 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001705
1706 for (String restriction : defaultRestrictions) {
1707 dpm.clearUserRestriction(admin1, restriction);
1708 }
1709
1710 assertNoDeviceOwnerRestrictions();
1711
1712 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001713 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001714 initializeDpms();
1715 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1716 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1717
1718 assertNoDeviceOwnerRestrictions();
1719
1720 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1721 // is set as it wasn't enabled during setDeviceOwner.
1722 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1723 assertFalse(UserRestrictionsUtils
1724 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1725 UserRestrictionsUtils
1726 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1727 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001728 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001729 initializeDpms();
1730 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1731 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1732
1733 DpmTestUtils.assertRestrictions(
1734 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1735 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1736 );
1737 DpmTestUtils.assertRestrictions(
1738 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1739 dpm.getUserRestrictions(admin1)
1740 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001741 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001742 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001743 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001744 eq(true) /* isDeviceOwner */,
1745 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001746 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001747 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001748
1749 // Remove the restriction.
1750 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1751
1752 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1753 initializeDpms();
1754 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1755 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1756 assertNoDeviceOwnerRestrictions();
1757 } finally {
1758 UserRestrictionsUtils
1759 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1760 }
1761 }
1762
1763 private void assertNoDeviceOwnerRestrictions() {
1764 DpmTestUtils.assertRestrictions(
1765 DpmTestUtils.newRestrictions(),
1766 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1767 );
1768 DpmTestUtils.assertRestrictions(
1769 DpmTestUtils.newRestrictions(),
1770 dpm.getUserRestrictions(admin1)
1771 );
1772 }
1773
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001774 public void testGetMacAddress() throws Exception {
1775 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1776 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1777 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1778
1779 // In this test, change the caller user to "system".
1780 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1781
1782 // Make sure admin1 is installed on system user.
1783 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1784
1785 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001786 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1787 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001788
1789 // DO needs to be an DA.
1790 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1791 assertTrue(dpm.isAdminActive(admin1));
1792
1793 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001794 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1795 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001796
1797 // Test 3. Caller has PO, but not DO.
1798 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001799 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1800 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001801
1802 // Remove PO.
1803 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001804 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001805 // Test 4, Caller is DO now.
1806 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1807
1808 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001809 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001810
1811 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001812 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001813 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001814
1815 // 4-3. With a real MAC address.
1816 final WifiInfo wi = new WifiInfo();
1817 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001818 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001819 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001820 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001821
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001822 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001823 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1824 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1825
1826 // In this test, change the caller user to "system".
1827 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1828
1829 // Make sure admin1 is installed on system user.
1830 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1831
1832 // Set admin1 as DA.
1833 dpm.setActiveAdmin(admin1, false);
1834 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001835 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1836 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001837
1838 // Set admin1 as PO.
1839 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001840 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1841 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001842
1843 // Remove PO and add DO.
1844 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001845 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001846 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1847
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001848 // admin1 is DO.
1849 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001850 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001851 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001852 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1853 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001854
1855 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001856 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001857 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001858 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1859 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001860
1861 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001862 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001863 dpm.reboot(admin1);
1864 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001865
1866 public void testSetGetSupportText() {
1867 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1868 dpm.setActiveAdmin(admin1, true);
1869 dpm.setActiveAdmin(admin2, true);
1870 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1871
1872 // Null default support messages.
1873 {
1874 assertNull(dpm.getLongSupportMessage(admin1));
1875 assertNull(dpm.getShortSupportMessage(admin1));
1876 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1877 assertNull(dpm.getShortSupportMessageForUser(admin1,
1878 DpmMockContext.CALLER_USER_HANDLE));
1879 assertNull(dpm.getLongSupportMessageForUser(admin1,
1880 DpmMockContext.CALLER_USER_HANDLE));
1881 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1882 }
1883
1884 // Only system can call the per user versions.
1885 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001886 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1887 () -> dpm.getShortSupportMessageForUser(admin1,
1888 DpmMockContext.CALLER_USER_HANDLE));
1889 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1890 () -> dpm.getLongSupportMessageForUser(admin1,
1891 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00001892 }
1893
1894 // Can't set message for admin in another uid.
1895 {
1896 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001897 assertExpectException(SecurityException.class,
1898 /* messageRegex= */ "is not owned by uid",
1899 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00001900 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1901 }
1902
1903 // Set/Get short returns what it sets and other admins text isn't changed.
1904 {
1905 final String supportText = "Some text to test with.";
1906 dpm.setShortSupportMessage(admin1, supportText);
1907 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1908 assertNull(dpm.getLongSupportMessage(admin1));
1909 assertNull(dpm.getShortSupportMessage(admin2));
1910
1911 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1912 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1913 DpmMockContext.CALLER_USER_HANDLE));
1914 assertNull(dpm.getShortSupportMessageForUser(admin2,
1915 DpmMockContext.CALLER_USER_HANDLE));
1916 assertNull(dpm.getLongSupportMessageForUser(admin1,
1917 DpmMockContext.CALLER_USER_HANDLE));
1918 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1919
1920 dpm.setShortSupportMessage(admin1, null);
1921 assertNull(dpm.getShortSupportMessage(admin1));
1922 }
1923
1924 // Set/Get long returns what it sets and other admins text isn't changed.
1925 {
1926 final String supportText = "Some text to test with.\nWith more text.";
1927 dpm.setLongSupportMessage(admin1, supportText);
1928 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1929 assertNull(dpm.getShortSupportMessage(admin1));
1930 assertNull(dpm.getLongSupportMessage(admin2));
1931
1932 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1933 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1934 DpmMockContext.CALLER_USER_HANDLE));
1935 assertNull(dpm.getLongSupportMessageForUser(admin2,
1936 DpmMockContext.CALLER_USER_HANDLE));
1937 assertNull(dpm.getShortSupportMessageForUser(admin1,
1938 DpmMockContext.CALLER_USER_HANDLE));
1939 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1940
1941 dpm.setLongSupportMessage(admin1, null);
1942 assertNull(dpm.getLongSupportMessage(admin1));
1943 }
1944 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001945
phweiss73145f42017-01-17 19:06:38 +01001946 public void testCreateAdminSupportIntent() throws Exception {
1947 // Setup device owner.
1948 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1949 setupDeviceOwner();
1950
1951 // Nonexisting permission returns null
1952 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
1953 assertNull(intent);
1954
1955 // Existing permission that is not set returns null
1956 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1957 assertNull(intent);
1958
1959 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01001960 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01001961 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1962 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1963 .thenReturn(true);
1964 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1965 assertNull(intent);
1966
1967 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01001968 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01001969 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1970 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1971 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
1972 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1973 assertNotNull(intent);
1974 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
1975 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
1976 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001977 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01001978 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
1979 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1980
1981 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
1982 // user restrictions
1983
1984 // Camera is not disabled
1985 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1986 assertNull(intent);
1987
1988 // Camera is disabled
1989 dpm.setCameraDisabled(admin1, true);
1990 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1991 assertNotNull(intent);
1992 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
1993 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1994
1995 // Screen capture is not disabled
1996 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1997 assertNull(intent);
1998
1999 // Screen capture is disabled
2000 dpm.setScreenCaptureDisabled(admin1, true);
2001 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2002 assertNotNull(intent);
2003 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2004 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2005
2006 // Same checks for different user
2007 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2008 // Camera should be disabled by device owner
2009 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2010 assertNotNull(intent);
2011 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2012 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2013 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2014 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2015 // ScreenCapture should not be disabled by device owner
2016 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2017 assertNull(intent);
2018 }
2019
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002020 /**
2021 * Test for:
2022 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002023 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002024 * {@link DevicePolicyManager#isAffiliatedUser}
2025 */
2026 public void testUserAffiliation() throws Exception {
2027 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2028 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2029 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2030
2031 // Check that the system user is unaffiliated.
2032 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2033 assertFalse(dpm.isAffiliatedUser());
2034
2035 // Set a device owner on the system user. Check that the system user becomes affiliated.
2036 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2037 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2038 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2039 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002040 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002041
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002042 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002043 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2044 setAsProfileOwner(admin2);
2045 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002046 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002047
2048 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2049 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002050 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002051 userAffiliationIds.add("red");
2052 userAffiliationIds.add("green");
2053 userAffiliationIds.add("blue");
2054 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002055 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002056 assertFalse(dpm.isAffiliatedUser());
2057
2058 // Have the device owner specify a set of affiliation ids that do not intersect with those
2059 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002060 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002061 deviceAffiliationIds.add("cyan");
2062 deviceAffiliationIds.add("yellow");
2063 deviceAffiliationIds.add("magenta");
2064 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2065 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002066 MoreAsserts.assertContentsInAnyOrder(
2067 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002068 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2069 assertFalse(dpm.isAffiliatedUser());
2070
2071 // Have the profile owner specify a set of affiliation ids that intersect with those
2072 // specified by the device owner. Check that the test user becomes affiliated.
2073 userAffiliationIds.add("yellow");
2074 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002075 MoreAsserts.assertContentsInAnyOrder(
2076 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002077 assertTrue(dpm.isAffiliatedUser());
2078
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002079 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002080 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002081 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002082 assertFalse(dpm.isAffiliatedUser());
2083
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002084 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2085 dpm.setAffiliationIds(admin2, userAffiliationIds);
2086 assertTrue(dpm.isAffiliatedUser());
2087 dpm.clearProfileOwner(admin2);
2088 assertFalse(dpm.isAffiliatedUser());
2089
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002090 // Check that the system user remains affiliated.
2091 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2092 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002093
2094 // Clear the device owner - the user becomes unaffiliated.
2095 clearDeviceOwner();
2096 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002097 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002098
2099 public void testGetUserProvisioningState_defaultResult() {
2100 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2101 }
2102
2103 public void testSetUserProvisioningState_permission() throws Exception {
2104 setupProfileOwner();
2105 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2106
2107 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2108 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2109 }
2110
2111 public void testSetUserProvisioningState_unprivileged() throws Exception {
2112 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002113 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2114 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2115 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002116 }
2117
2118 public void testSetUserProvisioningState_noManagement() {
2119 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002120 assertExpectException(IllegalStateException.class,
2121 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2122 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2123 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002124 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2125 }
2126
2127 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2128 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2129 setupDeviceOwner();
2130 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2131
2132 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2133 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2134 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2135 }
2136
2137 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2138 throws Exception {
2139 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2140 setupDeviceOwner();
2141 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2142
2143 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2144 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2145 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2146 }
2147
2148 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2149 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2150 setupDeviceOwner();
2151 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2152
2153 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2154 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2155 }
2156
2157 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2158 throws Exception {
2159 setupProfileOwner();
2160 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2161
2162 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2163 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2164 DevicePolicyManager.STATE_USER_UNMANAGED);
2165 }
2166
2167 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2168 throws Exception {
2169 setupProfileOwner();
2170 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2171
2172 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2173 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2174 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2175 }
2176
2177 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2178 setupProfileOwner();
2179 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2180
2181 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2182 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2183 }
2184
2185 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2186 setupProfileOwner();
2187 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2188
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002189 assertExpectException(IllegalStateException.class,
2190 /* messageRegex= */ "Cannot move to user provisioning state",
2191 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2192 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2193 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002194 }
2195
2196 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2197 throws Exception {
2198 setupProfileOwner();
2199 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2200
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002201 assertExpectException(IllegalStateException.class,
2202 /* messageRegex= */ "Cannot move to user provisioning state",
2203 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2204 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2205 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002206 }
2207
2208 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2209 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2210 for (int state : states) {
2211 dpm.setUserProvisioningState(state, userId);
2212 assertEquals(state, dpm.getUserProvisioningState());
2213 }
2214 }
2215
2216 private void setupProfileOwner() throws Exception {
2217 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2218
2219 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2220 dpm.setActiveAdmin(admin1, false);
2221 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2222
2223 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2224 }
2225
2226 private void setupDeviceOwner() throws Exception {
2227 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2228
2229 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2230 dpm.setActiveAdmin(admin1, false);
2231 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2232
2233 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2234 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002235
2236 public void testSetMaximumTimeToLock() {
2237 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2238
2239 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2240 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2241
Pavel Grafov75c0a892017-05-18 17:28:27 +01002242 reset(getServices().powerManagerInternal);
2243 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002244
2245 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002246 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2247 verifyStayOnWhilePluggedCleared(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);
Pavel Grafov28939982017-10-03 15:11:52 +01002252 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2253 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002254 reset(getServices().powerManagerInternal);
2255 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002256
2257 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002258 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2259 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002260 reset(getServices().powerManagerInternal);
2261 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002262
2263 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002264 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2265 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002266 reset(getServices().powerManagerInternal);
2267 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002268
2269 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002270 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2271 verifyStayOnWhilePluggedCleared(true);
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(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002276 reset(getServices().powerManagerInternal);
2277 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002278
Pavel Grafov28939982017-10-03 15:11:52 +01002279 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2280 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2281 verifyStayOnWhilePluggedCleared(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);
Pavel Grafov28939982017-10-03 15:11:52 +01002286 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2287 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002288 reset(getServices().powerManagerInternal);
2289 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002290
Pavel Grafov28939982017-10-03 15:11:52 +01002291 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002292 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002293 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2294 verifyStayOnWhilePluggedCleared(false);
2295 }
2296
2297 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2298 // uses separate challenge.
2299 public void testSetMaximumTimeToLockProfile() throws Exception {
2300 final int PROFILE_USER = 15;
2301 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2302 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2303 mContext.binder.callingUid = PROFILE_ADMIN;
2304 final DevicePolicyManagerInternal dpmi =
2305 LocalServices.getService(DevicePolicyManagerInternal.class);
2306
2307 dpm.setMaximumTimeToLock(admin1, 0);
2308
2309 reset(getServices().powerManagerInternal);
2310 reset(getServices().settings);
2311
2312 // First add timeout for the profile.
2313 dpm.setMaximumTimeToLock(admin1, 10);
2314 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2315
2316 reset(getServices().powerManagerInternal);
2317 reset(getServices().settings);
2318
2319 // Add separate challenge
2320 when(getServices().lockPatternUtils
2321 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2322 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2323
2324 verifyScreenTimeoutCall(10L, PROFILE_USER);
2325 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2326
2327 reset(getServices().powerManagerInternal);
2328 reset(getServices().settings);
2329
2330 // Remove the timeout.
2331 dpm.setMaximumTimeToLock(admin1, 0);
2332 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2333 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2334
2335 reset(getServices().powerManagerInternal);
2336 reset(getServices().settings);
2337
2338 // Add it back.
2339 dpm.setMaximumTimeToLock(admin1, 10);
2340 verifyScreenTimeoutCall(10L, PROFILE_USER);
2341 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2342
2343 reset(getServices().powerManagerInternal);
2344 reset(getServices().settings);
2345
2346 // Remove separate challenge.
2347 reset(getServices().lockPatternUtils);
2348 when(getServices().lockPatternUtils
2349 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2350 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2351
2352 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2353 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2354
2355 reset(getServices().powerManagerInternal);
2356 reset(getServices().settings);
2357
2358 // Remove the timeout.
2359 dpm.setMaximumTimeToLock(admin1, 0);
2360 verifyScreenTimeoutCall(null, PROFILE_USER);
2361 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002362 }
2363
Michal Karpinski943aabd2016-10-06 11:09:25 +01002364 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2365 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2366 setupDeviceOwner();
2367 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2368
Michal Karpinskid084ca52017-01-18 15:54:18 +00002369 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2370 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2371 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2372 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2373 - ONE_MINUTE;
2374
2375 // verify that the minimum timeout cannot be modified on user builds (system property is
2376 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002377 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002378
2379 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2380 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2381 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2382
Pavel Grafov75c0a892017-05-18 17:28:27 +01002383 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002384
2385 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002386 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002387
Michal Karpinskid084ca52017-01-18 15:54:18 +00002388 // reset to default (0 means the admin is not participating, so default should be returned)
2389 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002390
2391 // aggregation should be the default if unset by any admin
2392 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2393 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2394
2395 // admin not participating by default
2396 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2397
2398 //clamping from the top
2399 dpm.setRequiredStrongAuthTimeout(admin1,
2400 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2401 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2402 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2403 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2404 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2405
Michal Karpinskid084ca52017-01-18 15:54:18 +00002406 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002407 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2408 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2409 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2410 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2411
2412 // clamping from the bottom
2413 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2414 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2415 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2416
Michal Karpinskid084ca52017-01-18 15:54:18 +00002417 // values within range
2418 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2419 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2420 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2421
2422 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2423 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2424 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002425
2426 // reset to default
2427 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2428 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2429 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2430 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2431
2432 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002433 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2434 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002435 }
2436
Pavel Grafov28939982017-10-03 15:11:52 +01002437 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002438 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002439 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002440 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002441 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002442 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002443 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002444 }
Pavel Grafov28939982017-10-03 15:11:52 +01002445 }
2446
2447 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002448 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2449 // UnfinishedVerificationException.
2450 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002451
Esteban Talavera01576862016-12-15 11:16:44 +00002452 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002453 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002454 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002455 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002456 .thenReturn(false);
2457 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002458 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2459 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002460 .thenReturn(true);
2461 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2462
2463 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002464 }
Victor Chang3e794af2016-03-04 13:48:17 +00002465
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002466 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2467 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002468 mContext.packageName = admin1.getPackageName();
2469 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002470 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2471 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2472 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2473 false);
2474 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2475 }
2476
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002477 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2478 setup_DeviceAdminFeatureOff();
2479 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2480 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2481 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2482 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2483 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2484 assertCheckProvisioningPreCondition(
2485 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2486 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2487 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2488 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2489 }
2490
Esteban Talavera01576862016-12-15 11:16:44 +00002491 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002492 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002493 .thenReturn(false);
2494 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002495 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2496 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002497 .thenReturn(true);
2498 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2499
2500 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002501 }
Victor Chang3e794af2016-03-04 13:48:17 +00002502
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002503 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2504 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002505 mContext.packageName = admin1.getPackageName();
2506 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002507 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2508 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2509 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2510 false);
2511 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2512
2513 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002514 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002515 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2516 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2517 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2518 true);
2519 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2520 }
2521
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002522 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2523 setup_ManagedProfileFeatureOff();
2524 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2525 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2526 DevicePolicyManager.CODE_OK);
2527 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2528 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2529 assertCheckProvisioningPreCondition(
2530 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2531 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2532 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2533 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2534
2535 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002536 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002537 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2538 DevicePolicyManager.CODE_OK);
2539 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2540 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2541 assertCheckProvisioningPreCondition(
2542 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2543 DevicePolicyManager.CODE_OK);
2544 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2545 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2546 }
2547
Esteban Talavera01576862016-12-15 11:16:44 +00002548 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002549 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002550 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002551 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2552 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002553 .thenReturn(true);
2554 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2555
2556 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002557 }
Victor Chang3e794af2016-03-04 13:48:17 +00002558
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002559 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2560 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002561 mContext.packageName = admin1.getPackageName();
2562 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002563 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2564 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2565 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2566 false /* because of non-split user */);
2567 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2568 false /* because of non-split user */);
2569 }
2570
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002571 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002572 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002573 setup_nonSplitUser_firstBoot_primaryUser();
2574 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2575 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2576 DevicePolicyManager.CODE_OK);
2577 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2578 DevicePolicyManager.CODE_OK);
2579 assertCheckProvisioningPreCondition(
2580 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2581 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2582 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2583 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2584 }
2585
Esteban Talavera01576862016-12-15 11:16:44 +00002586 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002587 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002588 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002589 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2590 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002591 .thenReturn(true);
2592 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2593
2594 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002595 }
Victor Chang3e794af2016-03-04 13:48:17 +00002596
Nicolas Prevot45d29072017-01-18 16:11:19 +00002597 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2598 setDeviceOwner();
2599 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2600 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2601 }
2602
2603 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2604 setup_nonSplitUser_withDo_primaryUser();
2605 final int MANAGED_PROFILE_USER_ID = 18;
2606 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2607 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002608 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002609 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002610 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002611 true)).thenReturn(true);
2612 }
2613
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002614 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2615 throws Exception {
2616 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002617 mContext.packageName = admin1.getPackageName();
2618 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002619 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2620 false/* because of completed device setup */);
2621 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2622 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2623 false/* because of non-split user */);
2624 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2625 false/* because of non-split user */);
2626 }
2627
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002628 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2629 throws Exception {
2630 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2631 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2632 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2633 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2634 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2635 DevicePolicyManager.CODE_OK);
2636 assertCheckProvisioningPreCondition(
2637 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2638 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2639 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2640 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2641 }
2642
Nicolas Prevot45d29072017-01-18 16:11:19 +00002643 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2644 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002645 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002646 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2647
2648 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2649 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002650 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002651
2652 // COMP mode is allowed.
2653 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2654 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002655 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002656
Nicolas Prevot45d29072017-01-18 16:11:19 +00002657 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002658 assertCheckProvisioningPreCondition(
2659 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002660 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002661 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002662 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2663 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2664 }
Esteban Talavera01576862016-12-15 11:16:44 +00002665
Nicolas Prevot45d29072017-01-18 16:11:19 +00002666 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2667 setup_nonSplitUser_withDo_primaryUser();
2668 mContext.packageName = admin1.getPackageName();
2669 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2670 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2671 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002672 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002673 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2674 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2675 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002676 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002677 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2678 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2679 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2680 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2681 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002682 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002683 assertCheckProvisioningPreCondition(
2684 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002685 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002686 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002687 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2688 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2689 }
Esteban Talavera01576862016-12-15 11:16:44 +00002690
Nicolas Prevot45d29072017-01-18 16:11:19 +00002691 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2692 throws Exception {
2693 setup_nonSplitUser_withDo_primaryUser();
2694 mContext.packageName = admin1.getPackageName();
2695 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002696 // The DO should not be allowed to initiate provisioning if the restriction is set by
2697 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002698 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002699 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2700 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2701 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002702 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002703 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2704 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2705 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2706 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2707 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002708 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2709
2710 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002711 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002712 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002713 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002714 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2715 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2716 }
2717
2718 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2719 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2720 mContext.packageName = admin1.getPackageName();
2721 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2722
2723 // We can delete the managed profile to create a new one, so provisioning is allowed.
2724 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2725 DevicePolicyManager.CODE_OK);
2726 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2727 assertCheckProvisioningPreCondition(
2728 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2729 DpmMockContext.ANOTHER_PACKAGE_NAME,
2730 DevicePolicyManager.CODE_OK);
2731 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2732 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2733 }
2734
2735 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2736 throws Exception {
2737 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2738 mContext.packageName = admin1.getPackageName();
2739 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002740 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002741 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2742 eq(UserHandle.SYSTEM)))
2743 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002744 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002745 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2746 eq(UserHandle.SYSTEM)))
2747 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002748
2749 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002750 assertCheckProvisioningPreCondition(
2751 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2752 DpmMockContext.ANOTHER_PACKAGE_NAME,
2753 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2754 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2755 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002756
2757 // But the device owner can still do it because it has set the restriction itself.
2758 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2759 DevicePolicyManager.CODE_OK);
2760 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002761 }
2762
2763 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002764 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002765 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002766 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2767 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002768 .thenReturn(false);
2769 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2770
2771 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002772 }
Victor Chang3e794af2016-03-04 13:48:17 +00002773
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002774 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2775 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002776 mContext.packageName = admin1.getPackageName();
2777 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002778 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2779 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2780 false /* because canAddMoreManagedProfiles returns false */);
2781 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2782 true);
2783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2784 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002785 }
2786
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002787 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2788 throws Exception {
2789 setup_splitUser_firstBoot_systemUser();
2790 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2791 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2792 DevicePolicyManager.CODE_OK);
2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002794 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002795 assertCheckProvisioningPreCondition(
2796 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2797 DevicePolicyManager.CODE_OK);
2798 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2799 DevicePolicyManager.CODE_SYSTEM_USER);
2800 }
2801
Esteban Talavera01576862016-12-15 11:16:44 +00002802 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002803 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002804 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002805 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2806 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002807 .thenReturn(false);
2808 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2809
2810 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002811 }
Victor Chang3e794af2016-03-04 13:48:17 +00002812
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002813 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2814 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002815 mContext.packageName = admin1.getPackageName();
2816 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002817 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2818 true/* it's undefined behavior. Can be changed into false in the future */);
2819 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2820 false /* because canAddMoreManagedProfiles returns false */);
2821 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2822 true/* it's undefined behavior. Can be changed into false in the future */);
2823 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2824 false/* because calling uid is system user */);
2825 }
2826
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002827 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2828 throws Exception {
2829 setup_splitUser_afterDeviceSetup_systemUser();
2830 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2831 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2832 DevicePolicyManager.CODE_OK);
2833 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002834 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002835 assertCheckProvisioningPreCondition(
2836 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2837 DevicePolicyManager.CODE_OK);
2838 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2839 DevicePolicyManager.CODE_SYSTEM_USER);
2840 }
2841
Esteban Talavera01576862016-12-15 11:16:44 +00002842 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002843 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002844 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002845 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2846 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002847 true)).thenReturn(true);
2848 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2849
2850 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002851 }
Victor Chang3e794af2016-03-04 13:48:17 +00002852
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002853 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2854 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002855 mContext.packageName = admin1.getPackageName();
2856 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002857 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2858 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2859 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2860 true);
2861 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002862 }
2863
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002864 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002865 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002866 setup_splitUser_firstBoot_primaryUser();
2867 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2868 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2869 DevicePolicyManager.CODE_OK);
2870 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2871 DevicePolicyManager.CODE_OK);
2872 assertCheckProvisioningPreCondition(
2873 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2874 DevicePolicyManager.CODE_OK);
2875 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2876 DevicePolicyManager.CODE_OK);
2877 }
2878
Esteban Talavera01576862016-12-15 11:16:44 +00002879 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002880 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002881 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002882 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2883 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002884 true)).thenReturn(true);
2885 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2886
2887 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002888 }
Victor Chang3e794af2016-03-04 13:48:17 +00002889
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002890 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2891 throws Exception {
2892 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002893 mContext.packageName = admin1.getPackageName();
2894 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002895 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2896 true/* it's undefined behavior. Can be changed into false in the future */);
2897 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2898 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2899 true/* it's undefined behavior. Can be changed into false in the future */);
2900 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2901 false/* because user setup completed */);
2902 }
2903
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002904 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002905 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002906 setup_splitUser_afterDeviceSetup_primaryUser();
2907 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2908 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2909 DevicePolicyManager.CODE_OK);
2910 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2911 DevicePolicyManager.CODE_OK);
2912 assertCheckProvisioningPreCondition(
2913 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2914 DevicePolicyManager.CODE_OK);
2915 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2916 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2917 }
2918
Esteban Talavera01576862016-12-15 11:16:44 +00002919 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002920 setDeviceOwner();
2921
Pavel Grafov75c0a892017-05-18 17:28:27 +01002922 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002923 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002924 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2925 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002926 .thenReturn(false);
2927 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2928
2929 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002930 }
Victor Chang3e794af2016-03-04 13:48:17 +00002931
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002932 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2933 throws Exception {
2934 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002935 mContext.packageName = admin1.getPackageName();
2936 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002937 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2938 false /* can't provision managed profile on system user */);
2939 }
2940
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002941 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002942 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002943 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2944 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2945 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2946 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2947 }
2948
2949 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002950 setDeviceOwner();
2951
Pavel Grafov75c0a892017-05-18 17:28:27 +01002952 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002953 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002954 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2955 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002956 true)).thenReturn(true);
2957 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2958
2959 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002960 }
Victor Chang3e794af2016-03-04 13:48:17 +00002961
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002962 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2963 throws Exception {
2964 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002965 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2966 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002967 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2968 }
2969
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002970 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002971 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002972 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2973 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002974
2975 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002976 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2977 DevicePolicyManager.CODE_OK);
2978 }
2979
2980 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002981 setDeviceOwner();
2982
Pavel Grafov75c0a892017-05-18 17:28:27 +01002983 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002984 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002985 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2986 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002987 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2988 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002989 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002990 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002991 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002992 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00002993 true)).thenReturn(true);
2994 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2995
2996 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002997 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002998
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002999 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3000 throws Exception {
3001 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003002 mContext.packageName = admin1.getPackageName();
3003 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003004 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3005 }
3006
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003007 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3008 throws Exception {
3009 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3010 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3011 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3012 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3013 }
3014
3015 public void testCheckProvisioningPreCondition_permission() {
3016 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003017 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3018 () -> dpm.checkProvisioningPreCondition(
3019 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003020 }
3021
Victor Chang3577ed22016-08-25 18:49:26 +01003022 public void testForceUpdateUserSetupComplete_permission() {
3023 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003024 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3025 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003026 }
3027
3028 public void testForceUpdateUserSetupComplete_systemUser() {
3029 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3030 // GIVEN calling from user 20
3031 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003032 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3033 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003034 }
3035
3036 public void testForceUpdateUserSetupComplete_userbuild() {
3037 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3038 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3039
3040 final int userId = UserHandle.USER_SYSTEM;
3041 // GIVEN userComplete is false in SettingsProvider
3042 setUserSetupCompleteForUser(false, userId);
3043
3044 // GIVEN userComplete is true in DPM
3045 DevicePolicyManagerService.DevicePolicyData userData =
3046 new DevicePolicyManagerService.DevicePolicyData(userId);
3047 userData.mUserSetupComplete = true;
3048 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3049
3050 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003051 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003052
3053 assertTrue(dpms.hasUserSetupCompleted());
3054
3055 dpm.forceUpdateUserSetupComplete();
3056
3057 // THEN the state in dpms is not changed
3058 assertTrue(dpms.hasUserSetupCompleted());
3059 }
3060
3061 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3062 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3063 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3064
3065 final int userId = UserHandle.USER_SYSTEM;
3066 // GIVEN userComplete is false in SettingsProvider
3067 setUserSetupCompleteForUser(false, userId);
3068
3069 // GIVEN userComplete is true in DPM
3070 DevicePolicyManagerService.DevicePolicyData userData =
3071 new DevicePolicyManagerService.DevicePolicyData(userId);
3072 userData.mUserSetupComplete = true;
3073 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3074
3075 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003076 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003077
3078 assertTrue(dpms.hasUserSetupCompleted());
3079
3080 dpm.forceUpdateUserSetupComplete();
3081
3082 // THEN the state in dpms is not changed
3083 assertFalse(dpms.hasUserSetupCompleted());
3084 }
3085
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003086 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003087 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003088 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003089
3090 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3091 runAsCaller(mAdmin1Context, dpms, dpm -> {
3092 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3093 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003094 }
3095
3096 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3097 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3098 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003099
3100 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3101 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003102 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003103 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3104 .thenReturn(true);
3105
3106 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003107 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003108
3109 // Enabling logging should not change the timestamp.
3110 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003111 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003112 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003113 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003114 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003115 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003116
3117 // Retrieving the logs should update the timestamp.
3118 final long beforeRetrieval = System.currentTimeMillis();
3119 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003120 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003121 final long afterRetrieval = System.currentTimeMillis();
3122 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3123 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3124
3125 // Retrieving the pre-boot logs should update the timestamp.
3126 Thread.sleep(2);
3127 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003128 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003129 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3130
3131 // Checking the timestamp again should not change it.
3132 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003133 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003134
3135 // Retrieving the logs again should update the timestamp.
3136 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003137 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003138 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3139
3140 // Disabling logging should not change the timestamp.
3141 Thread.sleep(2);
3142 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003143 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003144
3145 // Restarting the DPMS should not lose the timestamp.
3146 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003147 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003148
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003149 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3150 mContext.binder.callingUid = 1234567;
3151 mContext.callerPermissions.add(permission.MANAGE_USERS);
3152 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3153 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3154
3155 // System can retrieve the timestamp.
3156 mContext.binder.clearCallingIdentity();
3157 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3158
3159 // Removing the device owner should clear the timestamp.
3160 clearDeviceOwner();
3161 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003162 }
3163
yuemingw0de748d2017-11-15 19:22:27 +00003164 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3165 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3166 setupDeviceOwner();
3167 assertExpectException(SecurityException.class, null, () ->
3168 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3169 }
3170
3171 public void testSetSystemSettingFailWithPO() throws Exception {
3172 setupProfileOwner();
3173 assertExpectException(SecurityException.class, null, () ->
3174 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"));
3175 }
3176
3177 public void testSetSystemSetting() throws Exception {
3178 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3179 setupDeviceOwner();
3180 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3181 verify(getServices().settings).settingsSystemPutString(
3182 Settings.System.SCREEN_BRIGHTNESS, "0");
3183 }
3184
yuemingwe43cdf72017-10-12 16:52:11 +01003185 public void testSetTime() throws Exception {
3186 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3187 setupDeviceOwner();
3188 dpm.setTime(admin1, 0);
3189 verify(getServices().alarmManager).setTime(0);
3190 }
3191
3192 public void testSetTimeFailWithPO() throws Exception {
3193 setupProfileOwner();
3194 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3195 }
3196
3197 public void testSetTimeWithAutoTimeOn() throws Exception {
3198 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3199 setupDeviceOwner();
3200 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3201 .thenReturn(1);
3202 assertFalse(dpm.setTime(admin1, 0));
3203 }
3204
3205 public void testSetTimeZone() throws Exception {
3206 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3207 setupDeviceOwner();
3208 dpm.setTimeZone(admin1, "Asia/Shanghai");
3209 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3210 }
3211
3212 public void testSetTimeZoneFailWithPO() throws Exception {
3213 setupProfileOwner();
3214 assertExpectException(SecurityException.class, null,
3215 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3216 }
3217
3218 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3219 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3220 setupDeviceOwner();
3221 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3222 .thenReturn(1);
3223 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3224 }
3225
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003226 public void testGetLastBugReportRequestTime() throws Exception {
3227 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3228 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003229
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003230 mContext.packageName = admin1.getPackageName();
3231 mContext.applicationInfo = new ApplicationInfo();
3232 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3233 .thenReturn(Color.WHITE);
3234 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3235 anyObject())).thenReturn(Color.WHITE);
3236
Esteban Talaverad36dd152016-12-15 08:51:45 +00003237 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3238 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003239 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003240
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003241 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003242 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003243
3244 // Requesting a bug report should update the timestamp.
3245 final long beforeRequest = System.currentTimeMillis();
3246 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003247 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003248 final long afterRequest = System.currentTimeMillis();
3249 assertTrue(bugReportRequestTime >= beforeRequest);
3250 assertTrue(bugReportRequestTime <= afterRequest);
3251
3252 // Checking the timestamp again should not change it.
3253 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003254 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003255
3256 // Restarting the DPMS should not lose the timestamp.
3257 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003258 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003259
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003260 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3261 mContext.binder.callingUid = 1234567;
3262 mContext.callerPermissions.add(permission.MANAGE_USERS);
3263 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3264 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3265
3266 // System can retrieve the timestamp.
3267 mContext.binder.clearCallingIdentity();
3268 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3269
3270 // Removing the device owner should clear the timestamp.
3271 clearDeviceOwner();
3272 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003273 }
3274
3275 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3276 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3277 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003278 mContext.packageName = admin1.getPackageName();
3279 mContext.applicationInfo = new ApplicationInfo();
3280 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3281 .thenReturn(Color.WHITE);
3282 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3283 anyObject())).thenReturn(Color.WHITE);
3284
3285 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3286 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003287 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003288 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003289 .thenReturn(true);
3290
3291 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003292 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003293
3294 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3295 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003296 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003297
3298 // Enabling logging should not change the timestamp.
3299 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003300 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003301
3302 // Retrieving the logs should update the timestamp.
3303 final long beforeRetrieval = System.currentTimeMillis();
3304 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003305 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003306 final long afterRetrieval = System.currentTimeMillis();
3307 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3308 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3309
3310 // Checking the timestamp again should not change it.
3311 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003312 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003313
3314 // Retrieving the logs again should update the timestamp.
3315 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003316 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003317 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3318
3319 // Disabling logging should not change the timestamp.
3320 Thread.sleep(2);
3321 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003322 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003323
3324 // Restarting the DPMS should not lose the timestamp.
3325 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003326 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3327
3328 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3329 mContext.binder.callingUid = 1234567;
3330 mContext.callerPermissions.add(permission.MANAGE_USERS);
3331 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3332 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3333
3334 // System can retrieve the timestamp.
3335 mContext.binder.clearCallingIdentity();
3336 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3337
3338 // Removing the device owner should clear the timestamp.
3339 clearDeviceOwner();
3340 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003341 }
3342
Tony Mak2f26b792016-11-28 17:54:51 +00003343 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3344 // Setup device owner.
3345 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3346 setupDeviceOwner();
3347
3348 // Only device owner is setup, the result list should be empty.
3349 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3350 MoreAsserts.assertEmpty(targetUsers);
3351
3352 // Setup a managed profile managed by the same admin.
3353 final int MANAGED_PROFILE_USER_ID = 15;
3354 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3355 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3356
3357 // Add a secondary user, it should never talk with.
3358 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003359 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003360
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003361 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3362 // other.
3363 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3364 MoreAsserts.assertEmpty(targetUsers);
3365
3366 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3367 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3368 MoreAsserts.assertEmpty(targetUsers);
3369
3370 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003371 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003372 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3373 dpm.setAffiliationIds(admin1, userAffiliationIds);
3374
3375 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3376 dpm.setAffiliationIds(admin1, userAffiliationIds);
3377
Tony Mak2f26b792016-11-28 17:54:51 +00003378 // Calling from device owner admin, the result list should just contain the managed
3379 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003380 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003381 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3382 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3383
3384 // Calling from managed profile admin, the result list should just contain the system
3385 // user id.
3386 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3387 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3388 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003389
3390 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003391 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003392
3393 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3394 // to each other.
3395 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3396 MoreAsserts.assertEmpty(targetUsers);
3397
3398 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3399 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3400 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003401 }
3402
3403 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3404 // Setup a device owner.
3405 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3406 setupDeviceOwner();
3407
3408 // Set up a managed profile managed by different package.
3409 final int MANAGED_PROFILE_USER_ID = 15;
3410 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3411 final ComponentName adminDifferentPackage =
3412 new ComponentName("another.package", "whatever.class");
3413 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3414
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003415 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003416 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003417 dpm.setAffiliationIds(admin1, userAffiliationIds);
3418
3419 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3420 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3421
Tony Mak2f26b792016-11-28 17:54:51 +00003422 // Calling from device owner admin, we should get zero bind device admin target users as
3423 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003424 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003425 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3426 MoreAsserts.assertEmpty(targetUsers);
3427
3428 // Calling from managed profile admin, we should still get zero target users for the same
3429 // reason.
3430 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3431 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3432 MoreAsserts.assertEmpty(targetUsers);
3433 }
3434
Charles Hee078db72017-10-19 18:03:20 +01003435 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003436 // Setup a device owner.
3437 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3438 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003439 // Lock task policy is updated when loading user data.
3440 verify(getServices().iactivityManager).updateLockTaskPackages(
3441 UserHandle.USER_SYSTEM, new String[0]);
3442 verify(getServices().iactivityManager).updateLockTaskFeatures(
3443 UserHandle.USER_SYSTEM, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003444
3445 // Set up a managed profile managed by different package (package name shouldn't matter)
3446 final int MANAGED_PROFILE_USER_ID = 15;
3447 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3448 final ComponentName adminDifferentPackage =
3449 new ComponentName("another.package", "whatever.class");
3450 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Charles Hee078db72017-10-19 18:03:20 +01003451 verify(getServices().iactivityManager).updateLockTaskPackages(
3452 MANAGED_PROFILE_USER_ID, new String[0]);
3453 verify(getServices().iactivityManager).updateLockTaskFeatures(
3454 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003455
3456 // The DO can still set lock task packages
3457 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3458 final String[] doPackages = {"doPackage1", "doPackage2"};
3459 dpm.setLockTaskPackages(admin1, doPackages);
3460 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3461 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3462 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Charles Hee078db72017-10-19 18:03:20 +01003463 verify(getServices().iactivityManager).updateLockTaskPackages(
3464 UserHandle.USER_SYSTEM, doPackages);
3465 // And the DO can still set lock task features
3466 final int doFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3467 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3468 dpm.setLockTaskFeatures(admin1, doFlags);
3469 verify(getServices().iactivityManager).updateLockTaskFeatures(
3470 UserHandle.USER_SYSTEM, doFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003471
3472 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3473 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3474 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003475 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3476 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3477 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3478 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003479 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
Charles Hee078db72017-10-19 18:03:20 +01003480 // And it shouldn't be able to setLockTaskFeatures.
3481 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3482 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3483 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3484 () -> dpm.setLockTaskFeatures(adminDifferentPackage, poFlags));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003485
3486 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003487 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003488 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3489 dpm.setAffiliationIds(admin1, userAffiliationIds);
3490
3491 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3492 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3493
3494 // Now the managed profile can set lock task packages.
3495 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3496 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3497 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3498 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003499 verify(getServices().iactivityManager).updateLockTaskPackages(
3500 MANAGED_PROFILE_USER_ID, poPackages);
3501 // And it can set lock task features.
3502 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
3503 verify(getServices().iactivityManager).updateLockTaskFeatures(
3504 MANAGED_PROFILE_USER_ID, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003505
3506 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003507 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003508 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3509 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003510 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3511 MANAGED_PROFILE_USER_ID, new String[0]);
3512 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3513 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003514
3515 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3516 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3517 }
3518
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003519 public void testIsDeviceManaged() throws Exception {
3520 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3521 setupDeviceOwner();
3522
3523 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3524 // find out that the device has a device owner.
3525 assertTrue(dpm.isDeviceManaged());
3526 mContext.binder.callingUid = 1234567;
3527 mContext.callerPermissions.add(permission.MANAGE_USERS);
3528 assertTrue(dpm.isDeviceManaged());
3529 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3530 mContext.binder.clearCallingIdentity();
3531 assertTrue(dpm.isDeviceManaged());
3532
3533 clearDeviceOwner();
3534
3535 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3536 // not have a device owner.
3537 mContext.binder.callingUid = 1234567;
3538 mContext.callerPermissions.add(permission.MANAGE_USERS);
3539 assertFalse(dpm.isDeviceManaged());
3540 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3541 mContext.binder.clearCallingIdentity();
3542 assertFalse(dpm.isDeviceManaged());
3543 }
3544
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003545 public void testDeviceOwnerOrganizationName() throws Exception {
3546 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3547 setupDeviceOwner();
3548
3549 dpm.setOrganizationName(admin1, "organization");
3550
3551 // Device owner can retrieve organization managing the device.
3552 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3553
3554 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3555 mContext.binder.callingUid = 1234567;
3556 mContext.callerPermissions.add(permission.MANAGE_USERS);
3557 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3558 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3559
3560 // System can retrieve organization managing the device.
3561 mContext.binder.clearCallingIdentity();
3562 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3563
3564 // Removing the device owner clears the organization managing the device.
3565 clearDeviceOwner();
3566 assertNull(dpm.getDeviceOwnerOrganizationName());
3567 }
3568
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003569 public void testWipeDataManagedProfile() throws Exception {
3570 final int MANAGED_PROFILE_USER_ID = 15;
3571 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3572 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3573 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3574
3575 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003576 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003577 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003578 // Get mock reason string since we throw an IAE with empty string input.
3579 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3580 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003581
3582 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003583 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003584 MANAGED_PROFILE_USER_ID);
3585 }
3586
3587 public void testWipeDataManagedProfileDisallowed() throws Exception {
3588 final int MANAGED_PROFILE_USER_ID = 15;
3589 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3590 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3591
3592 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003593 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003594 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3595
Pavel Grafov75c0a892017-05-18 17:28:27 +01003596 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003597 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3598 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3599 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003600 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3601 thenReturn("Just a test string.");
3602
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003603 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003604 // The PO is not allowed to remove the profile if the user restriction was set on the
3605 // profile by the system
3606 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3607 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003608 }
3609
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003610 public void testWipeDataDeviceOwner() throws Exception {
3611 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003612 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003613 UserManager.DISALLOW_FACTORY_RESET,
3614 UserHandle.SYSTEM))
3615 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003616 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3617 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003618
3619 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003620 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003621 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3622 /*wipeEuicc=*/ eq(false));
3623 }
3624
3625 public void testWipeEuiccDataEnabled() throws Exception {
3626 setDeviceOwner();
3627 when(getServices().userManager.getUserRestrictionSource(
3628 UserManager.DISALLOW_FACTORY_RESET,
3629 UserHandle.SYSTEM))
3630 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003631 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3632 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003633
3634 dpm.wipeData(WIPE_EUICC);
3635 verify(getServices().recoverySystem).rebootWipeUserData(
3636 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3637 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003638 }
3639
3640 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3641 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003642 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003643 UserManager.DISALLOW_FACTORY_RESET,
3644 UserHandle.SYSTEM))
3645 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003646 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3647 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003648 // The DO is not allowed to wipe the device if the user restriction was set
3649 // by the system
3650 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3651 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003652 }
3653
3654 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3655 final int MANAGED_PROFILE_USER_ID = 15;
3656 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3657 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3658
3659 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003660 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003661 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3662
Pavel Grafov75c0a892017-05-18 17:28:27 +01003663 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003664 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3665 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3666 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3667
3668 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3669 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3670
3671 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3672 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3673 // Failed password attempts on the parent user are taken into account, as there isn't a
3674 // separate work challenge.
3675 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3676 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3677 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3678
3679 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3680 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003681 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003682 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003683 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003684 }
3685
3686 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3687 throws Exception {
3688 final int MANAGED_PROFILE_USER_ID = 15;
3689 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3690 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3691
3692 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003693 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003694 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3695
Pavel Grafov75c0a892017-05-18 17:28:27 +01003696 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003697 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3698 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3699 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3700
3701 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3702 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3703
3704 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3705 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3706 // Failed password attempts on the parent user are taken into account, as there isn't a
3707 // separate work challenge.
3708 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3709 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3710 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3711
3712 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3713 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003714 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003715 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003716 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003717 }
3718
3719 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3720 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003721 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003722 UserManager.DISALLOW_FACTORY_RESET,
3723 UserHandle.SYSTEM))
3724 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3725
3726 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3727
3728 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3729 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3730 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3731 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3732 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3733
3734 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3735 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003736 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003737 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3738 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003739 }
3740
3741 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3742 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003743 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003744 UserManager.DISALLOW_FACTORY_RESET,
3745 UserHandle.SYSTEM))
3746 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3747
3748 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3749
3750 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3751 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3752 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3753 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3754 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3755
3756 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003757 verifyZeroInteractions(getServices().recoverySystem);
3758 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003759 .removeUserEvenWhenDisallowed(anyInt());
3760 }
3761
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003762 public void testGetPermissionGrantState() throws Exception {
3763 final String permission = "some.permission";
3764 final String app1 = "com.example.app1";
3765 final String app2 = "com.example.app2";
3766
Pavel Grafov75c0a892017-05-18 17:28:27 +01003767 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003768 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003769 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003770 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003771 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003772 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3773 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003774 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003775 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003776 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003777 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003778 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003779 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3780
3781 // System can retrieve permission grant state.
3782 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003783 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003784 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3785 dpm.getPermissionGrantState(null, app1, permission));
3786 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3787 dpm.getPermissionGrantState(null, app2, permission));
3788
3789 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003790 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3791 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003792 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3793 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003794
3795 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003796 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3797 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003798 setAsProfileOwner(admin1);
3799 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3800 dpm.getPermissionGrantState(admin1, app1, permission));
3801 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3802 dpm.getPermissionGrantState(admin1, app2, permission));
3803 }
3804
Rubin Xuaab7a412016-12-30 21:13:29 +00003805 public void testResetPasswordWithToken() throws Exception {
3806 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3807 setupDeviceOwner();
3808 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003809 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3810 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3811
Rubin Xuaab7a412016-12-30 21:13:29 +00003812 // test adding a token
3813 final byte[] token = new byte[32];
3814 final long handle = 123456;
3815 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003816 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003817 .thenReturn(handle);
3818 assertTrue(dpm.setResetPasswordToken(admin1, token));
3819
3820 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003821 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003822 .thenReturn(true);
3823 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3824
3825 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003826 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01003827 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
3828 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00003829 eq(UserHandle.USER_SYSTEM)))
3830 .thenReturn(true);
3831 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3832
3833 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003834 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003835 .thenReturn(true);
3836 assertTrue(dpm.clearResetPasswordToken(admin1));
3837 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003838
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003839 public void testIsActivePasswordSufficient() throws Exception {
3840 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3841 mContext.packageName = admin1.getPackageName();
3842 setupDeviceOwner();
3843
3844 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3845 dpm.setPasswordMinimumLength(admin1, 8);
3846 dpm.setPasswordMinimumLetters(admin1, 6);
3847 dpm.setPasswordMinimumLowerCase(admin1, 3);
3848 dpm.setPasswordMinimumUpperCase(admin1, 1);
3849 dpm.setPasswordMinimumNonLetter(admin1, 1);
3850 dpm.setPasswordMinimumNumeric(admin1, 1);
3851 dpm.setPasswordMinimumSymbols(admin1, 0);
3852
3853 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3854 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3855 8, 2,
3856 6, 1,
3857 0, 1);
3858
3859 setActivePasswordState(passwordMetricsNoSymbols);
3860 assertTrue(dpm.isActivePasswordSufficient());
3861
3862 initializeDpms();
3863 reset(mContext.spiedContext);
3864 assertTrue(dpm.isActivePasswordSufficient());
3865
3866 // This call simulates the user entering the password for the first time after a reboot.
3867 // This causes password metrics to be reloaded into memory. Until this happens,
3868 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3869 // even if the DPC changes password requirements so that the password no longer meets the
3870 // requirements. This is a known limitation of the current implementation of
3871 // isActivePasswordSufficient() - see b/34218769.
3872 setActivePasswordState(passwordMetricsNoSymbols);
3873 assertTrue(dpm.isActivePasswordSufficient());
3874
3875 dpm.setPasswordMinimumSymbols(admin1, 1);
3876 // This assertion would fail if we had not called setActivePasswordState() again after
3877 // initializeDpms() - see previous comment.
3878 assertFalse(dpm.isActivePasswordSufficient());
3879
3880 initializeDpms();
3881 reset(mContext.spiedContext);
3882 assertFalse(dpm.isActivePasswordSufficient());
3883
3884 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3885 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3886 7, 2,
3887 5, 1,
3888 1, 2);
3889
3890 setActivePasswordState(passwordMetricsWithSymbols);
3891 assertTrue(dpm.isActivePasswordSufficient());
3892 }
3893
Pavel Grafov75c0a892017-05-18 17:28:27 +01003894 private void setActivePasswordState(PasswordMetrics passwordMetrics)
3895 throws Exception {
3896 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003897 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003898
Pavel Grafov75c0a892017-05-18 17:28:27 +01003899 dpm.setActivePasswordState(passwordMetrics, userHandle);
3900 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003901
Pavel Grafov75c0a892017-05-18 17:28:27 +01003902 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3903 intent.setComponent(admin1);
3904 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3905
3906 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3907 MockUtils.checkIntent(intent),
3908 MockUtils.checkUserHandle(userHandle));
3909
3910 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
3911 // let it finish with system uid, otherwise it will throw and crash.
3912 flushTasks();
3913
3914 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003915 }
3916
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003917 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3918 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3919 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3920 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3921 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3922 DpmMockContext.SYSTEM_UID);
3923 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3924 DpmMockContext.SYSTEM_UID);
3925
3926 // Set up a device owner.
3927 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003928 setupDeviceOwner();
3929
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003930 // First and second user set IMEs manually.
3931 mContext.binder.callingUid = firstUserSystemUid;
3932 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3933 mContext.binder.callingUid = secondUserSystemUid;
3934 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003935
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003936 // Device owner changes IME for first user.
3937 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003938 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003939 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003940 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003941 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003942 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003943 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003944 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3945 mContext.binder.callingUid = firstUserSystemUid;
3946 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3947 mContext.binder.callingUid = secondUserSystemUid;
3948 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003949
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003950 // Second user changes IME manually.
3951 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3952 mContext.binder.callingUid = firstUserSystemUid;
3953 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3954 mContext.binder.callingUid = secondUserSystemUid;
3955 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003956
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003957 // First user changes IME manually.
3958 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3959 mContext.binder.callingUid = firstUserSystemUid;
3960 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3961 mContext.binder.callingUid = secondUserSystemUid;
3962 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003963
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003964 // Device owner changes IME for first user again.
3965 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003966 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003967 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003968 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003969 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003970 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003971 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3972 mContext.binder.callingUid = firstUserSystemUid;
3973 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3974 mContext.binder.callingUid = secondUserSystemUid;
3975 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003976
3977 // Restarting the DPMS should not lose information.
3978 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003979 mContext.binder.callingUid = firstUserSystemUid;
3980 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3981 mContext.binder.callingUid = secondUserSystemUid;
3982 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003983
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003984 // Device owner can find out whether it set the current IME itself.
3985 mContext.binder.callingUid = deviceOwnerUid;
3986 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003987
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003988 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003989 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003990 mContext.binder.callingUid = firstUserSystemUid;
3991 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3992 mContext.binder.callingUid = secondUserSystemUid;
3993 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003994 }
3995
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003996 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3997 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3998 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3999 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4000 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4001 DpmMockContext.SYSTEM_UID);
4002 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4003 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004004
4005 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004006 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004007 setupProfileOwner();
4008
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004009 // First and second user set IMEs manually.
4010 mContext.binder.callingUid = firstUserSystemUid;
4011 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4012 mContext.binder.callingUid = secondUserSystemUid;
4013 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004014
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004015 // Profile owner changes IME for second user.
4016 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004017 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004018 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004019 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004020 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004021 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004022 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004023 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4024 mContext.binder.callingUid = firstUserSystemUid;
4025 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4026 mContext.binder.callingUid = secondUserSystemUid;
4027 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004028
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004029 // First user changes IME manually.
4030 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4031 mContext.binder.callingUid = firstUserSystemUid;
4032 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4033 mContext.binder.callingUid = secondUserSystemUid;
4034 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004035
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004036 // Second user changes IME manually.
4037 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4038 mContext.binder.callingUid = firstUserSystemUid;
4039 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4040 mContext.binder.callingUid = secondUserSystemUid;
4041 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004042
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004043 // Profile owner changes IME for second user again.
4044 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004045 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004046 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004047 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004048 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004049 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004050 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4051 mContext.binder.callingUid = firstUserSystemUid;
4052 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4053 mContext.binder.callingUid = secondUserSystemUid;
4054 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004055
4056 // Restarting the DPMS should not lose information.
4057 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004058 mContext.binder.callingUid = firstUserSystemUid;
4059 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4060 mContext.binder.callingUid = secondUserSystemUid;
4061 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004062
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004063 // Profile owner can find out whether it set the current IME itself.
4064 mContext.binder.callingUid = profileOwnerUid;
4065 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004066
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004067 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004068 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004069 mContext.binder.callingUid = firstUserSystemUid;
4070 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4071 mContext.binder.callingUid = secondUserSystemUid;
4072 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004073 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004074
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004075 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4076 throws Exception {
4077 // Set up a device owner.
4078 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4079 setupDeviceOwner();
4080 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4081 }
4082
4083 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4084 throws Exception {
4085 // Set up a profile owner.
4086 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4087 setupProfileOwner();
4088 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4089 }
4090
4091 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4092 int adminUid) throws Exception {
4093 mContext.binder.callingUid = adminUid;
4094 final int userId = UserHandle.getUserId(adminUid);
4095
4096 final String packageName = "some.package";
4097 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4098 admin1, Collections.singletonList(packageName)));
4099 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4100
4101 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4102 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4103
4104 // Attempt to set to empty list (which means no listener is whitelisted)
4105 mContext.binder.callingUid = adminUid;
4106 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004107 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004108 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4109
4110 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4111 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4112 }
4113
4114 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4115 // Set up a managed profile
4116 final int MANAGED_PROFILE_USER_ID = 15;
4117 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4118 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4119 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4120
4121 final String permittedListener = "some.package";
4122 setupPackageInPackageManager(
4123 permittedListener,
4124 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4125 /*appId=*/ 12345, /*flags=*/ 0);
4126
4127 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4128 admin1, Collections.singletonList(permittedListener)));
4129
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004130 // isNotificationListenerServicePermitted should throw if not called from System.
4131 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4132 () -> dpms.isNotificationListenerServicePermitted(
4133 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004134
4135 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4136 assertTrue(dpms.isNotificationListenerServicePermitted(
4137 permittedListener, MANAGED_PROFILE_USER_ID));
4138 }
4139
4140 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4141 throws Exception {
4142 // Set up a managed profile
4143 final int MANAGED_PROFILE_USER_ID = 15;
4144 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4145 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4146 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4147
4148 final String permittedListener = "permitted.package";
4149 int appId = 12345;
4150 setupPackageInPackageManager(
4151 permittedListener,
4152 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4153 appId, /*flags=*/ 0);
4154
4155 final String notPermittedListener = "not.permitted.package";
4156 setupPackageInPackageManager(
4157 notPermittedListener,
4158 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4159 ++appId, /*flags=*/ 0);
4160
4161 final String systemListener = "system.package";
4162 setupPackageInPackageManager(
4163 systemListener,
4164 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4165 ++appId, ApplicationInfo.FLAG_SYSTEM);
4166
4167 // By default all packages are allowed
4168 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4169
4170 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4171 assertTrue(dpms.isNotificationListenerServicePermitted(
4172 permittedListener, MANAGED_PROFILE_USER_ID));
4173 assertTrue(dpms.isNotificationListenerServicePermitted(
4174 notPermittedListener, MANAGED_PROFILE_USER_ID));
4175 assertTrue(dpms.isNotificationListenerServicePermitted(
4176 systemListener, MANAGED_PROFILE_USER_ID));
4177
4178 // Setting only one package in the whitelist
4179 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4180 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4181 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004182 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004183 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4184 assertEquals(1, permittedListeners.size());
4185 assertEquals(permittedListener, permittedListeners.get(0));
4186
4187 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4188 assertTrue(dpms.isNotificationListenerServicePermitted(
4189 permittedListener, MANAGED_PROFILE_USER_ID));
4190 assertFalse(dpms.isNotificationListenerServicePermitted(
4191 notPermittedListener, MANAGED_PROFILE_USER_ID));
4192 // System packages are always allowed (even if not in the whitelist)
4193 assertTrue(dpms.isNotificationListenerServicePermitted(
4194 systemListener, MANAGED_PROFILE_USER_ID));
4195
4196 // Setting an empty whitelist - only system listeners allowed
4197 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4198 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004199 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004200 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4201
4202 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4203 assertFalse(dpms.isNotificationListenerServicePermitted(
4204 permittedListener, MANAGED_PROFILE_USER_ID));
4205 assertFalse(dpms.isNotificationListenerServicePermitted(
4206 notPermittedListener, MANAGED_PROFILE_USER_ID));
4207 // System packages are always allowed (even if not in the whitelist)
4208 assertTrue(dpms.isNotificationListenerServicePermitted(
4209 systemListener, MANAGED_PROFILE_USER_ID));
4210
4211 // Setting a null whitelist - all listeners allowed
4212 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4213 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4214 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4215
4216 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4217 assertTrue(dpms.isNotificationListenerServicePermitted(
4218 permittedListener, MANAGED_PROFILE_USER_ID));
4219 assertTrue(dpms.isNotificationListenerServicePermitted(
4220 notPermittedListener, MANAGED_PROFILE_USER_ID));
4221 assertTrue(dpms.isNotificationListenerServicePermitted(
4222 systemListener, MANAGED_PROFILE_USER_ID));
4223 }
4224
4225 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4226 throws Exception {
4227 // Set up a managed profile
4228 final int MANAGED_PROFILE_USER_ID = 15;
4229 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4230 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4231 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4232
4233 final String nonSystemPackage = "non.system.package";
4234 int appId = 12345;
4235 setupPackageInPackageManager(
4236 nonSystemPackage,
4237 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4238 appId, /*flags=*/ 0);
4239
4240 final String systemListener = "system.package";
4241 setupPackageInPackageManager(
4242 systemListener,
4243 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4244 ++appId, ApplicationInfo.FLAG_SYSTEM);
4245
4246 // By default all packages are allowed (for all profiles)
4247 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4248
4249 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4250 assertTrue(dpms.isNotificationListenerServicePermitted(
4251 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4252 assertTrue(dpms.isNotificationListenerServicePermitted(
4253 systemListener, MANAGED_PROFILE_USER_ID));
4254 assertTrue(dpms.isNotificationListenerServicePermitted(
4255 nonSystemPackage, UserHandle.USER_SYSTEM));
4256 assertTrue(dpms.isNotificationListenerServicePermitted(
4257 systemListener, UserHandle.USER_SYSTEM));
4258
4259 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4260 // all allowed in primary profile
4261 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4262 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004263 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004264 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4265
4266 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4267 assertFalse(dpms.isNotificationListenerServicePermitted(
4268 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4269 assertTrue(dpms.isNotificationListenerServicePermitted(
4270 systemListener, MANAGED_PROFILE_USER_ID));
4271 assertTrue(dpms.isNotificationListenerServicePermitted(
4272 nonSystemPackage, UserHandle.USER_SYSTEM));
4273 assertTrue(dpms.isNotificationListenerServicePermitted(
4274 systemListener, UserHandle.USER_SYSTEM));
4275 }
4276
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004277 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004278 mServiceContext.packageName = mRealTestContext.getPackageName();
4279 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4280 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004281 setDeviceOwner();
4282
Pavel Grafov75c0a892017-05-18 17:28:27 +01004283 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004284 }
4285
4286 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004287 mServiceContext.packageName = mRealTestContext.getPackageName();
4288 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4289 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004290 setAsProfileOwner(admin1);
4291
Pavel Grafov75c0a892017-05-18 17:28:27 +01004292 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4293 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004294 }
4295
4296 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004297 mServiceContext.packageName = mRealTestContext.getPackageName();
4298 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4299 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004300 setAsProfileOwner(admin1);
4301
Pavel Grafov75c0a892017-05-18 17:28:27 +01004302 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4303 caller.packageName = "com.example.delegate";
4304 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4305 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004306
Pavel Grafov75c0a892017-05-18 17:28:27 +01004307 // Make caller a delegated cert installer.
4308 runAsCaller(mAdmin1Context, dpms,
4309 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004310
4311 verifyCanGetOwnerInstalledCaCerts(null, caller);
4312 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004313 }
4314
Robin Lee2c68dad2017-03-17 12:50:24 +00004315 private void verifyCanGetOwnerInstalledCaCerts(
4316 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004317 final String alias = "cert";
4318 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004319
4320 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004321 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004322 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4323 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004324 }
4325 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4326
4327 // caller: device admin or delegated certificate installer
4328 callerContext.applicationInfo = new ApplicationInfo();
4329 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4330
4331 // system_server
4332 final DpmMockContext serviceContext = mContext;
4333 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004334 getServices().addPackageContext(callerUser, admin1Context);
4335 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004336
4337 // Install a CA cert.
4338 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004339 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004340 .thenReturn(alias);
4341 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004342 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004343 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004344 });
4345
Pavel Grafov75c0a892017-05-18 17:28:27 +01004346 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4347 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4348 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004349 flushTasks();
4350
Robin Lee2c68dad2017-03-17 12:50:24 +00004351 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4352
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004353 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004354 runAsCaller(admin1Context, dpms, (dpm) -> {
4355 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004356 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004357 ownerInstalledCaCerts.addAll(installedCaCerts);
4358 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004359
4360 // Restarting the DPMS should not lose information.
4361 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004362 runAsCaller(admin1Context, dpms, (dpm) ->
4363 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004364
4365 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004366 runAsCaller(serviceContext, dpms, (dpm) -> {
4367 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004368
Robin Lee2c68dad2017-03-17 12:50:24 +00004369 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004370 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004371 });
4372
Pavel Grafov75c0a892017-05-18 17:28:27 +01004373 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4374 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4375 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004376 flushTasks();
4377
4378 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4379 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004380 runAsCaller(admin1Context, dpms, (dpm) -> {
4381 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4382 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004383 }
4384
Robin Lee2c68dad2017-03-17 12:50:24 +00004385 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4386 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004387 final String alias = "cert";
4388 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004389
4390 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004391 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004392 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4393 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004394 }
4395 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4396
4397 // caller: device admin or delegated certificate installer
4398 callerContext.applicationInfo = new ApplicationInfo();
4399 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4400
4401 // system_server
4402 final DpmMockContext serviceContext = mContext;
4403 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004404 getServices().addPackageContext(callerUser, admin1Context);
4405 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004406
4407 // Install a CA cert as caller
4408 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004409 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004410 .thenReturn(alias);
4411 assertTrue(dpm.installCaCert(callerName, caCert));
4412 });
4413
4414 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004415 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004416 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004417 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4418 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4419 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004420 flushTasks();
4421
Robin Lee2c68dad2017-03-17 12:50:24 +00004422 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004423 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004424
4425 runAsCaller(serviceContext, dpms, (dpm) -> {
4426 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4427 assertNotNull(ownerInstalledCaCerts);
4428 assertTrue(ownerInstalledCaCerts.isEmpty());
4429 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004430 }
4431
Victor Chang3e794af2016-03-04 13:48:17 +00004432 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004433 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004434 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4435 dpms.notifyChangeToContentObserver(
4436 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4437 }
4438
4439 private void assertProvisioningAllowed(String action, boolean expected) {
4440 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4441 dpm.isProvisioningAllowed(action));
4442 }
Tony Mak2f26b792016-11-28 17:54:51 +00004443
Nicolas Prevot45d29072017-01-18 16:11:19 +00004444 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4445 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004446 final String previousPackageName = mContext.packageName;
4447 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004448
4449 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4450 mContext.packageName = packageName;
4451 mMockContext.binder.callingUid = uid;
4452 assertProvisioningAllowed(action, expected);
4453
4454 // Set the previous package name / calling uid to go back to the initial state.
4455 mContext.packageName = previousPackageName;
4456 mMockContext.binder.callingUid = previousUid;
4457 }
4458
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004459 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004460 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4461 }
4462
4463 private void assertCheckProvisioningPreCondition(
4464 String action, String packageName, int provisioningCondition) {
4465 assertEquals("checkProvisioningPreCondition("
4466 + action + ", " + packageName + ") returning unexpected result",
4467 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004468 }
4469
Tony Mak2f26b792016-11-28 17:54:51 +00004470 /**
4471 * Setup a managed profile with the specified admin and its uid.
4472 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4473 * @param adminUid uid of the admin package.
4474 * @param copyFromAdmin package information for {@code admin} will be built based on this
4475 * component's information.
4476 */
4477 private void addManagedProfile(
4478 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4479 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004480 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004481 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4482 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4483 dpm.setActiveAdmin(admin, false, userId);
4484 assertTrue(dpm.setProfileOwner(admin, null, userId));
4485 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4486 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004487
4488 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004489 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004490 */
Robin Leeabaa0692017-02-20 20:54:22 +00004491 private static StringParceledListSlice asSlice(String[] s) {
4492 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004493 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004494
4495 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004496 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4497 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004498
Robin Lee2c68dad2017-03-17 12:50:24 +00004499 // We can't let exceptions happen on the background thread. Throw them here if they happen
4500 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004501 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004502 }
Victor Chang3e794af2016-03-04 13:48:17 +00004503}