blob: c58b733b8b548eef1e3dfa74b0ec3472f684fdb1 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
yinxuf4f9cec2017-06-19 10:28:19 -070020import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010021import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
22import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
23import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
24
Pavel Grafova1ea8d92017-05-25 21:55:24 +010025import static com.android.server.testutis.TestUtils.assertExpectException;
26
Pavel Grafov75c0a892017-05-18 17:28:27 +010027import static org.mockito.Matchers.any;
28import static org.mockito.Matchers.anyInt;
29import static org.mockito.Matchers.anyLong;
30import static org.mockito.Matchers.anyObject;
31import static org.mockito.Matchers.anyString;
32import static org.mockito.Matchers.eq;
33import static org.mockito.Matchers.isNull;
34import static org.mockito.Mockito.atLeast;
35import static org.mockito.Mockito.doAnswer;
36import static org.mockito.Mockito.doReturn;
37import static org.mockito.Mockito.never;
38import static org.mockito.Mockito.nullable;
39import static org.mockito.Mockito.reset;
40import static org.mockito.Mockito.timeout;
41import static org.mockito.Mockito.times;
42import static org.mockito.Mockito.verify;
43import static org.mockito.Mockito.verifyZeroInteractions;
44import static org.mockito.Mockito.when;
45import static org.mockito.hamcrest.MockitoHamcrest.argThat;
46
Makoto Onukif76b06a2015-09-22 15:03:44 -070047import android.Manifest.permission;
48import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000049import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070050import android.app.admin.DeviceAdminReceiver;
51import android.app.admin.DevicePolicyManager;
52import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010053import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070054import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070055import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000056import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000057import android.content.pm.ApplicationInfo;
58import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070059import android.content.pm.PackageManager;
Robin Leeabaa0692017-02-20 20:54:22 +000060import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000061import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010062import android.graphics.Color;
63import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080064import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080065import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070066import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080067import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070068import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070069import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080070import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010071import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000072import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080073import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000074import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010075import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070076import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070077
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010078import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000079import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000080import com.android.server.LocalServices;
81import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000082import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000083
Robin Lee7f5c91c2017-02-08 21:27:02 +000084import org.hamcrest.BaseMatcher;
85import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070086import org.mockito.invocation.InvocationOnMock;
87import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070088
Makoto Onukic8a5a552015-11-19 14:29:12 -080089import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000090import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000091import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070092import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070093import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070094import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010095import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000096import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070097
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070099 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000100 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700101 m FrameworksServicesTests &&
102 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000103 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700104 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800105 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106
107 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000108 *
109 * , or:
110 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000112@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000114 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
115 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
116 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100117 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
118 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000119
Pavel Grafov75c0a892017-05-18 17:28:27 +0100120 // TODO replace all instances of this with explicit {@link #mServiceContext}.
121 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700122 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100123
124 private DpmMockContext mServiceContext;
125 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700126 public DevicePolicyManager dpm;
127 public DevicePolicyManagerServiceTestable dpms;
128
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100129 /*
130 * The CA cert below is the content of cacert.pem as generated by:
131 *
132 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
133 */
134 private static final String TEST_CA =
135 "-----BEGIN CERTIFICATE-----\n" +
136 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
137 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
138 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
139 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
140 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
141 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
142 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
143 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
144 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
145 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
146 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
147 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
148 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
149 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
150 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
151 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
152 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
153 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
154 "wQ==\n" +
155 "-----END CERTIFICATE-----\n";
156
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700157 @Override
158 protected void setUp() throws Exception {
159 super.setUp();
160
161 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100162 mServiceContext = mContext;
163 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
164 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700165 .thenReturn(true);
166
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800167 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100168 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800169
Makoto Onukia52562c2015-10-01 16:12:31 -0700170 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700171
Makoto Onukid932f762015-09-29 16:53:38 -0700172 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
173 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
174 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800175 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700176
Pavel Grafov75c0a892017-05-18 17:28:27 +0100177 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
178 mAdmin1Context.packageName = admin1.getPackageName();
179 mAdmin1Context.applicationInfo = new ApplicationInfo();
180 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
181
Makoto Onukib643fb02015-09-22 15:03:44 -0700182 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700183 }
184
Robin Lee2c68dad2017-03-17 12:50:24 +0000185 @Override
186 protected void tearDown() throws Exception {
187 flushTasks();
188 super.tearDown();
189 }
190
Makoto Onukia52562c2015-10-01 16:12:31 -0700191 private void initializeDpms() {
192 // Need clearCallingIdentity() to pass permission checks.
193 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100194 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700195
Pavel Grafov75c0a892017-05-18 17:28:27 +0100196 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
197 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
198 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700199
Pavel Grafov75c0a892017-05-18 17:28:27 +0100200 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700201
Pavel Grafov75c0a892017-05-18 17:28:27 +0100202 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700203 }
204
Makoto Onukib643fb02015-09-22 15:03:44 -0700205 private void setUpUserManager() {
206 // Emulate UserManager.set/getApplicationRestriction().
207 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
208
209 // UM.setApplicationRestrictions() will save to appRestrictions.
210 doAnswer(new Answer<Void>() {
211 @Override
212 public Void answer(InvocationOnMock invocation) throws Throwable {
213 String pkg = (String) invocation.getArguments()[0];
214 Bundle bundle = (Bundle) invocation.getArguments()[1];
215 UserHandle user = (UserHandle) invocation.getArguments()[2];
216
217 appRestrictions.put(Pair.create(pkg, user), bundle);
218
219 return null;
220 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100221 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100222 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700223
224 // UM.getApplicationRestrictions() will read from appRestrictions.
225 doAnswer(new Answer<Bundle>() {
226 @Override
227 public Bundle answer(InvocationOnMock invocation) throws Throwable {
228 String pkg = (String) invocation.getArguments()[0];
229 UserHandle user = (UserHandle) invocation.getArguments()[1];
230
231 return appRestrictions.get(Pair.create(pkg, user));
232 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100233 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700234 anyString(), any(UserHandle.class));
235
Makoto Onukid932f762015-09-29 16:53:38 -0700236 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100237 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700238 }
239
240 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100241 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700242
Pavel Grafov75c0a892017-05-18 17:28:27 +0100243 mServiceContext.binder.callingUid =
244 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
245 runAsCaller(mServiceContext, dpms, dpm -> {
246 // PO needs to be a DA.
247 dpm.setActiveAdmin(admin, /*replace=*/ false);
248 // Fire!
249 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
250 // Check
251 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
252 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700253
Pavel Grafov75c0a892017-05-18 17:28:27 +0100254 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700255 }
256
257 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100258 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700259 .thenReturn(false);
260
261 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100262 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700263
264 // If the device has no DPMS feature, it shouldn't register the local service.
265 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
266 }
267
268 /**
269 * Caller doesn't have proper permissions.
270 */
271 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700272 // 1. Failure cases.
273
274 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100275 assertExpectException(SecurityException.class, /* messageRegex= */ null,
276 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700277
278 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
279 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100280
281 assertExpectException(SecurityException.class, /* messageRegex= */ null,
282 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700283 }
284
Makoto Onukif76b06a2015-09-22 15:03:44 -0700285 /**
286 * Test for:
287 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800288 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700289 * {@link DevicePolicyManager#isAdminActive}
290 * {@link DevicePolicyManager#isAdminActiveAsUser}
291 * {@link DevicePolicyManager#getActiveAdmins}
292 * {@link DevicePolicyManager#getActiveAdminsAsUser}
293 */
294 public void testSetActiveAdmin() throws Exception {
295 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700296 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
297
Makoto Onukif76b06a2015-09-22 15:03:44 -0700298 // 2. Call the API.
299 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700300
301 // 3. Verify internal calls.
302
303 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700304 verify(mContext.spiedContext).sendBroadcastAsUser(
305 MockUtils.checkIntentAction(
306 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
307 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
308 verify(mContext.spiedContext).sendBroadcastAsUser(
309 MockUtils.checkIntentAction(
310 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700311 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
312
Pavel Grafov75c0a892017-05-18 17:28:27 +0100313 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700314 eq(admin1.getPackageName()),
315 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
316 eq(PackageManager.DONT_KILL_APP),
317 eq(DpmMockContext.CALLER_USER_HANDLE),
318 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700319
320 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700321
322 // Make sure it's active admin1.
323 assertTrue(dpm.isAdminActive(admin1));
324 assertFalse(dpm.isAdminActive(admin2));
325 assertFalse(dpm.isAdminActive(admin3));
326
327 // But not admin1 for a different user.
328
329 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
330 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
331 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
332
333 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
334 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
335
336 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
337
338 // Next, add one more admin.
339 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700340 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
341 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700342
343 dpm.setActiveAdmin(admin2, /* replace =*/ false);
344
345 // Now we have two admins.
346 assertTrue(dpm.isAdminActive(admin1));
347 assertTrue(dpm.isAdminActive(admin2));
348 assertFalse(dpm.isAdminActive(admin3));
349
350 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
351 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100352 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700353 eq(admin1.getPackageName()),
354 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
355 eq(PackageManager.DONT_KILL_APP),
356 eq(DpmMockContext.CALLER_USER_HANDLE),
357 anyString());
358
359 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100360 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
361 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700362
363 // 5. Add the same admin1 again with replace, which should succeed.
364 dpm.setActiveAdmin(admin1, /* replace =*/ true);
365
366 // TODO make sure it's replaced.
367
368 // 6. Test getActiveAdmins()
369 List<ComponentName> admins = dpm.getActiveAdmins();
370 assertEquals(2, admins.size());
371 assertEquals(admin1, admins.get(0));
372 assertEquals(admin2, admins.get(1));
373
374 // Another user has no admins.
375 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
376
377 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
378 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
379
380 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
381 }
382
Makoto Onukid932f762015-09-29 16:53:38 -0700383 public void testSetActiveAdmin_multiUsers() throws Exception {
384
385 final int ANOTHER_USER_ID = 100;
386 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
387
Pavel Grafov75c0a892017-05-18 17:28:27 +0100388 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700389
390 // Set up pacakge manager for the other user.
391 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700392
393 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
394
395 dpm.setActiveAdmin(admin1, /* replace =*/ false);
396
397 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
398 dpm.setActiveAdmin(admin2, /* replace =*/ false);
399
400
401 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
402 assertTrue(dpm.isAdminActive(admin1));
403 assertFalse(dpm.isAdminActive(admin2));
404
405 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
406 assertFalse(dpm.isAdminActive(admin1));
407 assertTrue(dpm.isAdminActive(admin2));
408 }
409
Makoto Onukif76b06a2015-09-22 15:03:44 -0700410 /**
411 * Test for:
412 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800413 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700414 */
415 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
416 // 1. Make sure the caller has proper permissions.
417 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
418
419 dpm.setActiveAdmin(admin1, /* replace =*/ false);
420 assertTrue(dpm.isAdminActive(admin1));
421
422 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100423 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
424 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700425 }
426
427 /**
428 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800429 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
430 * BIND_DEVICE_ADMIN.
431 */
432 public void testSetActiveAdmin_permissionCheck() throws Exception {
433 // 1. Make sure the caller has proper permissions.
434 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
435
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100436 assertExpectException(IllegalArgumentException.class,
437 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
438 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800439 assertFalse(dpm.isAdminActive(adminNoPerm));
440
441 // Change the target API level to MNC. Now it can be set as DA.
442 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
443 VERSION_CODES.M);
444 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
445 assertTrue(dpm.isAdminActive(adminNoPerm));
446
447 // TODO Test the "load from the file" case where DA will still be loaded even without
448 // BIND_DEVICE_ADMIN and target API is N.
449 }
450
451 /**
452 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700453 * {@link DevicePolicyManager#removeActiveAdmin}
454 */
455 public void testRemoveActiveAdmin_SecurityException() {
456 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
457
458 // Add admin.
459
460 dpm.setActiveAdmin(admin1, /* replace =*/ false);
461
462 assertTrue(dpm.isAdminActive(admin1));
463
464 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
465
466 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100467 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
468 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700469
470 // Try to remove active admin with a different caller userid should fail too, without
471 // having MANAGE_DEVICE_ADMINS.
472 mContext.callerPermissions.clear();
473
Makoto Onukid932f762015-09-29 16:53:38 -0700474 // Change the caller, and call into DPMS directly with a different user-id.
475
Makoto Onukif76b06a2015-09-22 15:03:44 -0700476 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100477 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
478 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700479 }
480
481 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800482 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
483 * (because we can't send the remove broadcast).
484 */
485 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
486 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
487
488 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
489
490 // Add admin.
491
492 dpm.setActiveAdmin(admin1, /* replace =*/ false);
493
494 assertTrue(dpm.isAdminActive(admin1));
495
496 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
497
498 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100499 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800500 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100501 assertExpectException(IllegalStateException.class,
502 /* messageRegex= */ "User must be running and unlocked",
503 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800504
505 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
506
507 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100508 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800509 .thenReturn(true);
510
511 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700512 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800513 }
514
515 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700516 * Test for:
517 * {@link DevicePolicyManager#removeActiveAdmin}
518 */
Makoto Onukid932f762015-09-29 16:53:38 -0700519 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700520 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
521
522 // Add admin1.
523
524 dpm.setActiveAdmin(admin1, /* replace =*/ false);
525
526 assertTrue(dpm.isAdminActive(admin1));
527 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
528
529 // Different user, but should work, because caller has proper permissions.
530 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700531
532 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700533 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700534
535 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700536 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700537
538 // TODO DO Still can't be removed in this case.
539 }
540
541 /**
542 * Test for:
543 * {@link DevicePolicyManager#removeActiveAdmin}
544 */
545 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
546 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
547 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
548
549 // Add admin1.
550
551 dpm.setActiveAdmin(admin1, /* replace =*/ false);
552
553 assertTrue(dpm.isAdminActive(admin1));
554 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
555
556 // Broadcast from saveSettingsLocked().
557 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
558 MockUtils.checkIntentAction(
559 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
560 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
561
562 // Remove. No permissions, but same user, so it'll work.
563 mContext.callerPermissions.clear();
564 dpm.removeActiveAdmin(admin1);
565
Makoto Onukif76b06a2015-09-22 15:03:44 -0700566 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
567 MockUtils.checkIntentAction(
568 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
569 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
570 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700571 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700572 eq(dpms.mHandler),
573 eq(Activity.RESULT_OK),
574 isNull(String.class),
575 isNull(Bundle.class));
576
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700577 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700578
579 // Again broadcast from saveSettingsLocked().
580 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
581 MockUtils.checkIntentAction(
582 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
583 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
584
585 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700586 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700587
588 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000589 * Test for: @{link DevicePolicyManager#setActivePasswordState}
590 *
591 * Validates that when the password for a user changes, the notification broadcast intent
592 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
593 * addition to ones in the original user.
594 */
595 public void testSetActivePasswordState_sendToProfiles() throws Exception {
596 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
597
598 final int MANAGED_PROFILE_USER_ID = 78;
599 final int MANAGED_PROFILE_ADMIN_UID =
600 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
601
602 // Setup device owner.
603 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
604 mContext.packageName = admin1.getPackageName();
605 setupDeviceOwner();
606
607 // Add a managed profile belonging to the system user.
608 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
609
610 // Change the parent user's password.
611 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
612
613 // Both the device owner and the managed profile owner should receive this broadcast.
614 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
615 intent.setComponent(admin1);
616 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
617
618 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
619 MockUtils.checkIntent(intent),
620 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
621 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
622 MockUtils.checkIntent(intent),
623 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
624 }
625
626 /**
627 * Test for: @{link DevicePolicyManager#setActivePasswordState}
628 *
629 * Validates that when the password for a managed profile changes, the notification broadcast
630 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
631 * its parent.
632 */
633 public void testSetActivePasswordState_notSentToParent() throws Exception {
634 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
635
636 final int MANAGED_PROFILE_USER_ID = 78;
637 final int MANAGED_PROFILE_ADMIN_UID =
638 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
639
640 // Setup device owner.
641 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
642 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100643 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000644 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
645 setupDeviceOwner();
646
647 // Add a managed profile belonging to the system user.
648 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
649
650 // Change the profile's password.
651 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
652
653 // Both the device owner and the managed profile owner should receive this broadcast.
654 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
655 intent.setComponent(admin1);
656 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
657
658 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
659 MockUtils.checkIntent(intent),
660 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
661 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
662 MockUtils.checkIntent(intent),
663 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
664 }
665 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000666 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700667 */
668 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000669 setDeviceOwner();
670
671 // Try to set a profile owner on the same user, which should fail.
672 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
673 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100674 assertExpectException(IllegalStateException.class,
675 /* messageRegex= */ "already has a device owner",
676 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000677
678 // DO admin can't be deactivated.
679 dpm.removeActiveAdmin(admin1);
680 assertTrue(dpm.isAdminActive(admin1));
681
682 // TODO Test getDeviceOwnerName() too. To do so, we need to change
683 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
684 }
685
686 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700687 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800688 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700689 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
690 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
691
Makoto Onukid932f762015-09-29 16:53:38 -0700692 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700693 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
694
Makoto Onukid932f762015-09-29 16:53:38 -0700695 // Make sure admin1 is installed on system user.
696 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700697
Makoto Onukic8a5a552015-11-19 14:29:12 -0800698 // Check various get APIs.
699 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
700
Makoto Onukib643fb02015-09-22 15:03:44 -0700701 // DO needs to be an DA.
702 dpm.setActiveAdmin(admin1, /* replace =*/ false);
703
704 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700705 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700706
Makoto Onukic8a5a552015-11-19 14:29:12 -0800707 // getDeviceOwnerComponent should return the admin1 component.
708 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
709 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
710
711 // Check various get APIs.
712 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
713
714 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
715 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
716 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
717 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
718
719 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
720
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000721 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100722 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000723 eq(admin1.getPackageName()));
724
Makoto Onukib643fb02015-09-22 15:03:44 -0700725 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100726 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700727 eq(UserHandle.USER_SYSTEM), eq(false));
728
729 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
730 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
731 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
732
Makoto Onukic8a5a552015-11-19 14:29:12 -0800733 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700734 }
735
Makoto Onukic8a5a552015-11-19 14:29:12 -0800736 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
737 final int origCallingUser = mContext.binder.callingUid;
738 final List origPermissions = new ArrayList(mContext.callerPermissions);
739 mContext.callerPermissions.clear();
740
741 mContext.callerPermissions.add(permission.MANAGE_USERS);
742
743 mContext.binder.callingUid = Process.SYSTEM_UID;
744
745 // TODO Test getDeviceOwnerName() too. To do so, we need to change
746 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
747 if (hasDeviceOwner) {
748 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
749 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
750 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
751
752 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
753 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
754 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
755 } else {
756 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
757 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
758 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
759
760 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
761 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
762 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
763 }
764
765 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
766 if (hasDeviceOwner) {
767 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
768 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
769 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
770
771 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
772 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
773 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
774 } else {
775 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
776 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
777 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
778
779 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
780 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
781 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
782 }
783
784 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
785 // Still with MANAGE_USERS.
786 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
787 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
788 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
789
790 if (hasDeviceOwner) {
791 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
792 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
793 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
794 } else {
795 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
796 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
797 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
798 }
799
800 mContext.binder.callingUid = Process.SYSTEM_UID;
801 mContext.callerPermissions.remove(permission.MANAGE_USERS);
802 // System can still call "OnAnyUser" without MANAGE_USERS.
803 if (hasDeviceOwner) {
804 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
805 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
806 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
807
808 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
809 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
810 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
811 } else {
812 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
813 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
814 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
815
816 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
817 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
818 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
819 }
820
821 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
822 // Still no MANAGE_USERS.
823 if (hasDeviceOwner) {
824 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
825 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
826 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
827 } else {
828 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
829 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
830 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
831 }
832
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100833 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
834 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
835 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
836 dpm::getDeviceOwnerComponentOnAnyUser);
837 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
838 dpm::getDeviceOwnerUserId);
839 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
840 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800841
842 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
843 // Still no MANAGE_USERS.
844 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
845 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
846 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
847
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100848 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
849 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
850 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
851 dpm::getDeviceOwnerComponentOnAnyUser);
852 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
853 dpm::getDeviceOwnerUserId);
854 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
855 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800856
857 // Restore.
858 mContext.binder.callingUid = origCallingUser;
859 mContext.callerPermissions.addAll(origPermissions);
860 }
861
862
Makoto Onukib643fb02015-09-22 15:03:44 -0700863 /**
864 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
865 */
866 public void testSetDeviceOwner_noSuchPackage() {
867 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800868 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700869 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
870 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
871
872 // Call from a process on the system user.
873 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
874
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100875 assertExpectException(IllegalArgumentException.class,
876 /* messageRegex= */ "Invalid component",
877 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -0700878 }
879
880 public void testSetDeviceOwner_failures() throws Exception {
881 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
882 }
883
Makoto Onukia52562c2015-10-01 16:12:31 -0700884 public void testClearDeviceOwner() throws Exception {
885 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800886 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700887 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
888 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
889
890 // Set admin1 as a DA to the secondary user.
891 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
892
893 dpm.setActiveAdmin(admin1, /* replace =*/ false);
894
895 // Set admin 1 as the DO to the system user.
896
897 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
898 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
899 dpm.setActiveAdmin(admin1, /* replace =*/ false);
900 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
901
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000902 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100903 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000904 eq(admin1.getPackageName()));
905
Makoto Onukic8a5a552015-11-19 14:29:12 -0800906 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700907
Makoto Onuki90b89652016-01-28 14:44:18 -0800908 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100909 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000910 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800911
912 assertTrue(dpm.isAdminActive(admin1));
913 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
914
Makoto Onukia52562c2015-10-01 16:12:31 -0700915 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100916 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -0700917
918 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100919 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
920 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800921
922 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100923 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100924 assertExpectException(IllegalStateException.class,
925 /* messageRegex= */ "User must be running and unlocked",
926 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800927
Pavel Grafov75c0a892017-05-18 17:28:27 +0100928 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
929 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700930 dpm.clearDeviceOwnerApp(admin1.getPackageName());
931
932 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800933 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700934
Pavel Grafov75c0a892017-05-18 17:28:27 +0100935 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000936 eq(false),
937 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
938
Pavel Grafov75c0a892017-05-18 17:28:27 +0100939 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -0800940 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100941 eq(null),
942 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800943
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700944 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100945
946 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
947 // and once for clearing it.
948 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
949 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
950 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700951 // TODO Check other calls.
952 }
953
954 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
955 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800956 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700957 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
958 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
959
960 // Set admin1 as a DA to the secondary user.
961 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
962
963 dpm.setActiveAdmin(admin1, /* replace =*/ false);
964
965 // Set admin 1 as the DO to the system user.
966
967 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
968 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
969 dpm.setActiveAdmin(admin1, /* replace =*/ false);
970 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
971
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000972 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100973 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000974 eq(admin1.getPackageName()));
975
Makoto Onukic8a5a552015-11-19 14:29:12 -0800976 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700977
978 // Now call clear from the secondary user, which should throw.
979 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
980
981 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100982 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700983 eq(admin1.getPackageName()),
984 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100985 assertExpectException(SecurityException.class,
986 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
987 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -0700988
Makoto Onukic8a5a552015-11-19 14:29:12 -0800989 // DO shouldn't be removed.
990 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700991 }
992
Makoto Onukib643fb02015-09-22 15:03:44 -0700993 public void testSetProfileOwner() throws Exception {
994 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700995
Makoto Onuki90b89652016-01-28 14:44:18 -0800996 // PO admin can't be deactivated.
997 dpm.removeActiveAdmin(admin1);
998 assertTrue(dpm.isAdminActive(admin1));
999
Makoto Onuki803d6752015-10-30 12:58:39 -07001000 // Try setting DO on the same user, which should fail.
1001 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001002 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1003 runAsCaller(mServiceContext, dpms, dpm -> {
1004 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001005 assertExpectException(IllegalStateException.class,
1006 /* messageRegex= */ "already has a profile owner",
1007 () -> dpm.setDeviceOwner(admin2, "owner-name",
1008 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001009 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001010 }
1011
Makoto Onuki90b89652016-01-28 14:44:18 -08001012 public void testClearProfileOwner() throws Exception {
1013 setAsProfileOwner(admin1);
1014
1015 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1016
1017 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1018 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1019
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001020 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001021 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001022 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001023 assertExpectException(IllegalStateException.class,
1024 /* messageRegex= */ "User must be running and unlocked",
1025 () -> dpm.clearProfileOwner(admin1));
1026
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001027 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001028 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001029 dpm.clearProfileOwner(admin1);
1030
1031 // Check
1032 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001033 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001034 }
1035
Makoto Onukib643fb02015-09-22 15:03:44 -07001036 public void testSetProfileOwner_failures() throws Exception {
1037 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1038 }
1039
Makoto Onukia52562c2015-10-01 16:12:31 -07001040 public void testGetDeviceOwnerAdminLocked() throws Exception {
1041 checkDeviceOwnerWithMultipleDeviceAdmins();
1042 }
1043
1044 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1045 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1046 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1047 // make sure it gets the right component from the right user.
1048
1049 final int ANOTHER_USER_ID = 100;
1050 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1051
Pavel Grafov75c0a892017-05-18 17:28:27 +01001052 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001053
1054 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001055 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001056 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1057 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1058
1059 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1060
Pavel Grafov75c0a892017-05-18 17:28:27 +01001061 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001062
Makoto Onukia52562c2015-10-01 16:12:31 -07001063 // Make sure the admin packge is installed to each user.
1064 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1065 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1066
1067 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1068 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1069
1070 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1071
1072
1073 // Set active admins to the users.
1074 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1075 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1076
1077 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1078 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1079
1080 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1081
1082 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001083 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001084 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1085
Makoto Onukic8a5a552015-11-19 14:29:12 -08001086 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001087
1088 // Then check getDeviceOwnerAdminLocked().
1089 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1090 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1091 }
1092
1093 /**
1094 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001095 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1096 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001097 *
1098 * We didn't use to persist the DO component class name, but now we do, and the above method
1099 * finds the right component from a package name upon migration.
1100 */
1101 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001102 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001103 checkDeviceOwnerWithMultipleDeviceAdmins();
1104
1105 // Overwrite the device owner setting and clears the clas name.
1106 dpms.mOwners.setDeviceOwner(
1107 new ComponentName(admin2.getPackageName(), ""),
1108 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1109 dpms.mOwners.writeDeviceOwner();
1110
1111 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001112 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001113
1114 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001115 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001116 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001117 initializeDpms();
1118
1119 // Now the DO component name is a full name.
1120 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1121 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001122 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001123 }
1124
Makoto Onukib643fb02015-09-22 15:03:44 -07001125 public void testSetGetApplicationRestriction() {
1126 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001127 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001128
1129 {
1130 Bundle rest = new Bundle();
1131 rest.putString("KEY_STRING", "Foo1");
1132 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1133 }
1134
1135 {
1136 Bundle rest = new Bundle();
1137 rest.putString("KEY_STRING", "Foo2");
1138 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1139 }
1140
1141 {
1142 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1143 assertNotNull(returned);
1144 assertEquals(returned.size(), 1);
1145 assertEquals(returned.get("KEY_STRING"), "Foo1");
1146 }
1147
1148 {
1149 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1150 assertNotNull(returned);
1151 assertEquals(returned.size(), 1);
1152 assertEquals(returned.get("KEY_STRING"), "Foo2");
1153 }
1154
1155 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1156 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1157 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001158
Edman Anjosf9946772016-11-28 16:35:15 +01001159 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001160 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1161 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001162 *
1163 * @param packageName the name of the package to be setup
1164 * @param appId the application ID to be given to the package
1165 * @return the UID of the package as known by the mock package manager
1166 */
1167 private int setupPackageInPackageManager(final String packageName, final int appId)
1168 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001169 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001170 ApplicationInfo.FLAG_HAS_CODE);
1171 }
1172
1173 /**
1174 * Setup a package in the package manager mock. Useful for faking installed applications.
1175 *
1176 * @param packageName the name of the package to be setup
1177 * @param userId the user id where the package will be "installed"
1178 * @param appId the application ID to be given to the package
1179 * @param flags flags to set in the ApplicationInfo for this package
1180 * @return the UID of the package as known by the mock package manager
1181 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001182 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1183 int flags) throws Exception {
1184 final int uid = UserHandle.getUid(userId, appId);
1185 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001186 final PackageInfo pi = new PackageInfo();
1187 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001188 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001189 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001190 eq(packageName),
1191 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001192 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001193 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001194 eq(packageName),
1195 anyInt(),
1196 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001197 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001198 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001199 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001200 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001201 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001202 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001203 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001204 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001205 return uid;
1206 }
1207
Robin Lee7f5c91c2017-02-08 21:27:02 +00001208 public void testCertificateDisclosure() throws Exception {
1209 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1210 final UserHandle user = UserHandle.of(userId);
1211
1212 mContext.applicationInfo = new ApplicationInfo();
1213 mContext.callerPermissions.add(permission.MANAGE_USERS);
1214 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001215 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001216 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1217
Robin Leeabaa0692017-02-20 20:54:22 +00001218 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1219 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001220
1221 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1222 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1223
1224 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001225 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001226 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001227 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001228 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001229 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001230 .cancelAsUser(anyString(), anyInt(), eq(user));
1231
1232 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001233 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001234 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001235 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1236 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001237 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001238 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001239 .notifyAsUser(anyString(), anyInt(), argThat(
1240 new BaseMatcher<Notification>() {
1241 @Override
1242 public boolean matches(Object item) {
1243 final Notification noti = (Notification) item;
1244 return TEST_STRING.equals(
1245 noti.extras.getString(Notification.EXTRA_TITLE));
1246 }
1247 @Override
1248 public void describeTo(Description description) {
1249 description.appendText(
1250 "Notification{title=\"" + TEST_STRING + "\"}");
1251 }
1252 }), eq(user));
1253 }
1254
Edman Anjosf9946772016-11-28 16:35:15 +01001255 /**
1256 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1257 * privileges can acually be exercised by a delegate are not covered here.
1258 */
1259 public void testDelegation() throws Exception {
1260 setAsProfileOwner(admin1);
1261
1262 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1263
1264 // Given two packages
1265 final String CERT_DELEGATE = "com.delegate.certs";
1266 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1267 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1268 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1269 20989);
1270
1271 // On delegation
1272 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1273 mContext.packageName = admin1.getPackageName();
1274 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1275 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1276
1277 // DPMS correctly stores and retrieves the delegates
1278 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1279 assertEquals(2, policy.mDelegationMap.size());
1280 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1281 DELEGATION_CERT_INSTALL);
1282 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1283 DELEGATION_CERT_INSTALL);
1284 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1285 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1286 DELEGATION_APP_RESTRICTIONS);
1287 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1288 DELEGATION_APP_RESTRICTIONS);
1289 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1290
1291 // On calling install certificate APIs from an unauthorized process
1292 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1293 mContext.packageName = RESTRICTIONS_DELEGATE;
1294
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001295 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1296 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001297
1298 // On calling install certificate APIs from an authorized process
1299 mContext.binder.callingUid = CERT_DELEGATE_UID;
1300 mContext.packageName = CERT_DELEGATE;
1301
1302 // DPMS executes without a SecurityException
1303 try {
1304 dpm.installCaCert(null, null);
1305 } catch (SecurityException unexpected) {
1306 fail("Threw SecurityException on authorized access");
1307 } catch (NullPointerException expected) {
1308 }
1309
1310 // On removing a delegate
1311 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1312 mContext.packageName = admin1.getPackageName();
1313 dpm.setCertInstallerPackage(admin1, null);
1314
1315 // DPMS does not allow access to ex-delegate
1316 mContext.binder.callingUid = CERT_DELEGATE_UID;
1317 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001318 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1319 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001320
1321 // But still allows access to other existing delegates
1322 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1323 mContext.packageName = RESTRICTIONS_DELEGATE;
1324 try {
1325 dpm.getApplicationRestrictions(null, "pkg");
1326 } catch (SecurityException expected) {
1327 fail("Threw SecurityException on authorized access");
1328 }
1329 }
1330
Esteban Talaverabf60f722015-12-10 16:26:44 +00001331 public void testApplicationRestrictionsManagingApp() throws Exception {
1332 setAsProfileOwner(admin1);
1333
Rubin Xued1928a2016-02-11 17:23:06 +00001334 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001335 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001336 final String nonDelegateExceptionMessageRegex =
1337 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001338 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001339 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1340 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001341
Esteban Talaverabf60f722015-12-10 16:26:44 +00001342 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1343 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001344 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1345 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001346 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001347 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001348 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001349 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1350 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001351
1352 // Check via the profile owner that no restrictions were set.
1353 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001354 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001355 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1356
Rubin Xued1928a2016-02-11 17:23:06 +00001357 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001358 assertExpectException(PackageManager.NameNotFoundException.class,
1359 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1360 () -> dpm.setApplicationRestrictionsManagingPackage(
1361 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001362
Esteban Talaverabf60f722015-12-10 16:26:44 +00001363 // Let appRestrictionsManagerPackage manage app restrictions
1364 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1365 assertEquals(appRestrictionsManagerPackage,
1366 dpm.getApplicationRestrictionsManagingPackage(admin1));
1367
1368 // Now that package should be able to set and retrieve app restrictions.
1369 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001370 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001371 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1372 dpm.setApplicationRestrictions(null, "pkg1", rest);
1373 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1374 assertEquals(1, returned.size(), 1);
1375 assertEquals("Foo1", returned.get("KEY_STRING"));
1376
1377 // The same app running on a separate user shouldn't be able to manage app restrictions.
1378 mContext.binder.callingUid = UserHandle.getUid(
1379 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1380 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001381 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1382 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001383
1384 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1385 // too.
1386 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001387 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001388 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1389 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1390 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1391
1392 // Removing the ability for the package to manage app restrictions.
1393 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1394 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1395 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001396 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001397 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001398 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1399 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001400 }
1401
Makoto Onukia4f11972015-10-01 13:19:58 -07001402 public void testSetUserRestriction_asDo() throws Exception {
1403 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001404 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001405 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1406 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1407
1408 // First, set DO.
1409
1410 // Call from a process on the system user.
1411 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1412
1413 // Make sure admin1 is installed on system user.
1414 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001415
1416 // Call.
1417 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001418 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001419 UserHandle.USER_SYSTEM));
1420
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001421 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001422 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001423 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001424 DpmTestUtils.assertRestrictions(
1425 DpmTestUtils.newRestrictions(defaultRestrictions),
1426 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1427 );
1428 DpmTestUtils.assertRestrictions(
1429 DpmTestUtils.newRestrictions(defaultRestrictions),
1430 dpm.getUserRestrictions(admin1)
1431 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001432 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001433 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001434 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001435 eq(true) /* isDeviceOwner */,
1436 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001437 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001438 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001439
1440 for (String restriction : defaultRestrictions) {
1441 dpm.clearUserRestriction(admin1, restriction);
1442 }
1443
Esteban Talavera548a04b2016-12-20 15:22:30 +00001444 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001445 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001446
1447 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001448 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001450 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1451 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001452 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001453
Makoto Onukia4f11972015-10-01 13:19:58 -07001454 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001455 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001456 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001457 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1458 UserManager.DISALLOW_ADD_USER),
1459 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001460 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001461
Makoto Onuki068c54a2015-10-13 14:34:03 -07001462 DpmTestUtils.assertRestrictions(
1463 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001464 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001465 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1466 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001467 DpmTestUtils.assertRestrictions(
1468 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001469 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001470 dpm.getUserRestrictions(admin1)
1471 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001472
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001473 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001474 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001475 eq(UserHandle.USER_SYSTEM),
1476 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001477 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001478 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001479
Makoto Onuki068c54a2015-10-13 14:34:03 -07001480 DpmTestUtils.assertRestrictions(
1481 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1482 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1483 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001484 DpmTestUtils.assertRestrictions(
1485 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1486 dpm.getUserRestrictions(admin1)
1487 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001488
1489 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001490 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001491 eq(UserHandle.USER_SYSTEM),
1492 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001493 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001494 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001495
Esteban Talavera548a04b2016-12-20 15:22:30 +00001496 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001497
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001498 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1499 // DO sets them, the scope is global.
1500 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001501 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001502 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001503 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001504 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001505 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001506 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1507 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001508 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001509
1510 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1511 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001512 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001513
1514 // More tests.
1515 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001516 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001517 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001518 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1519 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001520 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001521
1522 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001523 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001524 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001525 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001526 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.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001531 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001532 eq(UserHandle.USER_SYSTEM),
1533 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001534 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001535 UserManager.DISALLOW_ADD_USER),
1536 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001537 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001538
1539 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1540 // locally.
1541 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001542 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001543
1544 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1545 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1546 dpm.setCameraDisabled(admin2, true);
1547
Pavel Grafov75c0a892017-05-18 17:28:27 +01001548 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001549 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001550 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001551 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001552 UserManager.DISALLOW_ADD_USER),
1553 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001554 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001555 // TODO Make sure restrictions are written to the file.
1556 }
1557
1558 public void testSetUserRestriction_asPo() {
1559 setAsProfileOwner(admin1);
1560
Makoto Onuki068c54a2015-10-13 14:34:03 -07001561 DpmTestUtils.assertRestrictions(
1562 DpmTestUtils.newRestrictions(),
1563 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1564 .ensureUserRestrictions()
1565 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001566
1567 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001568 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001569 eq(DpmMockContext.CALLER_USER_HANDLE),
1570 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001571 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001572 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001573
Makoto Onukia4f11972015-10-01 13:19:58 -07001574 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001575 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001576 eq(DpmMockContext.CALLER_USER_HANDLE),
1577 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1578 UserManager.DISALLOW_OUTGOING_CALLS),
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 Onukia4f11972015-10-01 13:19:58 -07001581
Makoto Onuki068c54a2015-10-13 14:34:03 -07001582 DpmTestUtils.assertRestrictions(
1583 DpmTestUtils.newRestrictions(
1584 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1585 UserManager.DISALLOW_OUTGOING_CALLS
1586 ),
1587 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1588 .ensureUserRestrictions()
1589 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001590 DpmTestUtils.assertRestrictions(
1591 DpmTestUtils.newRestrictions(
1592 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1593 UserManager.DISALLOW_OUTGOING_CALLS
1594 ),
1595 dpm.getUserRestrictions(admin1)
1596 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001597
1598 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001599 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001600 eq(DpmMockContext.CALLER_USER_HANDLE),
1601 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001602 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001603 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001604
1605 DpmTestUtils.assertRestrictions(
1606 DpmTestUtils.newRestrictions(
1607 UserManager.DISALLOW_OUTGOING_CALLS
1608 ),
1609 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1610 .ensureUserRestrictions()
1611 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001612 DpmTestUtils.assertRestrictions(
1613 DpmTestUtils.newRestrictions(
1614 UserManager.DISALLOW_OUTGOING_CALLS
1615 ),
1616 dpm.getUserRestrictions(admin1)
1617 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001618
1619 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001620 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001621 eq(DpmMockContext.CALLER_USER_HANDLE),
1622 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001623 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001624 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001625
Makoto Onuki068c54a2015-10-13 14:34:03 -07001626 DpmTestUtils.assertRestrictions(
1627 DpmTestUtils.newRestrictions(),
1628 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1629 .ensureUserRestrictions()
1630 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001631 DpmTestUtils.assertRestrictions(
1632 DpmTestUtils.newRestrictions(),
1633 dpm.getUserRestrictions(admin1)
1634 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001635
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001636 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1637 // though when DO sets them they'll be applied globally.
1638 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001639 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001640 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001641 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001642 eq(DpmMockContext.CALLER_USER_HANDLE),
1643 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1644 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001645 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001646 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001647
1648 dpm.setCameraDisabled(admin1, true);
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),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001651 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001652 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001653 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001654 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001655
Makoto Onukia4f11972015-10-01 13:19:58 -07001656 // TODO Make sure restrictions are written to the file.
1657 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001658
Esteban Talavera548a04b2016-12-20 15:22:30 +00001659
1660 public void testDefaultEnabledUserRestrictions() throws Exception {
1661 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1662 mContext.callerPermissions.add(permission.MANAGE_USERS);
1663 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1664 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1665
1666 // First, set DO.
1667
1668 // Call from a process on the system user.
1669 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1670
1671 // Make sure admin1 is installed on system user.
1672 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1673
1674 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1675 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1676 UserHandle.USER_SYSTEM));
1677
1678 // Check that the user restrictions that are enabled by default are set. Then unset them.
1679 String[] defaultRestrictions = UserRestrictionsUtils
1680 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1681 assertTrue(defaultRestrictions.length > 0);
1682 DpmTestUtils.assertRestrictions(
1683 DpmTestUtils.newRestrictions(defaultRestrictions),
1684 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1685 );
1686 DpmTestUtils.assertRestrictions(
1687 DpmTestUtils.newRestrictions(defaultRestrictions),
1688 dpm.getUserRestrictions(admin1)
1689 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001690 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001691 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001692 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001693 eq(true) /* isDeviceOwner */,
1694 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001695 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001696 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001697
1698 for (String restriction : defaultRestrictions) {
1699 dpm.clearUserRestriction(admin1, restriction);
1700 }
1701
1702 assertNoDeviceOwnerRestrictions();
1703
1704 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001705 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001706 initializeDpms();
1707 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1708 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1709
1710 assertNoDeviceOwnerRestrictions();
1711
1712 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1713 // is set as it wasn't enabled during setDeviceOwner.
1714 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1715 assertFalse(UserRestrictionsUtils
1716 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1717 UserRestrictionsUtils
1718 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1719 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001720 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001721 initializeDpms();
1722 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1723 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1724
1725 DpmTestUtils.assertRestrictions(
1726 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1727 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1728 );
1729 DpmTestUtils.assertRestrictions(
1730 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1731 dpm.getUserRestrictions(admin1)
1732 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001733 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001734 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001735 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001736 eq(true) /* isDeviceOwner */,
1737 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001738 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001739 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001740
1741 // Remove the restriction.
1742 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1743
1744 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1745 initializeDpms();
1746 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1747 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1748 assertNoDeviceOwnerRestrictions();
1749 } finally {
1750 UserRestrictionsUtils
1751 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1752 }
1753 }
1754
1755 private void assertNoDeviceOwnerRestrictions() {
1756 DpmTestUtils.assertRestrictions(
1757 DpmTestUtils.newRestrictions(),
1758 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1759 );
1760 DpmTestUtils.assertRestrictions(
1761 DpmTestUtils.newRestrictions(),
1762 dpm.getUserRestrictions(admin1)
1763 );
1764 }
1765
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001766 public void testGetMacAddress() throws Exception {
1767 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1768 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1769 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1770
1771 // In this test, change the caller user to "system".
1772 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1773
1774 // Make sure admin1 is installed on system user.
1775 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1776
1777 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001778 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1779 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001780
1781 // DO needs to be an DA.
1782 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1783 assertTrue(dpm.isAdminActive(admin1));
1784
1785 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001786 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1787 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001788
1789 // Test 3. Caller has PO, but not DO.
1790 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001791 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1792 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001793
1794 // Remove PO.
1795 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001796 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001797 // Test 4, Caller is DO now.
1798 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1799
1800 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001801 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001802
1803 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001804 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001805 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001806
1807 // 4-3. With a real MAC address.
1808 final WifiInfo wi = new WifiInfo();
1809 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001810 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001811 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001812 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001813
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001814 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001815 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1816 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1817
1818 // In this test, change the caller user to "system".
1819 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1820
1821 // Make sure admin1 is installed on system user.
1822 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1823
1824 // Set admin1 as DA.
1825 dpm.setActiveAdmin(admin1, false);
1826 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001827 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1828 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001829
1830 // Set admin1 as PO.
1831 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001832 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1833 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001834
1835 // Remove PO and add DO.
1836 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001837 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001838 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1839
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001840 // admin1 is DO.
1841 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001842 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001843 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001844 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1845 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001846
1847 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001848 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001849 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001850 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1851 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001852
1853 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001854 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001855 dpm.reboot(admin1);
1856 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001857
1858 public void testSetGetSupportText() {
1859 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1860 dpm.setActiveAdmin(admin1, true);
1861 dpm.setActiveAdmin(admin2, true);
1862 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1863
1864 // Null default support messages.
1865 {
1866 assertNull(dpm.getLongSupportMessage(admin1));
1867 assertNull(dpm.getShortSupportMessage(admin1));
1868 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1869 assertNull(dpm.getShortSupportMessageForUser(admin1,
1870 DpmMockContext.CALLER_USER_HANDLE));
1871 assertNull(dpm.getLongSupportMessageForUser(admin1,
1872 DpmMockContext.CALLER_USER_HANDLE));
1873 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1874 }
1875
1876 // Only system can call the per user versions.
1877 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001878 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1879 () -> dpm.getShortSupportMessageForUser(admin1,
1880 DpmMockContext.CALLER_USER_HANDLE));
1881 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1882 () -> dpm.getLongSupportMessageForUser(admin1,
1883 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00001884 }
1885
1886 // Can't set message for admin in another uid.
1887 {
1888 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001889 assertExpectException(SecurityException.class,
1890 /* messageRegex= */ "is not owned by uid",
1891 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00001892 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1893 }
1894
1895 // Set/Get short returns what it sets and other admins text isn't changed.
1896 {
1897 final String supportText = "Some text to test with.";
1898 dpm.setShortSupportMessage(admin1, supportText);
1899 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1900 assertNull(dpm.getLongSupportMessage(admin1));
1901 assertNull(dpm.getShortSupportMessage(admin2));
1902
1903 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1904 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1905 DpmMockContext.CALLER_USER_HANDLE));
1906 assertNull(dpm.getShortSupportMessageForUser(admin2,
1907 DpmMockContext.CALLER_USER_HANDLE));
1908 assertNull(dpm.getLongSupportMessageForUser(admin1,
1909 DpmMockContext.CALLER_USER_HANDLE));
1910 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1911
1912 dpm.setShortSupportMessage(admin1, null);
1913 assertNull(dpm.getShortSupportMessage(admin1));
1914 }
1915
1916 // Set/Get long returns what it sets and other admins text isn't changed.
1917 {
1918 final String supportText = "Some text to test with.\nWith more text.";
1919 dpm.setLongSupportMessage(admin1, supportText);
1920 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1921 assertNull(dpm.getShortSupportMessage(admin1));
1922 assertNull(dpm.getLongSupportMessage(admin2));
1923
1924 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1925 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1926 DpmMockContext.CALLER_USER_HANDLE));
1927 assertNull(dpm.getLongSupportMessageForUser(admin2,
1928 DpmMockContext.CALLER_USER_HANDLE));
1929 assertNull(dpm.getShortSupportMessageForUser(admin1,
1930 DpmMockContext.CALLER_USER_HANDLE));
1931 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1932
1933 dpm.setLongSupportMessage(admin1, null);
1934 assertNull(dpm.getLongSupportMessage(admin1));
1935 }
1936 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001937
phweiss73145f42017-01-17 19:06:38 +01001938 public void testCreateAdminSupportIntent() throws Exception {
1939 // Setup device owner.
1940 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1941 setupDeviceOwner();
1942
1943 // Nonexisting permission returns null
1944 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
1945 assertNull(intent);
1946
1947 // Existing permission that is not set returns null
1948 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1949 assertNull(intent);
1950
1951 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01001952 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01001953 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1954 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1955 .thenReturn(true);
1956 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1957 assertNull(intent);
1958
1959 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01001960 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01001961 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1962 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1963 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
1964 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1965 assertNotNull(intent);
1966 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
1967 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
1968 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001969 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01001970 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
1971 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1972
1973 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
1974 // user restrictions
1975
1976 // Camera is not disabled
1977 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1978 assertNull(intent);
1979
1980 // Camera is disabled
1981 dpm.setCameraDisabled(admin1, true);
1982 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1983 assertNotNull(intent);
1984 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
1985 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1986
1987 // Screen capture is not disabled
1988 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1989 assertNull(intent);
1990
1991 // Screen capture is disabled
1992 dpm.setScreenCaptureDisabled(admin1, true);
1993 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1994 assertNotNull(intent);
1995 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
1996 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1997
1998 // Same checks for different user
1999 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2000 // Camera should be disabled by device owner
2001 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2002 assertNotNull(intent);
2003 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2004 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2005 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2006 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2007 // ScreenCapture should not be disabled by device owner
2008 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2009 assertNull(intent);
2010 }
2011
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002012 /**
2013 * Test for:
2014 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002015 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002016 * {@link DevicePolicyManager#isAffiliatedUser}
2017 */
2018 public void testUserAffiliation() throws Exception {
2019 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2020 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2021 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2022
2023 // Check that the system user is unaffiliated.
2024 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2025 assertFalse(dpm.isAffiliatedUser());
2026
2027 // Set a device owner on the system user. Check that the system user becomes affiliated.
2028 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2029 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2030 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2031 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002032 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002033
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002034 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002035 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2036 setAsProfileOwner(admin2);
2037 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002038 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002039
2040 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2041 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002042 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002043 userAffiliationIds.add("red");
2044 userAffiliationIds.add("green");
2045 userAffiliationIds.add("blue");
2046 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002047 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002048 assertFalse(dpm.isAffiliatedUser());
2049
2050 // Have the device owner specify a set of affiliation ids that do not intersect with those
2051 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002052 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002053 deviceAffiliationIds.add("cyan");
2054 deviceAffiliationIds.add("yellow");
2055 deviceAffiliationIds.add("magenta");
2056 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2057 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002058 MoreAsserts.assertContentsInAnyOrder(
2059 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002060 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2061 assertFalse(dpm.isAffiliatedUser());
2062
2063 // Have the profile owner specify a set of affiliation ids that intersect with those
2064 // specified by the device owner. Check that the test user becomes affiliated.
2065 userAffiliationIds.add("yellow");
2066 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002067 MoreAsserts.assertContentsInAnyOrder(
2068 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002069 assertTrue(dpm.isAffiliatedUser());
2070
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002071 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002072 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002073 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002074 assertFalse(dpm.isAffiliatedUser());
2075
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002076 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2077 dpm.setAffiliationIds(admin2, userAffiliationIds);
2078 assertTrue(dpm.isAffiliatedUser());
2079 dpm.clearProfileOwner(admin2);
2080 assertFalse(dpm.isAffiliatedUser());
2081
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002082 // Check that the system user remains affiliated.
2083 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2084 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002085
2086 // Clear the device owner - the user becomes unaffiliated.
2087 clearDeviceOwner();
2088 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002089 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002090
2091 public void testGetUserProvisioningState_defaultResult() {
2092 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2093 }
2094
2095 public void testSetUserProvisioningState_permission() throws Exception {
2096 setupProfileOwner();
2097 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2098
2099 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2100 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2101 }
2102
2103 public void testSetUserProvisioningState_unprivileged() throws Exception {
2104 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002105 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2106 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2107 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002108 }
2109
2110 public void testSetUserProvisioningState_noManagement() {
2111 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002112 assertExpectException(IllegalStateException.class,
2113 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2114 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2115 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002116 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2117 }
2118
2119 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2120 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2121 setupDeviceOwner();
2122 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2123
2124 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2125 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2126 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2127 }
2128
2129 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2130 throws Exception {
2131 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2132 setupDeviceOwner();
2133 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2134
2135 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2136 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2137 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2138 }
2139
2140 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2141 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2142 setupDeviceOwner();
2143 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2144
2145 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2146 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2147 }
2148
2149 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2150 throws Exception {
2151 setupProfileOwner();
2152 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2153
2154 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2155 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2156 DevicePolicyManager.STATE_USER_UNMANAGED);
2157 }
2158
2159 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2160 throws Exception {
2161 setupProfileOwner();
2162 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2163
2164 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2165 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2166 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2167 }
2168
2169 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2170 setupProfileOwner();
2171 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2172
2173 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2174 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2175 }
2176
2177 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2178 setupProfileOwner();
2179 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2180
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002181 assertExpectException(IllegalStateException.class,
2182 /* messageRegex= */ "Cannot move to user provisioning state",
2183 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2184 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2185 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002186 }
2187
2188 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2189 throws Exception {
2190 setupProfileOwner();
2191 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2192
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002193 assertExpectException(IllegalStateException.class,
2194 /* messageRegex= */ "Cannot move to user provisioning state",
2195 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2196 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2197 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002198 }
2199
2200 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2201 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2202 for (int state : states) {
2203 dpm.setUserProvisioningState(state, userId);
2204 assertEquals(state, dpm.getUserProvisioningState());
2205 }
2206 }
2207
2208 private void setupProfileOwner() throws Exception {
2209 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2210
2211 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2212 dpm.setActiveAdmin(admin1, false);
2213 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2214
2215 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2216 }
2217
2218 private void setupDeviceOwner() throws Exception {
2219 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2220
2221 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2222 dpm.setActiveAdmin(admin1, false);
2223 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2224
2225 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2226 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002227
2228 public void testSetMaximumTimeToLock() {
2229 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2230
2231 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2232 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2233
Pavel Grafov75c0a892017-05-18 17:28:27 +01002234 reset(getServices().powerManagerInternal);
2235 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002236
2237 dpm.setMaximumTimeToLock(admin1, 0);
2238 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002239 reset(getServices().powerManagerInternal);
2240 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002241
2242 dpm.setMaximumTimeToLock(admin1, 1);
2243 verifyScreenTimeoutCall(1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002244 reset(getServices().powerManagerInternal);
2245 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002246
2247 dpm.setMaximumTimeToLock(admin2, 10);
2248 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002249 reset(getServices().powerManagerInternal);
2250 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002251
2252 dpm.setMaximumTimeToLock(admin1, 5);
2253 verifyScreenTimeoutCall(5, 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, 4);
2258 verifyScreenTimeoutCall(4, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002259 reset(getServices().powerManagerInternal);
2260 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002261
2262 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002263 reset(getServices().powerManagerInternal);
2264 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002265
2266 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2267 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002268 reset(getServices().powerManagerInternal);
2269 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002270
2271 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2272 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002273 reset(getServices().powerManagerInternal);
2274 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002275
2276 dpm.setMaximumTimeToLock(admin2, 10);
2277 verifyScreenTimeoutCall(10, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002278 reset(getServices().powerManagerInternal);
2279 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002280
2281 // There's no restriction; shold be set to MAX.
2282 dpm.setMaximumTimeToLock(admin2, 0);
2283 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2284 }
2285
Michal Karpinski943aabd2016-10-06 11:09:25 +01002286 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2287 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2288 setupDeviceOwner();
2289 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2290
Michal Karpinskid084ca52017-01-18 15:54:18 +00002291 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2292 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2293 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2294 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2295 - ONE_MINUTE;
2296
2297 // verify that the minimum timeout cannot be modified on user builds (system property is
2298 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002299 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002300
2301 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2302 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2303 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2304
Pavel Grafov75c0a892017-05-18 17:28:27 +01002305 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002306
2307 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002308 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002309
2310 // Always return the default (second arg) when getting system property for long type
Pavel Grafov75c0a892017-05-18 17:28:27 +01002311 when(getServices().systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2312 invocation -> invocation.getArguments()[1]
Michal Karpinskid084ca52017-01-18 15:54:18 +00002313 );
2314
2315 // reset to default (0 means the admin is not participating, so default should be returned)
2316 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002317
2318 // aggregation should be the default if unset by any admin
2319 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2320 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2321
2322 // admin not participating by default
2323 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2324
2325 //clamping from the top
2326 dpm.setRequiredStrongAuthTimeout(admin1,
2327 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2328 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2329 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2330 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2331 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2332
Michal Karpinskid084ca52017-01-18 15:54:18 +00002333 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002334 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2335 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2336 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2337 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2338
2339 // clamping from the bottom
2340 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2341 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2342 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2343
Michal Karpinskid084ca52017-01-18 15:54:18 +00002344 // values within range
2345 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2346 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2347 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2348
2349 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2350 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2351 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002352
2353 // reset to default
2354 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2355 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2356 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2357 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2358
2359 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002360 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2361 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002362 }
2363
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002364 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2365 boolean shouldStayOnWhilePluggedInBeCleared) {
2366 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002367 verify(getServices().powerManagerInternal, times(0))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002368 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2369 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002370 verify(getServices().powerManagerInternal, times(1))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002371 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2372 }
2373 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2374 // UnfinishedVerificationException.
2375 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002376
Esteban Talavera01576862016-12-15 11:16:44 +00002377 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002378 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002379 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002380 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002381 .thenReturn(false);
2382 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002383 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2384 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002385 .thenReturn(true);
2386 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2387
2388 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002389 }
Victor Chang3e794af2016-03-04 13:48:17 +00002390
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002391 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2392 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002393 mContext.packageName = admin1.getPackageName();
2394 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002395 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2396 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2397 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2398 false);
2399 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2400 }
2401
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002402 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2403 setup_DeviceAdminFeatureOff();
2404 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2405 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2406 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2407 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2408 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2409 assertCheckProvisioningPreCondition(
2410 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2411 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2412 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2413 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2414 }
2415
Esteban Talavera01576862016-12-15 11:16:44 +00002416 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002417 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002418 .thenReturn(false);
2419 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002420 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2421 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002422 .thenReturn(true);
2423 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2424
2425 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002426 }
Victor Chang3e794af2016-03-04 13:48:17 +00002427
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002428 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2429 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002430 mContext.packageName = admin1.getPackageName();
2431 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002432 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2433 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2434 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2435 false);
2436 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2437
2438 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002439 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002440 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2441 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2442 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2443 true);
2444 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2445 }
2446
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002447 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2448 setup_ManagedProfileFeatureOff();
2449 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2450 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2451 DevicePolicyManager.CODE_OK);
2452 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2453 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2454 assertCheckProvisioningPreCondition(
2455 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2456 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2457 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2458 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2459
2460 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002461 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002462 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2463 DevicePolicyManager.CODE_OK);
2464 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2465 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2466 assertCheckProvisioningPreCondition(
2467 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2468 DevicePolicyManager.CODE_OK);
2469 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2470 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2471 }
2472
Esteban Talavera01576862016-12-15 11:16:44 +00002473 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002474 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002475 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002476 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2477 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002478 .thenReturn(true);
2479 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2480
2481 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002482 }
Victor Chang3e794af2016-03-04 13:48:17 +00002483
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002484 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2485 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002486 mContext.packageName = admin1.getPackageName();
2487 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002488 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2489 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2490 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2491 false /* because of non-split user */);
2492 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2493 false /* because of non-split user */);
2494 }
2495
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002496 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002497 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002498 setup_nonSplitUser_firstBoot_primaryUser();
2499 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2500 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2501 DevicePolicyManager.CODE_OK);
2502 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2503 DevicePolicyManager.CODE_OK);
2504 assertCheckProvisioningPreCondition(
2505 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2506 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2507 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2508 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2509 }
2510
Esteban Talavera01576862016-12-15 11:16:44 +00002511 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002512 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002513 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002514 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2515 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002516 .thenReturn(true);
2517 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2518
2519 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002520 }
Victor Chang3e794af2016-03-04 13:48:17 +00002521
Nicolas Prevot45d29072017-01-18 16:11:19 +00002522 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2523 setDeviceOwner();
2524 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2525 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2526 }
2527
2528 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2529 setup_nonSplitUser_withDo_primaryUser();
2530 final int MANAGED_PROFILE_USER_ID = 18;
2531 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2532 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002533 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002534 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002535 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002536 true)).thenReturn(true);
2537 }
2538
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002539 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2540 throws Exception {
2541 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002542 mContext.packageName = admin1.getPackageName();
2543 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002544 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2545 false/* because of completed device setup */);
2546 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2547 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2548 false/* because of non-split user */);
2549 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2550 false/* because of non-split user */);
2551 }
2552
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002553 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2554 throws Exception {
2555 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2556 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2557 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2558 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2559 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2560 DevicePolicyManager.CODE_OK);
2561 assertCheckProvisioningPreCondition(
2562 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2563 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2564 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2565 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2566 }
2567
Nicolas Prevot45d29072017-01-18 16:11:19 +00002568 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2569 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002570 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002571 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2572
2573 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2574 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002575 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002576
2577 // COMP mode is allowed.
2578 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2579 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002580 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002581
Nicolas Prevot45d29072017-01-18 16:11:19 +00002582 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002583 assertCheckProvisioningPreCondition(
2584 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002585 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002586 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002587 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2588 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2589 }
Esteban Talavera01576862016-12-15 11:16:44 +00002590
Nicolas Prevot45d29072017-01-18 16:11:19 +00002591 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2592 setup_nonSplitUser_withDo_primaryUser();
2593 mContext.packageName = admin1.getPackageName();
2594 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2595 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2596 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002597 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002598 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2599 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2600 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002601 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002602 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2603 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2604 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2605 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2606 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002607 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002608 assertCheckProvisioningPreCondition(
2609 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002610 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002611 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002612 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2613 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2614 }
Esteban Talavera01576862016-12-15 11:16:44 +00002615
Nicolas Prevot45d29072017-01-18 16:11:19 +00002616 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2617 throws Exception {
2618 setup_nonSplitUser_withDo_primaryUser();
2619 mContext.packageName = admin1.getPackageName();
2620 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002621 // The DO should not be allowed to initiate provisioning if the restriction is set by
2622 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002623 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002624 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2625 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2626 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002627 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002628 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2629 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2630 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2631 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2632 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002633 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2634
2635 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002636 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002637 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002638 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002639 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2640 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2641 }
2642
2643 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2644 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2645 mContext.packageName = admin1.getPackageName();
2646 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2647
2648 // We can delete the managed profile to create a new one, so provisioning is allowed.
2649 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2650 DevicePolicyManager.CODE_OK);
2651 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2652 assertCheckProvisioningPreCondition(
2653 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2654 DpmMockContext.ANOTHER_PACKAGE_NAME,
2655 DevicePolicyManager.CODE_OK);
2656 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2657 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2658 }
2659
2660 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2661 throws Exception {
2662 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2663 mContext.packageName = admin1.getPackageName();
2664 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002665 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002666 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2667 eq(UserHandle.SYSTEM)))
2668 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002669 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002670 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2671 eq(UserHandle.SYSTEM)))
2672 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002673
2674 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002675 assertCheckProvisioningPreCondition(
2676 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2677 DpmMockContext.ANOTHER_PACKAGE_NAME,
2678 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2679 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2680 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002681
2682 // But the device owner can still do it because it has set the restriction itself.
2683 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2684 DevicePolicyManager.CODE_OK);
2685 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002686 }
2687
2688 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002689 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002690 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002691 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2692 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002693 .thenReturn(false);
2694 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2695
2696 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002697 }
Victor Chang3e794af2016-03-04 13:48:17 +00002698
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002699 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2700 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002701 mContext.packageName = admin1.getPackageName();
2702 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002703 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2704 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2705 false /* because canAddMoreManagedProfiles returns false */);
2706 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2707 true);
2708 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2709 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002710 }
2711
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002712 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2713 throws Exception {
2714 setup_splitUser_firstBoot_systemUser();
2715 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2716 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2717 DevicePolicyManager.CODE_OK);
2718 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002719 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002720 assertCheckProvisioningPreCondition(
2721 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2722 DevicePolicyManager.CODE_OK);
2723 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2724 DevicePolicyManager.CODE_SYSTEM_USER);
2725 }
2726
Esteban Talavera01576862016-12-15 11:16:44 +00002727 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002728 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002729 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002730 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2731 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002732 .thenReturn(false);
2733 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2734
2735 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002736 }
Victor Chang3e794af2016-03-04 13:48:17 +00002737
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002738 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2739 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002740 mContext.packageName = admin1.getPackageName();
2741 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002742 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2743 true/* it's undefined behavior. Can be changed into false in the future */);
2744 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2745 false /* because canAddMoreManagedProfiles returns false */);
2746 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2747 true/* it's undefined behavior. Can be changed into false in the future */);
2748 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2749 false/* because calling uid is system user */);
2750 }
2751
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002752 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2753 throws Exception {
2754 setup_splitUser_afterDeviceSetup_systemUser();
2755 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2756 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2757 DevicePolicyManager.CODE_OK);
2758 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002759 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002760 assertCheckProvisioningPreCondition(
2761 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2762 DevicePolicyManager.CODE_OK);
2763 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2764 DevicePolicyManager.CODE_SYSTEM_USER);
2765 }
2766
Esteban Talavera01576862016-12-15 11:16:44 +00002767 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002768 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002769 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002770 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2771 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002772 true)).thenReturn(true);
2773 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2774
2775 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002776 }
Victor Chang3e794af2016-03-04 13:48:17 +00002777
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002778 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2779 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002780 mContext.packageName = admin1.getPackageName();
2781 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002782 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2784 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2785 true);
2786 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002787 }
2788
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002789 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002790 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002791 setup_splitUser_firstBoot_primaryUser();
2792 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2794 DevicePolicyManager.CODE_OK);
2795 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2796 DevicePolicyManager.CODE_OK);
2797 assertCheckProvisioningPreCondition(
2798 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2799 DevicePolicyManager.CODE_OK);
2800 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2801 DevicePolicyManager.CODE_OK);
2802 }
2803
Esteban Talavera01576862016-12-15 11:16:44 +00002804 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002805 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002806 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002807 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2808 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002809 true)).thenReturn(true);
2810 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2811
2812 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002813 }
Victor Chang3e794af2016-03-04 13:48:17 +00002814
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002815 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2816 throws Exception {
2817 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002818 mContext.packageName = admin1.getPackageName();
2819 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002820 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2821 true/* it's undefined behavior. Can be changed into false in the future */);
2822 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2823 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2824 true/* it's undefined behavior. Can be changed into false in the future */);
2825 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2826 false/* because user setup completed */);
2827 }
2828
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002829 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002830 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002831 setup_splitUser_afterDeviceSetup_primaryUser();
2832 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2833 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2834 DevicePolicyManager.CODE_OK);
2835 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2836 DevicePolicyManager.CODE_OK);
2837 assertCheckProvisioningPreCondition(
2838 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2839 DevicePolicyManager.CODE_OK);
2840 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2841 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2842 }
2843
Esteban Talavera01576862016-12-15 11:16:44 +00002844 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002845 setDeviceOwner();
2846
Pavel Grafov75c0a892017-05-18 17:28:27 +01002847 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002848 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002849 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2850 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002851 .thenReturn(false);
2852 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2853
2854 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002855 }
Victor Chang3e794af2016-03-04 13:48:17 +00002856
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002857 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2858 throws Exception {
2859 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002860 mContext.packageName = admin1.getPackageName();
2861 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002862 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2863 false /* can't provision managed profile on system user */);
2864 }
2865
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002866 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002867 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002868 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2869 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2870 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2871 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2872 }
2873
2874 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002875 setDeviceOwner();
2876
Pavel Grafov75c0a892017-05-18 17:28:27 +01002877 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002878 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002879 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2880 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002881 true)).thenReturn(true);
2882 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2883
2884 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002885 }
Victor Chang3e794af2016-03-04 13:48:17 +00002886
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002887 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2888 throws Exception {
2889 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002890 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2891 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002892 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2893 }
2894
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002895 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002896 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002897 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2898 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002899
2900 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002901 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2902 DevicePolicyManager.CODE_OK);
2903 }
2904
2905 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002906 setDeviceOwner();
2907
Pavel Grafov75c0a892017-05-18 17:28:27 +01002908 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002909 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002910 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2911 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002912 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2913 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002914 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002915 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002916 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002917 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00002918 true)).thenReturn(true);
2919 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2920
2921 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002922 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002923
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002924 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2925 throws Exception {
2926 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002927 mContext.packageName = admin1.getPackageName();
2928 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002929 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2930 }
2931
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002932 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2933 throws Exception {
2934 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2935 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2936 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2937 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2938 }
2939
2940 public void testCheckProvisioningPreCondition_permission() {
2941 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002942 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2943 () -> dpm.checkProvisioningPreCondition(
2944 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002945 }
2946
Victor Chang3577ed22016-08-25 18:49:26 +01002947 public void testForceUpdateUserSetupComplete_permission() {
2948 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002949 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2950 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01002951 }
2952
2953 public void testForceUpdateUserSetupComplete_systemUser() {
2954 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2955 // GIVEN calling from user 20
2956 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002957 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2958 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01002959 }
2960
2961 public void testForceUpdateUserSetupComplete_userbuild() {
2962 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2963 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2964
2965 final int userId = UserHandle.USER_SYSTEM;
2966 // GIVEN userComplete is false in SettingsProvider
2967 setUserSetupCompleteForUser(false, userId);
2968
2969 // GIVEN userComplete is true in DPM
2970 DevicePolicyManagerService.DevicePolicyData userData =
2971 new DevicePolicyManagerService.DevicePolicyData(userId);
2972 userData.mUserSetupComplete = true;
2973 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2974
2975 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01002976 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01002977
2978 assertTrue(dpms.hasUserSetupCompleted());
2979
2980 dpm.forceUpdateUserSetupComplete();
2981
2982 // THEN the state in dpms is not changed
2983 assertTrue(dpms.hasUserSetupCompleted());
2984 }
2985
2986 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2987 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2988 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2989
2990 final int userId = UserHandle.USER_SYSTEM;
2991 // GIVEN userComplete is false in SettingsProvider
2992 setUserSetupCompleteForUser(false, userId);
2993
2994 // GIVEN userComplete is true in DPM
2995 DevicePolicyManagerService.DevicePolicyData userData =
2996 new DevicePolicyManagerService.DevicePolicyData(userId);
2997 userData.mUserSetupComplete = true;
2998 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2999
3000 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003001 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003002
3003 assertTrue(dpms.hasUserSetupCompleted());
3004
3005 dpm.forceUpdateUserSetupComplete();
3006
3007 // THEN the state in dpms is not changed
3008 assertFalse(dpms.hasUserSetupCompleted());
3009 }
3010
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003011 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003012 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003013 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003014
3015 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3016 runAsCaller(mAdmin1Context, dpms, dpm -> {
3017 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3018 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003019 }
3020
3021 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3022 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3023 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003024
3025 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3026 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003027 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003028 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3029 .thenReturn(true);
3030
3031 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003032 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003033
3034 // Enabling logging should not change the timestamp.
3035 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003036 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003037 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003038 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003039 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003040 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003041
3042 // Retrieving the logs should update the timestamp.
3043 final long beforeRetrieval = System.currentTimeMillis();
3044 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003045 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003046 final long afterRetrieval = System.currentTimeMillis();
3047 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3048 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3049
3050 // Retrieving the pre-boot logs should update the timestamp.
3051 Thread.sleep(2);
3052 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003053 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003054 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3055
3056 // Checking the timestamp again should not change it.
3057 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003058 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003059
3060 // Retrieving the logs again should update the timestamp.
3061 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003062 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003063 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3064
3065 // Disabling logging should not change the timestamp.
3066 Thread.sleep(2);
3067 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003068 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003069
3070 // Restarting the DPMS should not lose the timestamp.
3071 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003072 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003073
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003074 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3075 mContext.binder.callingUid = 1234567;
3076 mContext.callerPermissions.add(permission.MANAGE_USERS);
3077 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3078 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3079
3080 // System can retrieve the timestamp.
3081 mContext.binder.clearCallingIdentity();
3082 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3083
3084 // Removing the device owner should clear the timestamp.
3085 clearDeviceOwner();
3086 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003087 }
3088
3089 public void testGetLastBugReportRequestTime() throws Exception {
3090 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3091 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003092
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003093 mContext.packageName = admin1.getPackageName();
3094 mContext.applicationInfo = new ApplicationInfo();
3095 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3096 .thenReturn(Color.WHITE);
3097 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3098 anyObject())).thenReturn(Color.WHITE);
3099
Esteban Talaverad36dd152016-12-15 08:51:45 +00003100 // 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);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003103
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003104 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003105 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003106
3107 // Requesting a bug report should update the timestamp.
3108 final long beforeRequest = System.currentTimeMillis();
3109 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003110 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003111 final long afterRequest = System.currentTimeMillis();
3112 assertTrue(bugReportRequestTime >= beforeRequest);
3113 assertTrue(bugReportRequestTime <= afterRequest);
3114
3115 // Checking the timestamp again should not change it.
3116 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003117 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003118
3119 // Restarting the DPMS should not lose the timestamp.
3120 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003121 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003122
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003123 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3124 mContext.binder.callingUid = 1234567;
3125 mContext.callerPermissions.add(permission.MANAGE_USERS);
3126 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3127 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3128
3129 // System can retrieve the timestamp.
3130 mContext.binder.clearCallingIdentity();
3131 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3132
3133 // Removing the device owner should clear the timestamp.
3134 clearDeviceOwner();
3135 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003136 }
3137
3138 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3139 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3140 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003141 mContext.packageName = admin1.getPackageName();
3142 mContext.applicationInfo = new ApplicationInfo();
3143 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3144 .thenReturn(Color.WHITE);
3145 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3146 anyObject())).thenReturn(Color.WHITE);
3147
3148 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3149 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003150 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
3151 when(getServices().iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003152 .thenReturn(true);
3153
3154 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003155 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003156
3157 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3158 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003159 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003160
3161 // Enabling logging should not change the timestamp.
3162 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003163 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003164
3165 // Retrieving the logs should update the timestamp.
3166 final long beforeRetrieval = System.currentTimeMillis();
3167 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003168 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003169 final long afterRetrieval = System.currentTimeMillis();
3170 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3171 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3172
3173 // Checking the timestamp again should not change it.
3174 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003175 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003176
3177 // Retrieving the logs again should update the timestamp.
3178 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003179 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003180 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3181
3182 // Disabling logging should not change the timestamp.
3183 Thread.sleep(2);
3184 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003185 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003186
3187 // Restarting the DPMS should not lose the timestamp.
3188 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003189 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3190
3191 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3192 mContext.binder.callingUid = 1234567;
3193 mContext.callerPermissions.add(permission.MANAGE_USERS);
3194 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3195 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3196
3197 // System can retrieve the timestamp.
3198 mContext.binder.clearCallingIdentity();
3199 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3200
3201 // Removing the device owner should clear the timestamp.
3202 clearDeviceOwner();
3203 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003204 }
3205
Tony Mak2f26b792016-11-28 17:54:51 +00003206 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3207 // Setup device owner.
3208 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3209 setupDeviceOwner();
3210
3211 // Only device owner is setup, the result list should be empty.
3212 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3213 MoreAsserts.assertEmpty(targetUsers);
3214
3215 // Setup a managed profile managed by the same admin.
3216 final int MANAGED_PROFILE_USER_ID = 15;
3217 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3218 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3219
3220 // Add a secondary user, it should never talk with.
3221 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003222 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003223
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003224 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3225 // other.
3226 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3227 MoreAsserts.assertEmpty(targetUsers);
3228
3229 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3230 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3231 MoreAsserts.assertEmpty(targetUsers);
3232
3233 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003234 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003235 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3236 dpm.setAffiliationIds(admin1, userAffiliationIds);
3237
3238 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3239 dpm.setAffiliationIds(admin1, userAffiliationIds);
3240
Tony Mak2f26b792016-11-28 17:54:51 +00003241 // Calling from device owner admin, the result list should just contain the managed
3242 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003243 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003244 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3245 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3246
3247 // Calling from managed profile admin, the result list should just contain the system
3248 // user id.
3249 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3250 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3251 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003252
3253 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003254 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003255
3256 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3257 // to each other.
3258 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3259 MoreAsserts.assertEmpty(targetUsers);
3260
3261 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3262 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3263 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003264 }
3265
3266 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3267 // Setup a device owner.
3268 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3269 setupDeviceOwner();
3270
3271 // Set up a managed profile managed by different package.
3272 final int MANAGED_PROFILE_USER_ID = 15;
3273 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3274 final ComponentName adminDifferentPackage =
3275 new ComponentName("another.package", "whatever.class");
3276 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3277
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003278 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003279 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003280 dpm.setAffiliationIds(admin1, userAffiliationIds);
3281
3282 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3283 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3284
Tony Mak2f26b792016-11-28 17:54:51 +00003285 // Calling from device owner admin, we should get zero bind device admin target users as
3286 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003287 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003288 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3289 MoreAsserts.assertEmpty(targetUsers);
3290
3291 // Calling from managed profile admin, we should still get zero target users for the same
3292 // reason.
3293 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3294 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3295 MoreAsserts.assertEmpty(targetUsers);
3296 }
3297
Esteban Talaverabdcada92017-02-01 14:20:06 +00003298 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3299 // Setup a device owner.
3300 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3301 setupDeviceOwner();
3302 // Lock task packages are updated when loading user data.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003303 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003304 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3305
3306 // Set up a managed profile managed by different package (package name shouldn't matter)
3307 final int MANAGED_PROFILE_USER_ID = 15;
3308 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3309 final ComponentName adminDifferentPackage =
3310 new ComponentName("another.package", "whatever.class");
3311 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003312 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003313 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3314
3315 // The DO can still set lock task packages
3316 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3317 final String[] doPackages = {"doPackage1", "doPackage2"};
3318 dpm.setLockTaskPackages(admin1, doPackages);
3319 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3320 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3321 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003322 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003323 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3324
3325 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3326 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3327 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003328 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3329 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3330 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3331 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003332 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3333
3334 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003335 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003336 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3337 dpm.setAffiliationIds(admin1, userAffiliationIds);
3338
3339 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3340 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3341
3342 // Now the managed profile can set lock task packages.
3343 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3344 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3345 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3346 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003347 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003348 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3349
3350 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003351 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003352 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3353 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003354 verify(getServices().iactivityManager, times(2))
Esteban Talaverabdcada92017-02-01 14:20:06 +00003355 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3356
3357 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3358 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3359 }
3360
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003361 public void testIsDeviceManaged() throws Exception {
3362 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3363 setupDeviceOwner();
3364
3365 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3366 // find out that the device has a device owner.
3367 assertTrue(dpm.isDeviceManaged());
3368 mContext.binder.callingUid = 1234567;
3369 mContext.callerPermissions.add(permission.MANAGE_USERS);
3370 assertTrue(dpm.isDeviceManaged());
3371 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3372 mContext.binder.clearCallingIdentity();
3373 assertTrue(dpm.isDeviceManaged());
3374
3375 clearDeviceOwner();
3376
3377 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3378 // not have a device owner.
3379 mContext.binder.callingUid = 1234567;
3380 mContext.callerPermissions.add(permission.MANAGE_USERS);
3381 assertFalse(dpm.isDeviceManaged());
3382 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3383 mContext.binder.clearCallingIdentity();
3384 assertFalse(dpm.isDeviceManaged());
3385 }
3386
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003387 public void testDeviceOwnerOrganizationName() throws Exception {
3388 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3389 setupDeviceOwner();
3390
3391 dpm.setOrganizationName(admin1, "organization");
3392
3393 // Device owner can retrieve organization managing the device.
3394 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3395
3396 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3397 mContext.binder.callingUid = 1234567;
3398 mContext.callerPermissions.add(permission.MANAGE_USERS);
3399 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3400 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3401
3402 // System can retrieve organization managing the device.
3403 mContext.binder.clearCallingIdentity();
3404 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3405
3406 // Removing the device owner clears the organization managing the device.
3407 clearDeviceOwner();
3408 assertNull(dpm.getDeviceOwnerOrganizationName());
3409 }
3410
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003411 public void testWipeDataManagedProfile() throws Exception {
3412 final int MANAGED_PROFILE_USER_ID = 15;
3413 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3414 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3415 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3416
3417 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003418 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003419 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3420
3421 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003422 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003423 MANAGED_PROFILE_USER_ID);
3424 }
3425
3426 public void testWipeDataManagedProfileDisallowed() throws Exception {
3427 final int MANAGED_PROFILE_USER_ID = 15;
3428 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3429 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3430
3431 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003432 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003433 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3434
Pavel Grafov75c0a892017-05-18 17:28:27 +01003435 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003436 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3437 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3438 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3439 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003440 // The PO is not allowed to remove the profile if the user restriction was set on the
3441 // profile by the system
3442 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3443 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003444 }
3445
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003446 public void testWipeDataDeviceOwner() throws Exception {
3447 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003448 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003449 UserManager.DISALLOW_FACTORY_RESET,
3450 UserHandle.SYSTEM))
3451 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3452
3453 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003454 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003455 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3456 /*wipeEuicc=*/ eq(false));
3457 }
3458
3459 public void testWipeEuiccDataEnabled() throws Exception {
3460 setDeviceOwner();
3461 when(getServices().userManager.getUserRestrictionSource(
3462 UserManager.DISALLOW_FACTORY_RESET,
3463 UserHandle.SYSTEM))
3464 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3465
3466 dpm.wipeData(WIPE_EUICC);
3467 verify(getServices().recoverySystem).rebootWipeUserData(
3468 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3469 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003470 }
3471
3472 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3473 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003474 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003475 UserManager.DISALLOW_FACTORY_RESET,
3476 UserHandle.SYSTEM))
3477 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003478 // The DO is not allowed to wipe the device if the user restriction was set
3479 // by the system
3480 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3481 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003482 }
3483
3484 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3485 final int MANAGED_PROFILE_USER_ID = 15;
3486 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3487 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3488
3489 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003490 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003491 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3492
Pavel Grafov75c0a892017-05-18 17:28:27 +01003493 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003494 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3495 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3496 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3497
3498 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3499 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3500
3501 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3502 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3503 // Failed password attempts on the parent user are taken into account, as there isn't a
3504 // separate work challenge.
3505 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3506 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3507 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3508
3509 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3510 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003511 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003512 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003513 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003514 }
3515
3516 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3517 throws Exception {
3518 final int MANAGED_PROFILE_USER_ID = 15;
3519 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3520 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3521
3522 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003523 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003524 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3525
Pavel Grafov75c0a892017-05-18 17:28:27 +01003526 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003527 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3528 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3529 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3530
3531 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3532 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3533
3534 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3535 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3536 // Failed password attempts on the parent user are taken into account, as there isn't a
3537 // separate work challenge.
3538 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3539 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3540 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3541
3542 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3543 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003544 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003545 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003546 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003547 }
3548
3549 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3550 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003551 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003552 UserManager.DISALLOW_FACTORY_RESET,
3553 UserHandle.SYSTEM))
3554 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3555
3556 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3557
3558 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3559 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3560 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3561 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3562 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3563
3564 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3565 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003566 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003567 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3568 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003569 }
3570
3571 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3572 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003573 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003574 UserManager.DISALLOW_FACTORY_RESET,
3575 UserHandle.SYSTEM))
3576 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3577
3578 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3579
3580 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3581 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3582 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3583 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3584 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3585
3586 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003587 verifyZeroInteractions(getServices().recoverySystem);
3588 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003589 .removeUserEvenWhenDisallowed(anyInt());
3590 }
3591
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003592 public void testGetPermissionGrantState() throws Exception {
3593 final String permission = "some.permission";
3594 final String app1 = "com.example.app1";
3595 final String app2 = "com.example.app2";
3596
Pavel Grafov75c0a892017-05-18 17:28:27 +01003597 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003598 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003599 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003600 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003601 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003602 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3603 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003604 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003605 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003606 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003607 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003608 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003609 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3610
3611 // System can retrieve permission grant state.
3612 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003613 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003614 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3615 dpm.getPermissionGrantState(null, app1, permission));
3616 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3617 dpm.getPermissionGrantState(null, app2, permission));
3618
3619 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003620 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3621 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003622 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3623 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003624
3625 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003626 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3627 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003628 setAsProfileOwner(admin1);
3629 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3630 dpm.getPermissionGrantState(admin1, app1, permission));
3631 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3632 dpm.getPermissionGrantState(admin1, app2, permission));
3633 }
3634
Rubin Xuaab7a412016-12-30 21:13:29 +00003635 public void testResetPasswordWithToken() throws Exception {
3636 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3637 setupDeviceOwner();
3638 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003639 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3640 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3641
Rubin Xuaab7a412016-12-30 21:13:29 +00003642 // test adding a token
3643 final byte[] token = new byte[32];
3644 final long handle = 123456;
3645 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003646 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003647 .thenReturn(handle);
3648 assertTrue(dpm.setResetPasswordToken(admin1, token));
3649
3650 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003651 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003652 .thenReturn(true);
3653 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3654
3655 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003656 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xuaab7a412016-12-30 21:13:29 +00003657 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3658 eq(UserHandle.USER_SYSTEM)))
3659 .thenReturn(true);
3660 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3661
3662 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003663 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003664 .thenReturn(true);
3665 assertTrue(dpm.clearResetPasswordToken(admin1));
3666 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003667
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003668 public void testIsActivePasswordSufficient() throws Exception {
3669 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3670 mContext.packageName = admin1.getPackageName();
3671 setupDeviceOwner();
3672
3673 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3674 dpm.setPasswordMinimumLength(admin1, 8);
3675 dpm.setPasswordMinimumLetters(admin1, 6);
3676 dpm.setPasswordMinimumLowerCase(admin1, 3);
3677 dpm.setPasswordMinimumUpperCase(admin1, 1);
3678 dpm.setPasswordMinimumNonLetter(admin1, 1);
3679 dpm.setPasswordMinimumNumeric(admin1, 1);
3680 dpm.setPasswordMinimumSymbols(admin1, 0);
3681
3682 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3683 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3684 8, 2,
3685 6, 1,
3686 0, 1);
3687
3688 setActivePasswordState(passwordMetricsNoSymbols);
3689 assertTrue(dpm.isActivePasswordSufficient());
3690
3691 initializeDpms();
3692 reset(mContext.spiedContext);
3693 assertTrue(dpm.isActivePasswordSufficient());
3694
3695 // This call simulates the user entering the password for the first time after a reboot.
3696 // This causes password metrics to be reloaded into memory. Until this happens,
3697 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3698 // even if the DPC changes password requirements so that the password no longer meets the
3699 // requirements. This is a known limitation of the current implementation of
3700 // isActivePasswordSufficient() - see b/34218769.
3701 setActivePasswordState(passwordMetricsNoSymbols);
3702 assertTrue(dpm.isActivePasswordSufficient());
3703
3704 dpm.setPasswordMinimumSymbols(admin1, 1);
3705 // This assertion would fail if we had not called setActivePasswordState() again after
3706 // initializeDpms() - see previous comment.
3707 assertFalse(dpm.isActivePasswordSufficient());
3708
3709 initializeDpms();
3710 reset(mContext.spiedContext);
3711 assertFalse(dpm.isActivePasswordSufficient());
3712
3713 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3714 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3715 7, 2,
3716 5, 1,
3717 1, 2);
3718
3719 setActivePasswordState(passwordMetricsWithSymbols);
3720 assertTrue(dpm.isActivePasswordSufficient());
3721 }
3722
Pavel Grafov75c0a892017-05-18 17:28:27 +01003723 private void setActivePasswordState(PasswordMetrics passwordMetrics)
3724 throws Exception {
3725 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003726 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003727
Pavel Grafov75c0a892017-05-18 17:28:27 +01003728 dpm.setActivePasswordState(passwordMetrics, userHandle);
3729 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003730
Pavel Grafov75c0a892017-05-18 17:28:27 +01003731 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3732 intent.setComponent(admin1);
3733 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3734
3735 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3736 MockUtils.checkIntent(intent),
3737 MockUtils.checkUserHandle(userHandle));
3738
3739 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
3740 // let it finish with system uid, otherwise it will throw and crash.
3741 flushTasks();
3742
3743 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003744 }
3745
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003746 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3747 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3748 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3749 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3750 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3751 DpmMockContext.SYSTEM_UID);
3752 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3753 DpmMockContext.SYSTEM_UID);
3754
3755 // Set up a device owner.
3756 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003757 setupDeviceOwner();
3758
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003759 // First and second user set IMEs manually.
3760 mContext.binder.callingUid = firstUserSystemUid;
3761 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3762 mContext.binder.callingUid = secondUserSystemUid;
3763 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003764
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003765 // Device owner changes IME for first user.
3766 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003767 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003768 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003769 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003770 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003771 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003772 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003773 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3774 mContext.binder.callingUid = firstUserSystemUid;
3775 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3776 mContext.binder.callingUid = secondUserSystemUid;
3777 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003778
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003779 // Second user changes IME manually.
3780 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3781 mContext.binder.callingUid = firstUserSystemUid;
3782 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3783 mContext.binder.callingUid = secondUserSystemUid;
3784 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003785
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003786 // First user changes IME manually.
3787 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3788 mContext.binder.callingUid = firstUserSystemUid;
3789 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3790 mContext.binder.callingUid = secondUserSystemUid;
3791 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003792
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003793 // Device owner changes IME for first user again.
3794 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003795 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003796 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003797 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003798 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003799 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003800 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3801 mContext.binder.callingUid = firstUserSystemUid;
3802 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3803 mContext.binder.callingUid = secondUserSystemUid;
3804 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003805
3806 // Restarting the DPMS should not lose information.
3807 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003808 mContext.binder.callingUid = firstUserSystemUid;
3809 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3810 mContext.binder.callingUid = secondUserSystemUid;
3811 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003812
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003813 // Device owner can find out whether it set the current IME itself.
3814 mContext.binder.callingUid = deviceOwnerUid;
3815 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003816
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003817 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003818 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003819 mContext.binder.callingUid = firstUserSystemUid;
3820 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3821 mContext.binder.callingUid = secondUserSystemUid;
3822 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003823 }
3824
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003825 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3826 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3827 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3828 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3829 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3830 DpmMockContext.SYSTEM_UID);
3831 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3832 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003833
3834 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003835 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003836 setupProfileOwner();
3837
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003838 // First and second user set IMEs manually.
3839 mContext.binder.callingUid = firstUserSystemUid;
3840 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3841 mContext.binder.callingUid = secondUserSystemUid;
3842 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003843
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003844 // Profile owner changes IME for second user.
3845 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003846 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003847 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003848 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003849 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003850 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003851 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003852 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3853 mContext.binder.callingUid = firstUserSystemUid;
3854 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3855 mContext.binder.callingUid = secondUserSystemUid;
3856 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003857
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003858 // First user changes IME manually.
3859 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3860 mContext.binder.callingUid = firstUserSystemUid;
3861 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3862 mContext.binder.callingUid = secondUserSystemUid;
3863 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003864
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003865 // Second user changes IME manually.
3866 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3867 mContext.binder.callingUid = firstUserSystemUid;
3868 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3869 mContext.binder.callingUid = secondUserSystemUid;
3870 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003871
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003872 // Profile owner changes IME for second user again.
3873 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003874 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003875 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003876 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003877 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003878 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003879 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3880 mContext.binder.callingUid = firstUserSystemUid;
3881 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3882 mContext.binder.callingUid = secondUserSystemUid;
3883 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003884
3885 // Restarting the DPMS should not lose information.
3886 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003887 mContext.binder.callingUid = firstUserSystemUid;
3888 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3889 mContext.binder.callingUid = secondUserSystemUid;
3890 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003891
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003892 // Profile owner can find out whether it set the current IME itself.
3893 mContext.binder.callingUid = profileOwnerUid;
3894 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003895
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003896 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003897 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003898 mContext.binder.callingUid = firstUserSystemUid;
3899 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3900 mContext.binder.callingUid = secondUserSystemUid;
3901 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003902 }
Rubin Xuaab7a412016-12-30 21:13:29 +00003903
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003904 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
3905 throws Exception {
3906 // Set up a device owner.
3907 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3908 setupDeviceOwner();
3909 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3910 }
3911
3912 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
3913 throws Exception {
3914 // Set up a profile owner.
3915 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3916 setupProfileOwner();
3917 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3918 }
3919
3920 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
3921 int adminUid) throws Exception {
3922 mContext.binder.callingUid = adminUid;
3923 final int userId = UserHandle.getUserId(adminUid);
3924
3925 final String packageName = "some.package";
3926 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
3927 admin1, Collections.singletonList(packageName)));
3928 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3929
3930 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3931 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
3932
3933 // Attempt to set to empty list (which means no listener is whitelisted)
3934 mContext.binder.callingUid = adminUid;
3935 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01003936 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003937 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3938
3939 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3940 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
3941 }
3942
3943 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
3944 // Set up a managed profile
3945 final int MANAGED_PROFILE_USER_ID = 15;
3946 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3947 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3948 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3949
3950 final String permittedListener = "some.package";
3951 setupPackageInPackageManager(
3952 permittedListener,
3953 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3954 /*appId=*/ 12345, /*flags=*/ 0);
3955
3956 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
3957 admin1, Collections.singletonList(permittedListener)));
3958
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003959 // isNotificationListenerServicePermitted should throw if not called from System.
3960 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3961 () -> dpms.isNotificationListenerServicePermitted(
3962 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003963
3964 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3965 assertTrue(dpms.isNotificationListenerServicePermitted(
3966 permittedListener, MANAGED_PROFILE_USER_ID));
3967 }
3968
3969 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
3970 throws Exception {
3971 // Set up a managed profile
3972 final int MANAGED_PROFILE_USER_ID = 15;
3973 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3974 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3975 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3976
3977 final String permittedListener = "permitted.package";
3978 int appId = 12345;
3979 setupPackageInPackageManager(
3980 permittedListener,
3981 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3982 appId, /*flags=*/ 0);
3983
3984 final String notPermittedListener = "not.permitted.package";
3985 setupPackageInPackageManager(
3986 notPermittedListener,
3987 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3988 ++appId, /*flags=*/ 0);
3989
3990 final String systemListener = "system.package";
3991 setupPackageInPackageManager(
3992 systemListener,
3993 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3994 ++appId, ApplicationInfo.FLAG_SYSTEM);
3995
3996 // By default all packages are allowed
3997 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3998
3999 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4000 assertTrue(dpms.isNotificationListenerServicePermitted(
4001 permittedListener, MANAGED_PROFILE_USER_ID));
4002 assertTrue(dpms.isNotificationListenerServicePermitted(
4003 notPermittedListener, MANAGED_PROFILE_USER_ID));
4004 assertTrue(dpms.isNotificationListenerServicePermitted(
4005 systemListener, MANAGED_PROFILE_USER_ID));
4006
4007 // Setting only one package in the whitelist
4008 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4009 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4010 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004011 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004012 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4013 assertEquals(1, permittedListeners.size());
4014 assertEquals(permittedListener, permittedListeners.get(0));
4015
4016 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4017 assertTrue(dpms.isNotificationListenerServicePermitted(
4018 permittedListener, MANAGED_PROFILE_USER_ID));
4019 assertFalse(dpms.isNotificationListenerServicePermitted(
4020 notPermittedListener, MANAGED_PROFILE_USER_ID));
4021 // System packages are always allowed (even if not in the whitelist)
4022 assertTrue(dpms.isNotificationListenerServicePermitted(
4023 systemListener, MANAGED_PROFILE_USER_ID));
4024
4025 // Setting an empty whitelist - only system listeners allowed
4026 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4027 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004028 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004029 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4030
4031 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4032 assertFalse(dpms.isNotificationListenerServicePermitted(
4033 permittedListener, MANAGED_PROFILE_USER_ID));
4034 assertFalse(dpms.isNotificationListenerServicePermitted(
4035 notPermittedListener, MANAGED_PROFILE_USER_ID));
4036 // System packages are always allowed (even if not in the whitelist)
4037 assertTrue(dpms.isNotificationListenerServicePermitted(
4038 systemListener, MANAGED_PROFILE_USER_ID));
4039
4040 // Setting a null whitelist - all listeners allowed
4041 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4042 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4043 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4044
4045 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4046 assertTrue(dpms.isNotificationListenerServicePermitted(
4047 permittedListener, MANAGED_PROFILE_USER_ID));
4048 assertTrue(dpms.isNotificationListenerServicePermitted(
4049 notPermittedListener, MANAGED_PROFILE_USER_ID));
4050 assertTrue(dpms.isNotificationListenerServicePermitted(
4051 systemListener, MANAGED_PROFILE_USER_ID));
4052 }
4053
4054 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4055 throws Exception {
4056 // Set up a managed profile
4057 final int MANAGED_PROFILE_USER_ID = 15;
4058 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4059 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4060 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4061
4062 final String nonSystemPackage = "non.system.package";
4063 int appId = 12345;
4064 setupPackageInPackageManager(
4065 nonSystemPackage,
4066 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4067 appId, /*flags=*/ 0);
4068
4069 final String systemListener = "system.package";
4070 setupPackageInPackageManager(
4071 systemListener,
4072 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4073 ++appId, ApplicationInfo.FLAG_SYSTEM);
4074
4075 // By default all packages are allowed (for all profiles)
4076 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4077
4078 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4079 assertTrue(dpms.isNotificationListenerServicePermitted(
4080 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4081 assertTrue(dpms.isNotificationListenerServicePermitted(
4082 systemListener, MANAGED_PROFILE_USER_ID));
4083 assertTrue(dpms.isNotificationListenerServicePermitted(
4084 nonSystemPackage, UserHandle.USER_SYSTEM));
4085 assertTrue(dpms.isNotificationListenerServicePermitted(
4086 systemListener, UserHandle.USER_SYSTEM));
4087
4088 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4089 // all allowed in primary profile
4090 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4091 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004092 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004093 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4094
4095 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4096 assertFalse(dpms.isNotificationListenerServicePermitted(
4097 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4098 assertTrue(dpms.isNotificationListenerServicePermitted(
4099 systemListener, MANAGED_PROFILE_USER_ID));
4100 assertTrue(dpms.isNotificationListenerServicePermitted(
4101 nonSystemPackage, UserHandle.USER_SYSTEM));
4102 assertTrue(dpms.isNotificationListenerServicePermitted(
4103 systemListener, UserHandle.USER_SYSTEM));
4104 }
4105
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004106 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004107 mServiceContext.packageName = mRealTestContext.getPackageName();
4108 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4109 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004110 setDeviceOwner();
4111
Pavel Grafov75c0a892017-05-18 17:28:27 +01004112 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004113 }
4114
4115 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004116 mServiceContext.packageName = mRealTestContext.getPackageName();
4117 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4118 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004119 setAsProfileOwner(admin1);
4120
Pavel Grafov75c0a892017-05-18 17:28:27 +01004121 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4122 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004123 }
4124
4125 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004126 mServiceContext.packageName = mRealTestContext.getPackageName();
4127 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4128 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004129 setAsProfileOwner(admin1);
4130
Pavel Grafov75c0a892017-05-18 17:28:27 +01004131 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4132 caller.packageName = "com.example.delegate";
4133 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4134 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004135
Pavel Grafov75c0a892017-05-18 17:28:27 +01004136 // Make caller a delegated cert installer.
4137 runAsCaller(mAdmin1Context, dpms,
4138 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004139
4140 verifyCanGetOwnerInstalledCaCerts(null, caller);
4141 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004142 }
4143
Robin Lee2c68dad2017-03-17 12:50:24 +00004144 private void verifyCanGetOwnerInstalledCaCerts(
4145 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004146 final String alias = "cert";
4147 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004148
4149 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004150 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004151 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4152 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004153 }
4154 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4155
4156 // caller: device admin or delegated certificate installer
4157 callerContext.applicationInfo = new ApplicationInfo();
4158 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4159
4160 // system_server
4161 final DpmMockContext serviceContext = mContext;
4162 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004163 getServices().addPackageContext(callerUser, admin1Context);
4164 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004165
4166 // Install a CA cert.
4167 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004168 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004169 .thenReturn(alias);
4170 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004171 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004172 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004173 });
4174
Pavel Grafov75c0a892017-05-18 17:28:27 +01004175 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4176 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4177 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004178 flushTasks();
4179
Robin Lee2c68dad2017-03-17 12:50:24 +00004180 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4181
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004182 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004183 runAsCaller(admin1Context, dpms, (dpm) -> {
4184 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004185 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004186 ownerInstalledCaCerts.addAll(installedCaCerts);
4187 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004188
4189 // Restarting the DPMS should not lose information.
4190 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004191 runAsCaller(admin1Context, dpms, (dpm) ->
4192 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004193
4194 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004195 runAsCaller(serviceContext, dpms, (dpm) -> {
4196 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004197
Robin Lee2c68dad2017-03-17 12:50:24 +00004198 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004199 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004200 });
4201
Pavel Grafov75c0a892017-05-18 17:28:27 +01004202 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4203 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4204 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004205 flushTasks();
4206
4207 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4208 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004209 runAsCaller(admin1Context, dpms, (dpm) -> {
4210 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4211 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004212 }
4213
Robin Lee2c68dad2017-03-17 12:50:24 +00004214 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4215 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004216 final String alias = "cert";
4217 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004218
4219 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004220 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004221 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4222 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004223 }
4224 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4225
4226 // caller: device admin or delegated certificate installer
4227 callerContext.applicationInfo = new ApplicationInfo();
4228 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4229
4230 // system_server
4231 final DpmMockContext serviceContext = mContext;
4232 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004233 getServices().addPackageContext(callerUser, admin1Context);
4234 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004235
4236 // Install a CA cert as caller
4237 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004238 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004239 .thenReturn(alias);
4240 assertTrue(dpm.installCaCert(callerName, caCert));
4241 });
4242
4243 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004244 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004245 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004246 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4247 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4248 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004249 flushTasks();
4250
Robin Lee2c68dad2017-03-17 12:50:24 +00004251 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004252 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004253
4254 runAsCaller(serviceContext, dpms, (dpm) -> {
4255 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4256 assertNotNull(ownerInstalledCaCerts);
4257 assertTrue(ownerInstalledCaCerts.isEmpty());
4258 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004259 }
4260
Victor Chang3e794af2016-03-04 13:48:17 +00004261 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004262 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004263 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4264 dpms.notifyChangeToContentObserver(
4265 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4266 }
4267
4268 private void assertProvisioningAllowed(String action, boolean expected) {
4269 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4270 dpm.isProvisioningAllowed(action));
4271 }
Tony Mak2f26b792016-11-28 17:54:51 +00004272
Nicolas Prevot45d29072017-01-18 16:11:19 +00004273 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4274 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004275 final String previousPackageName = mContext.packageName;
4276 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004277
4278 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4279 mContext.packageName = packageName;
4280 mMockContext.binder.callingUid = uid;
4281 assertProvisioningAllowed(action, expected);
4282
4283 // Set the previous package name / calling uid to go back to the initial state.
4284 mContext.packageName = previousPackageName;
4285 mMockContext.binder.callingUid = previousUid;
4286 }
4287
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004288 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004289 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4290 }
4291
4292 private void assertCheckProvisioningPreCondition(
4293 String action, String packageName, int provisioningCondition) {
4294 assertEquals("checkProvisioningPreCondition("
4295 + action + ", " + packageName + ") returning unexpected result",
4296 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004297 }
4298
Tony Mak2f26b792016-11-28 17:54:51 +00004299 /**
4300 * Setup a managed profile with the specified admin and its uid.
4301 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4302 * @param adminUid uid of the admin package.
4303 * @param copyFromAdmin package information for {@code admin} will be built based on this
4304 * component's information.
4305 */
4306 private void addManagedProfile(
4307 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4308 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004309 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004310 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4311 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4312 dpm.setActiveAdmin(admin, false, userId);
4313 assertTrue(dpm.setProfileOwner(admin, null, userId));
4314 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4315 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004316
4317 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004318 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004319 */
Robin Leeabaa0692017-02-20 20:54:22 +00004320 private static StringParceledListSlice asSlice(String[] s) {
4321 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004322 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004323
4324 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004325 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4326 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004327
Robin Lee2c68dad2017-03-17 12:50:24 +00004328 // We can't let exceptions happen on the background thread. Throw them here if they happen
4329 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004330 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004331 }
Victor Chang3e794af2016-03-04 13:48:17 +00004332}