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