blob: 73983bd3227d29b02d63eaa717549fbb3fb21148 [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;
Eran Messeri94d56762017-12-21 20:50:54 +000020import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
21import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
22import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
23import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
yinxuf4f9cec2017-06-19 10:28:19 -070024import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010025import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
26import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
27import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
28
Eugene Susla4f8680b2017-08-07 17:25:30 -070029import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010030
Pavel Grafov75c0a892017-05-18 17:28:27 +010031import static org.mockito.Matchers.any;
32import static org.mockito.Matchers.anyInt;
33import static org.mockito.Matchers.anyLong;
34import static org.mockito.Matchers.anyObject;
35import static org.mockito.Matchers.anyString;
36import static org.mockito.Matchers.eq;
37import static org.mockito.Matchers.isNull;
38import static org.mockito.Mockito.atLeast;
39import static org.mockito.Mockito.doAnswer;
40import static org.mockito.Mockito.doReturn;
41import static org.mockito.Mockito.never;
42import static org.mockito.Mockito.nullable;
43import static org.mockito.Mockito.reset;
44import static org.mockito.Mockito.timeout;
45import static org.mockito.Mockito.times;
46import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080047import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010048import static org.mockito.Mockito.verifyZeroInteractions;
49import static org.mockito.Mockito.when;
50import static org.mockito.hamcrest.MockitoHamcrest.argThat;
51
Makoto Onukif76b06a2015-09-22 15:03:44 -070052import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000053import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070054import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000055import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070056import android.app.admin.DeviceAdminReceiver;
57import android.app.admin.DevicePolicyManager;
58import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010059import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070060import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000062import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000063import android.content.pm.ApplicationInfo;
64import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070065import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010066import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000067import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000068import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010069import android.graphics.Color;
70import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080071import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070072import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080073import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070074import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070075import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010076import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080077import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010078import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000079import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000080import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000081import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080082import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000083import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010084import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070085import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070086
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010087import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000088import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000089import com.android.server.LocalServices;
90import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000091import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000092import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000093
Robin Lee7f5c91c2017-02-08 21:27:02 +000094import org.hamcrest.BaseMatcher;
95import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -080096import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -070097import org.mockito.invocation.InvocationOnMock;
98import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070099
arangelov08d534b2018-01-22 15:20:53 +0000100import java.io.File;
101import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800102import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000103import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000104import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700105import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700107import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100108import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000109import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700110
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700112 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000113 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700114 m FrameworksServicesTests &&
115 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000116 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700118 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700119
120 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000121 *
122 * , or:
123 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000125@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100126@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700127public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000128 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
129 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
130 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100131 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800132 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100133 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000134
Pavel Grafov75c0a892017-05-18 17:28:27 +0100135 // TODO replace all instances of this with explicit {@link #mServiceContext}.
136 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700137 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100138
139 private DpmMockContext mServiceContext;
140 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700141 public DevicePolicyManager dpm;
142 public DevicePolicyManagerServiceTestable dpms;
143
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100144 /*
145 * The CA cert below is the content of cacert.pem as generated by:
146 *
147 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
148 */
149 private static final String TEST_CA =
150 "-----BEGIN CERTIFICATE-----\n" +
151 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
152 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
153 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
154 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
155 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
156 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
157 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
158 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
159 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
160 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
161 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
162 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
163 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
164 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
165 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
166 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
167 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
168 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
169 "wQ==\n" +
170 "-----END CERTIFICATE-----\n";
171
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700172 @Override
173 protected void setUp() throws Exception {
174 super.setUp();
175
176 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100177 mServiceContext = mContext;
178 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
179 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700180 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100181 doReturn(Collections.singletonList(new ResolveInfo()))
182 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
183 any(Intent.class),
184 anyInt(),
185 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700186
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800187 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100188 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800189
Makoto Onukia52562c2015-10-01 16:12:31 -0700190 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700191
Sudheer Shanka101c3532018-01-08 16:28:42 -0800192 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800193 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700194 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
195 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
196 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800197 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700198
Pavel Grafov75c0a892017-05-18 17:28:27 +0100199 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
200 mAdmin1Context.packageName = admin1.getPackageName();
201 mAdmin1Context.applicationInfo = new ApplicationInfo();
202 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
203
Makoto Onukib643fb02015-09-22 15:03:44 -0700204 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700205 }
206
arangelov08d534b2018-01-22 15:20:53 +0000207 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
208 return dpms.mTransferOwnershipMetadataManager;
209 }
210
Robin Lee2c68dad2017-03-17 12:50:24 +0000211 @Override
212 protected void tearDown() throws Exception {
213 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000214 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000215 super.tearDown();
216 }
217
Makoto Onukia52562c2015-10-01 16:12:31 -0700218 private void initializeDpms() {
219 // Need clearCallingIdentity() to pass permission checks.
220 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100221 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700222
Pavel Grafov75c0a892017-05-18 17:28:27 +0100223 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
224 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
225 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700226
Pavel Grafov75c0a892017-05-18 17:28:27 +0100227 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700228
Pavel Grafov75c0a892017-05-18 17:28:27 +0100229 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700230 }
231
Makoto Onukib643fb02015-09-22 15:03:44 -0700232 private void setUpUserManager() {
233 // Emulate UserManager.set/getApplicationRestriction().
234 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
235
236 // UM.setApplicationRestrictions() will save to appRestrictions.
237 doAnswer(new Answer<Void>() {
238 @Override
239 public Void answer(InvocationOnMock invocation) throws Throwable {
240 String pkg = (String) invocation.getArguments()[0];
241 Bundle bundle = (Bundle) invocation.getArguments()[1];
242 UserHandle user = (UserHandle) invocation.getArguments()[2];
243
244 appRestrictions.put(Pair.create(pkg, user), bundle);
245
246 return null;
247 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100248 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100249 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700250
251 // UM.getApplicationRestrictions() will read from appRestrictions.
252 doAnswer(new Answer<Bundle>() {
253 @Override
254 public Bundle answer(InvocationOnMock invocation) throws Throwable {
255 String pkg = (String) invocation.getArguments()[0];
256 UserHandle user = (UserHandle) invocation.getArguments()[1];
257
258 return appRestrictions.get(Pair.create(pkg, user));
259 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100260 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700261 anyString(), any(UserHandle.class));
262
Makoto Onukid932f762015-09-29 16:53:38 -0700263 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100264 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700265 }
266
267 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100268 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700269
Pavel Grafov75c0a892017-05-18 17:28:27 +0100270 mServiceContext.binder.callingUid =
271 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
272 runAsCaller(mServiceContext, dpms, dpm -> {
273 // PO needs to be a DA.
274 dpm.setActiveAdmin(admin, /*replace=*/ false);
275 // Fire!
276 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
277 // Check
278 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
279 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700280
Pavel Grafov75c0a892017-05-18 17:28:27 +0100281 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700282 }
283
284 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100285 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700286 .thenReturn(false);
287
288 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100289 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700290
291 // If the device has no DPMS feature, it shouldn't register the local service.
292 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
293 }
294
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800295 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800296 // Device owner in SYSTEM_USER
297 setDeviceOwner();
298 // Profile owner in CALLER_USER_HANDLE
299 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
300 setAsProfileOwner(admin2);
301 // Active admin in CALLER_USER_HANDLE
302 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
303 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
304 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
305 DpmMockContext.CALLER_USER_HANDLE);
306 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
307 DpmMockContext.CALLER_USER_HANDLE));
308
309 initializeDpms();
310
311 // Verify
312 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800313 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800314 eq(UserHandle.USER_SYSTEM));
315 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800316 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800317 adminAnotherPackage.getPackageName()),
318 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800319 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
320 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
321 }
322
323 public void testLoadAdminData_noAdmins() throws Exception {
324 final int ANOTHER_USER_ID = 15;
325 getServices().addUser(ANOTHER_USER_ID, 0);
326
327 initializeDpms();
328
329 // Verify
330 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
331 null, DpmMockContext.CALLER_USER_HANDLE);
332 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
333 null, ANOTHER_USER_ID);
334 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
335 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800336 }
337
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700338 /**
339 * Caller doesn't have proper permissions.
340 */
341 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700342 // 1. Failure cases.
343
344 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100345 assertExpectException(SecurityException.class, /* messageRegex= */ null,
346 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700347
348 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
349 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100350
351 assertExpectException(SecurityException.class, /* messageRegex= */ null,
352 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700353 }
354
Makoto Onukif76b06a2015-09-22 15:03:44 -0700355 /**
356 * Test for:
357 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800358 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700359 * {@link DevicePolicyManager#isAdminActive}
360 * {@link DevicePolicyManager#isAdminActiveAsUser}
361 * {@link DevicePolicyManager#getActiveAdmins}
362 * {@link DevicePolicyManager#getActiveAdminsAsUser}
363 */
364 public void testSetActiveAdmin() throws Exception {
365 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700366 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
367
Makoto Onukif76b06a2015-09-22 15:03:44 -0700368 // 2. Call the API.
369 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700370
371 // 3. Verify internal calls.
372
373 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700374 verify(mContext.spiedContext).sendBroadcastAsUser(
375 MockUtils.checkIntentAction(
376 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
377 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
378 verify(mContext.spiedContext).sendBroadcastAsUser(
379 MockUtils.checkIntentAction(
380 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700381 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
382
Pavel Grafov75c0a892017-05-18 17:28:27 +0100383 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700384 eq(admin1.getPackageName()),
385 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
386 eq(PackageManager.DONT_KILL_APP),
387 eq(DpmMockContext.CALLER_USER_HANDLE),
388 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700389
Sudheer Shanka101c3532018-01-08 16:28:42 -0800390 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
391 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
392
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700393 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700394
395 // Make sure it's active admin1.
396 assertTrue(dpm.isAdminActive(admin1));
397 assertFalse(dpm.isAdminActive(admin2));
398 assertFalse(dpm.isAdminActive(admin3));
399
400 // But not admin1 for a different user.
401
402 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
403 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
404 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
405
406 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
407 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
408
409 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
410
411 // Next, add one more admin.
412 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700413 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700414 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700415
416 dpm.setActiveAdmin(admin2, /* replace =*/ false);
417
418 // Now we have two admins.
419 assertTrue(dpm.isAdminActive(admin1));
420 assertTrue(dpm.isAdminActive(admin2));
421 assertFalse(dpm.isAdminActive(admin3));
422
423 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
424 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100425 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700426 eq(admin1.getPackageName()),
427 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
428 eq(PackageManager.DONT_KILL_APP),
429 eq(DpmMockContext.CALLER_USER_HANDLE),
430 anyString());
431
Sudheer Shanka101c3532018-01-08 16:28:42 -0800432 // times(2) because it was previously called for admin1 which is in the same package
433 // as admin2.
434 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
435 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
436
Makoto Onukif76b06a2015-09-22 15:03:44 -0700437 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100438 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
439 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700440
441 // 5. Add the same admin1 again with replace, which should succeed.
442 dpm.setActiveAdmin(admin1, /* replace =*/ true);
443
444 // TODO make sure it's replaced.
445
446 // 6. Test getActiveAdmins()
447 List<ComponentName> admins = dpm.getActiveAdmins();
448 assertEquals(2, admins.size());
449 assertEquals(admin1, admins.get(0));
450 assertEquals(admin2, admins.get(1));
451
Sudheer Shanka101c3532018-01-08 16:28:42 -0800452 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
453 // replaced
454 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
455
Makoto Onukif76b06a2015-09-22 15:03:44 -0700456 // Another user has no admins.
457 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
458
459 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
460 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
461
462 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
463 }
464
Makoto Onukid932f762015-09-29 16:53:38 -0700465 public void testSetActiveAdmin_multiUsers() throws Exception {
466
467 final int ANOTHER_USER_ID = 100;
468 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
469
Pavel Grafov75c0a892017-05-18 17:28:27 +0100470 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700471
472 // Set up pacakge manager for the other user.
473 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700474
475 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
476
477 dpm.setActiveAdmin(admin1, /* replace =*/ false);
478
479 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
480 dpm.setActiveAdmin(admin2, /* replace =*/ false);
481
482
483 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
484 assertTrue(dpm.isAdminActive(admin1));
485 assertFalse(dpm.isAdminActive(admin2));
486
487 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
488 assertFalse(dpm.isAdminActive(admin1));
489 assertTrue(dpm.isAdminActive(admin2));
490 }
491
Makoto Onukif76b06a2015-09-22 15:03:44 -0700492 /**
493 * Test for:
494 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800495 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700496 */
497 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
498 // 1. Make sure the caller has proper permissions.
499 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
500
501 dpm.setActiveAdmin(admin1, /* replace =*/ false);
502 assertTrue(dpm.isAdminActive(admin1));
503
504 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100505 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
506 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700507 }
508
509 /**
510 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800511 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
512 * BIND_DEVICE_ADMIN.
513 */
514 public void testSetActiveAdmin_permissionCheck() throws Exception {
515 // 1. Make sure the caller has proper permissions.
516 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
517
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100518 assertExpectException(IllegalArgumentException.class,
519 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
520 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800521 assertFalse(dpm.isAdminActive(adminNoPerm));
522
523 // Change the target API level to MNC. Now it can be set as DA.
524 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
525 VERSION_CODES.M);
526 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
527 assertTrue(dpm.isAdminActive(adminNoPerm));
528
529 // TODO Test the "load from the file" case where DA will still be loaded even without
530 // BIND_DEVICE_ADMIN and target API is N.
531 }
532
533 /**
534 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700535 * {@link DevicePolicyManager#removeActiveAdmin}
536 */
537 public void testRemoveActiveAdmin_SecurityException() {
538 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
539
540 // Add admin.
541
542 dpm.setActiveAdmin(admin1, /* replace =*/ false);
543
544 assertTrue(dpm.isAdminActive(admin1));
545
546 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
547
548 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100549 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
550 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700551
552 // Try to remove active admin with a different caller userid should fail too, without
553 // having MANAGE_DEVICE_ADMINS.
554 mContext.callerPermissions.clear();
555
Makoto Onukid932f762015-09-29 16:53:38 -0700556 // Change the caller, and call into DPMS directly with a different user-id.
557
Makoto Onukif76b06a2015-09-22 15:03:44 -0700558 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100559 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
560 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700561 }
562
563 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800564 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
565 * (because we can't send the remove broadcast).
566 */
567 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
568 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
569
570 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
571
572 // Add admin.
573
574 dpm.setActiveAdmin(admin1, /* replace =*/ false);
575
576 assertTrue(dpm.isAdminActive(admin1));
577
578 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
579
580 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100581 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800582 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100583 assertExpectException(IllegalStateException.class,
584 /* messageRegex= */ "User must be running and unlocked",
585 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800586
587 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800588 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
589 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800590
591 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100592 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800593 .thenReturn(true);
594
595 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700596 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800597 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
598 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800599 }
600
601 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700602 * Test for:
603 * {@link DevicePolicyManager#removeActiveAdmin}
604 */
Makoto Onukid932f762015-09-29 16:53:38 -0700605 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700606 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
607
608 // Add admin1.
609
610 dpm.setActiveAdmin(admin1, /* replace =*/ false);
611
612 assertTrue(dpm.isAdminActive(admin1));
613 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
614
615 // Different user, but should work, because caller has proper permissions.
616 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700617
618 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700619 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700620
621 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700622 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800623 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
624 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700625
626 // TODO DO Still can't be removed in this case.
627 }
628
629 /**
630 * Test for:
631 * {@link DevicePolicyManager#removeActiveAdmin}
632 */
633 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
634 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
635 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
636
637 // Add admin1.
638
639 dpm.setActiveAdmin(admin1, /* replace =*/ false);
640
641 assertTrue(dpm.isAdminActive(admin1));
642 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
643
644 // Broadcast from saveSettingsLocked().
645 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
646 MockUtils.checkIntentAction(
647 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
648 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
649
650 // Remove. No permissions, but same user, so it'll work.
651 mContext.callerPermissions.clear();
652 dpm.removeActiveAdmin(admin1);
653
Makoto Onukif76b06a2015-09-22 15:03:44 -0700654 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
655 MockUtils.checkIntentAction(
656 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
657 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
658 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700659 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700660 eq(dpms.mHandler),
661 eq(Activity.RESULT_OK),
662 isNull(String.class),
663 isNull(Bundle.class));
664
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700665 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800666 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
667 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700668
669 // Again broadcast from saveSettingsLocked().
670 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
671 MockUtils.checkIntentAction(
672 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
673 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
674
675 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700676 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700677
Sudheer Shanka101c3532018-01-08 16:28:42 -0800678 public void testRemoveActiveAdmin_multipleAdminsInUser() {
679 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
680 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
681
682 // Add admin1.
683 dpm.setActiveAdmin(admin1, /* replace =*/ false);
684
685 assertTrue(dpm.isAdminActive(admin1));
686 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
687
688 // Add admin2.
689 dpm.setActiveAdmin(admin2, /* replace =*/ false);
690
691 assertTrue(dpm.isAdminActive(admin2));
692 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
693
694 // Broadcast from saveSettingsLocked().
695 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
696 MockUtils.checkIntentAction(
697 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
698 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
699
700 // Remove. No permissions, but same user, so it'll work.
701 mContext.callerPermissions.clear();
702 dpm.removeActiveAdmin(admin1);
703
704 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
705 MockUtils.checkIntentAction(
706 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
707 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
708 isNull(String.class),
709 any(BroadcastReceiver.class),
710 eq(dpms.mHandler),
711 eq(Activity.RESULT_OK),
712 isNull(String.class),
713 isNull(Bundle.class));
714
715 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
716 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800717 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800718 eq(DpmMockContext.CALLER_USER_HANDLE));
719
720 // Again broadcast from saveSettingsLocked().
721 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
722 MockUtils.checkIntentAction(
723 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
724 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
725 }
726
727 /**
728 * Test for:
729 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
730 */
731 public void testForceRemoveActiveAdmin() throws Exception {
732 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
733
734 // Add admin.
735 setupPackageInPackageManager(admin1.getPackageName(),
736 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
737 /* appId= */ 10138,
738 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
739 dpm.setActiveAdmin(admin1, /* replace =*/ false);
740 assertTrue(dpm.isAdminActive(admin1));
741
742 // Calling from a non-shell uid should fail with a SecurityException
743 mContext.binder.callingUid = 123456;
744 assertExpectException(SecurityException.class,
745 /* messageRegex =*/ "Non-shell user attempted to call",
746 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
747
748 mContext.binder.callingUid = Process.SHELL_UID;
749 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
750
751 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
752 // Verify
753 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
754 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
755 null, DpmMockContext.CALLER_USER_HANDLE);
756 }
757
Makoto Onukib643fb02015-09-22 15:03:44 -0700758 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000759 * Test for: @{link DevicePolicyManager#setActivePasswordState}
760 *
761 * Validates that when the password for a user changes, the notification broadcast intent
762 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
763 * addition to ones in the original user.
764 */
765 public void testSetActivePasswordState_sendToProfiles() throws Exception {
766 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
767
768 final int MANAGED_PROFILE_USER_ID = 78;
769 final int MANAGED_PROFILE_ADMIN_UID =
770 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
771
772 // Setup device owner.
773 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
774 mContext.packageName = admin1.getPackageName();
775 setupDeviceOwner();
776
777 // Add a managed profile belonging to the system user.
778 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
779
780 // Change the parent user's password.
781 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
782
783 // Both the device owner and the managed profile owner should receive this broadcast.
784 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
785 intent.setComponent(admin1);
786 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
787
788 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
789 MockUtils.checkIntent(intent),
790 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
791 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
792 MockUtils.checkIntent(intent),
793 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
794 }
795
796 /**
797 * Test for: @{link DevicePolicyManager#setActivePasswordState}
798 *
799 * Validates that when the password for a managed profile changes, the notification broadcast
800 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
801 * its parent.
802 */
803 public void testSetActivePasswordState_notSentToParent() throws Exception {
804 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
805
806 final int MANAGED_PROFILE_USER_ID = 78;
807 final int MANAGED_PROFILE_ADMIN_UID =
808 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
809
810 // Setup device owner.
811 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
812 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100813 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000814 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
815 setupDeviceOwner();
816
817 // Add a managed profile belonging to the system user.
818 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
819
820 // Change the profile's password.
821 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
822
823 // Both the device owner and the managed profile owner should receive this broadcast.
824 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
825 intent.setComponent(admin1);
826 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
827
828 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
829 MockUtils.checkIntent(intent),
830 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
831 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
832 MockUtils.checkIntent(intent),
833 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
834 }
835 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000836 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700837 */
838 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000839 setDeviceOwner();
840
841 // Try to set a profile owner on the same user, which should fail.
842 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
843 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100844 assertExpectException(IllegalStateException.class,
845 /* messageRegex= */ "already has a device owner",
846 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000847
848 // DO admin can't be deactivated.
849 dpm.removeActiveAdmin(admin1);
850 assertTrue(dpm.isAdminActive(admin1));
851
852 // TODO Test getDeviceOwnerName() too. To do so, we need to change
853 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
854 }
855
856 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700857 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800858 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700859 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
860 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
861
Makoto Onukid932f762015-09-29 16:53:38 -0700862 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700863 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
864
Makoto Onukid932f762015-09-29 16:53:38 -0700865 // Make sure admin1 is installed on system user.
866 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700867
Makoto Onukic8a5a552015-11-19 14:29:12 -0800868 // Check various get APIs.
869 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
870
Makoto Onukib643fb02015-09-22 15:03:44 -0700871 // DO needs to be an DA.
872 dpm.setActiveAdmin(admin1, /* replace =*/ false);
873
874 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700875 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700876
Makoto Onukic8a5a552015-11-19 14:29:12 -0800877 // getDeviceOwnerComponent should return the admin1 component.
878 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
879 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
880
881 // Check various get APIs.
882 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
883
884 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
885 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
886 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
887 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
888
889 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
890
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000891 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100892 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000893 eq(admin1.getPackageName()));
894
Makoto Onukib643fb02015-09-22 15:03:44 -0700895 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100896 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700897 eq(UserHandle.USER_SYSTEM), eq(false));
898
899 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
900 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
901 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
902
Makoto Onukic8a5a552015-11-19 14:29:12 -0800903 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700904 }
905
Makoto Onukic8a5a552015-11-19 14:29:12 -0800906 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
907 final int origCallingUser = mContext.binder.callingUid;
908 final List origPermissions = new ArrayList(mContext.callerPermissions);
909 mContext.callerPermissions.clear();
910
911 mContext.callerPermissions.add(permission.MANAGE_USERS);
912
913 mContext.binder.callingUid = Process.SYSTEM_UID;
914
915 // TODO Test getDeviceOwnerName() too. To do so, we need to change
916 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
917 if (hasDeviceOwner) {
918 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
919 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
920 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
921
922 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
923 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
924 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
925 } else {
926 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
927 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
928 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
929
930 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
931 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
932 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
933 }
934
935 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
936 if (hasDeviceOwner) {
937 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
938 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
939 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
940
941 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
942 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
943 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
944 } else {
945 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
946 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
947 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
948
949 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
950 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
951 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
952 }
953
954 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
955 // Still with MANAGE_USERS.
956 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
957 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
958 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
959
960 if (hasDeviceOwner) {
961 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
962 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
963 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
964 } else {
965 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
966 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
967 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
968 }
969
970 mContext.binder.callingUid = Process.SYSTEM_UID;
971 mContext.callerPermissions.remove(permission.MANAGE_USERS);
972 // System can still call "OnAnyUser" without MANAGE_USERS.
973 if (hasDeviceOwner) {
974 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
975 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
976 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
977
978 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
979 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
980 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
981 } else {
982 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
983 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
984 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
985
986 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
987 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
988 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
989 }
990
991 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
992 // Still no MANAGE_USERS.
993 if (hasDeviceOwner) {
994 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
995 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
996 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
997 } else {
998 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
999 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1000 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1001 }
1002
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001003 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1004 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1005 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1006 dpm::getDeviceOwnerComponentOnAnyUser);
1007 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1008 dpm::getDeviceOwnerUserId);
1009 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1010 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001011
1012 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1013 // Still no MANAGE_USERS.
1014 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1015 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1016 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1017
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001018 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1019 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1020 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1021 dpm::getDeviceOwnerComponentOnAnyUser);
1022 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1023 dpm::getDeviceOwnerUserId);
1024 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1025 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001026
1027 // Restore.
1028 mContext.binder.callingUid = origCallingUser;
1029 mContext.callerPermissions.addAll(origPermissions);
1030 }
1031
1032
Makoto Onukib643fb02015-09-22 15:03:44 -07001033 /**
1034 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1035 */
1036 public void testSetDeviceOwner_noSuchPackage() {
1037 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001038 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001039 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1040 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1041
1042 // Call from a process on the system user.
1043 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1044
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001045 assertExpectException(IllegalArgumentException.class,
1046 /* messageRegex= */ "Invalid component",
1047 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001048 }
1049
1050 public void testSetDeviceOwner_failures() throws Exception {
1051 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1052 }
1053
Makoto Onukia52562c2015-10-01 16:12:31 -07001054 public void testClearDeviceOwner() throws Exception {
1055 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001056 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001057 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1058 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1059
1060 // Set admin1 as a DA to the secondary user.
1061 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1062
1063 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1064
1065 // Set admin 1 as the DO to the system user.
1066
1067 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1068 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1069 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1070 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1071
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001072 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001073 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001074 eq(admin1.getPackageName()));
1075
Makoto Onukic8a5a552015-11-19 14:29:12 -08001076 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001077
Makoto Onuki90b89652016-01-28 14:44:18 -08001078 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001079 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001080 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001081
1082 assertTrue(dpm.isAdminActive(admin1));
1083 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1084
Makoto Onukia52562c2015-10-01 16:12:31 -07001085 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001086 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001087
1088 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001089 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1090 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001091
1092 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001093 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001094 assertExpectException(IllegalStateException.class,
1095 /* messageRegex= */ "User must be running and unlocked",
1096 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001097
Pavel Grafov75c0a892017-05-18 17:28:27 +01001098 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1099 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001100 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1101
1102 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001103 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001104
Pavel Grafov75c0a892017-05-18 17:28:27 +01001105 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001106 eq(false),
1107 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1108
Pavel Grafov75c0a892017-05-18 17:28:27 +01001109 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001110 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001111 eq(null),
1112 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001113
Sudheer Shanka101c3532018-01-08 16:28:42 -08001114 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1115 null, UserHandle.USER_SYSTEM);
1116
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001117 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001118
1119 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1120 // and once for clearing it.
1121 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1122 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1123 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001124 // TODO Check other calls.
1125 }
1126
1127 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1128 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001129 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001130 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1131 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1132
1133 // Set admin1 as a DA to the secondary user.
1134 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1135
1136 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1137
1138 // Set admin 1 as the DO to the system user.
1139
1140 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1141 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1142 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1143 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1144
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001145 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001146 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001147 eq(admin1.getPackageName()));
1148
Makoto Onukic8a5a552015-11-19 14:29:12 -08001149 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001150
1151 // Now call clear from the secondary user, which should throw.
1152 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1153
1154 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001155 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001156 eq(admin1.getPackageName()),
1157 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001158 assertExpectException(SecurityException.class,
1159 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1160 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001161
Makoto Onukic8a5a552015-11-19 14:29:12 -08001162 // DO shouldn't be removed.
1163 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001164 }
1165
Makoto Onukib643fb02015-09-22 15:03:44 -07001166 public void testSetProfileOwner() throws Exception {
1167 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001168
Makoto Onuki90b89652016-01-28 14:44:18 -08001169 // PO admin can't be deactivated.
1170 dpm.removeActiveAdmin(admin1);
1171 assertTrue(dpm.isAdminActive(admin1));
1172
Makoto Onuki803d6752015-10-30 12:58:39 -07001173 // Try setting DO on the same user, which should fail.
1174 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001175 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1176 runAsCaller(mServiceContext, dpms, dpm -> {
1177 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001178 assertExpectException(IllegalStateException.class,
1179 /* messageRegex= */ "already has a profile owner",
1180 () -> dpm.setDeviceOwner(admin2, "owner-name",
1181 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001182 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001183 }
1184
Makoto Onuki90b89652016-01-28 14:44:18 -08001185 public void testClearProfileOwner() throws Exception {
1186 setAsProfileOwner(admin1);
1187
1188 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1189
1190 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1191 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1192
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001193 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001194 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001195 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001196 assertExpectException(IllegalStateException.class,
1197 /* messageRegex= */ "User must be running and unlocked",
1198 () -> dpm.clearProfileOwner(admin1));
1199
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001200 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001201 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001202 dpm.clearProfileOwner(admin1);
1203
1204 // Check
1205 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001206 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001207 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1208 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001209 }
1210
Makoto Onukib643fb02015-09-22 15:03:44 -07001211 public void testSetProfileOwner_failures() throws Exception {
1212 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1213 }
1214
Makoto Onukia52562c2015-10-01 16:12:31 -07001215 public void testGetDeviceOwnerAdminLocked() throws Exception {
1216 checkDeviceOwnerWithMultipleDeviceAdmins();
1217 }
1218
1219 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1220 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1221 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1222 // make sure it gets the right component from the right user.
1223
1224 final int ANOTHER_USER_ID = 100;
1225 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1226
Pavel Grafov75c0a892017-05-18 17:28:27 +01001227 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001228
1229 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001230 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001231 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1232 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1233
1234 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1235
Pavel Grafov75c0a892017-05-18 17:28:27 +01001236 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001237
Makoto Onukia52562c2015-10-01 16:12:31 -07001238 // Make sure the admin packge is installed to each user.
1239 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1240 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1241
1242 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1243 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1244
1245 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1246
1247
1248 // Set active admins to the users.
1249 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1250 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1251
1252 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1253 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1254
1255 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1256
1257 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001258 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001259 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1260
Makoto Onukic8a5a552015-11-19 14:29:12 -08001261 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001262
1263 // Then check getDeviceOwnerAdminLocked().
1264 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1265 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1266 }
1267
1268 /**
1269 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001270 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1271 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001272 *
1273 * We didn't use to persist the DO component class name, but now we do, and the above method
1274 * finds the right component from a package name upon migration.
1275 */
1276 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001277 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001278 checkDeviceOwnerWithMultipleDeviceAdmins();
1279
1280 // Overwrite the device owner setting and clears the clas name.
1281 dpms.mOwners.setDeviceOwner(
1282 new ComponentName(admin2.getPackageName(), ""),
1283 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1284 dpms.mOwners.writeDeviceOwner();
1285
1286 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001287 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001288
1289 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001290 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001291 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001292 initializeDpms();
1293
1294 // Now the DO component name is a full name.
1295 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1296 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001297 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001298 }
1299
Makoto Onukib643fb02015-09-22 15:03:44 -07001300 public void testSetGetApplicationRestriction() {
1301 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001302 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001303
1304 {
1305 Bundle rest = new Bundle();
1306 rest.putString("KEY_STRING", "Foo1");
1307 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1308 }
1309
1310 {
1311 Bundle rest = new Bundle();
1312 rest.putString("KEY_STRING", "Foo2");
1313 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1314 }
1315
1316 {
1317 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1318 assertNotNull(returned);
1319 assertEquals(returned.size(), 1);
1320 assertEquals(returned.get("KEY_STRING"), "Foo1");
1321 }
1322
1323 {
1324 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1325 assertNotNull(returned);
1326 assertEquals(returned.size(), 1);
1327 assertEquals(returned.get("KEY_STRING"), "Foo2");
1328 }
1329
1330 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1331 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1332 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001333
Edman Anjosf9946772016-11-28 16:35:15 +01001334 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001335 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1336 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001337 *
1338 * @param packageName the name of the package to be setup
1339 * @param appId the application ID to be given to the package
1340 * @return the UID of the package as known by the mock package manager
1341 */
1342 private int setupPackageInPackageManager(final String packageName, final int appId)
1343 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001344 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001345 ApplicationInfo.FLAG_HAS_CODE);
1346 }
1347
1348 /**
1349 * Setup a package in the package manager mock. Useful for faking installed applications.
1350 *
1351 * @param packageName the name of the package to be setup
1352 * @param userId the user id where the package will be "installed"
1353 * @param appId the application ID to be given to the package
1354 * @param flags flags to set in the ApplicationInfo for this package
1355 * @return the UID of the package as known by the mock package manager
1356 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001357 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1358 int flags) throws Exception {
1359 final int uid = UserHandle.getUid(userId, appId);
1360 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001361 final PackageInfo pi = new PackageInfo();
1362 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001363 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001364 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001365 eq(packageName),
1366 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001367 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001368 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001369 eq(packageName),
1370 anyInt(),
1371 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001372 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001373 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001374 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001375 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001376 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001377 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001378 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001379 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001380 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001381 return uid;
1382 }
1383
Robin Lee7f5c91c2017-02-08 21:27:02 +00001384 public void testCertificateDisclosure() throws Exception {
1385 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1386 final UserHandle user = UserHandle.of(userId);
1387
1388 mContext.applicationInfo = new ApplicationInfo();
1389 mContext.callerPermissions.add(permission.MANAGE_USERS);
1390 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001391 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001392 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1393
Robin Leeabaa0692017-02-20 20:54:22 +00001394 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1395 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001396
1397 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1398 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1399
1400 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001401 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001402 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001403 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001404 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001405 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001406 .cancelAsUser(anyString(), anyInt(), eq(user));
1407
1408 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001409 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001410 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001411 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1412 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001413 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001414 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001415 .notifyAsUser(anyString(), anyInt(), argThat(
1416 new BaseMatcher<Notification>() {
1417 @Override
1418 public boolean matches(Object item) {
1419 final Notification noti = (Notification) item;
1420 return TEST_STRING.equals(
1421 noti.extras.getString(Notification.EXTRA_TITLE));
1422 }
1423 @Override
1424 public void describeTo(Description description) {
1425 description.appendText(
1426 "Notification{title=\"" + TEST_STRING + "\"}");
1427 }
1428 }), eq(user));
1429 }
1430
Edman Anjosf9946772016-11-28 16:35:15 +01001431 /**
1432 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1433 * privileges can acually be exercised by a delegate are not covered here.
1434 */
1435 public void testDelegation() throws Exception {
1436 setAsProfileOwner(admin1);
1437
1438 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1439
1440 // Given two packages
1441 final String CERT_DELEGATE = "com.delegate.certs";
1442 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1443 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1444 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1445 20989);
1446
1447 // On delegation
1448 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1449 mContext.packageName = admin1.getPackageName();
1450 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1451 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1452
1453 // DPMS correctly stores and retrieves the delegates
1454 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1455 assertEquals(2, policy.mDelegationMap.size());
1456 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1457 DELEGATION_CERT_INSTALL);
1458 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1459 DELEGATION_CERT_INSTALL);
1460 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1461 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1462 DELEGATION_APP_RESTRICTIONS);
1463 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1464 DELEGATION_APP_RESTRICTIONS);
1465 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1466
1467 // On calling install certificate APIs from an unauthorized process
1468 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1469 mContext.packageName = RESTRICTIONS_DELEGATE;
1470
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001471 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1472 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001473
1474 // On calling install certificate APIs from an authorized process
1475 mContext.binder.callingUid = CERT_DELEGATE_UID;
1476 mContext.packageName = CERT_DELEGATE;
1477
1478 // DPMS executes without a SecurityException
1479 try {
1480 dpm.installCaCert(null, null);
1481 } catch (SecurityException unexpected) {
1482 fail("Threw SecurityException on authorized access");
1483 } catch (NullPointerException expected) {
1484 }
1485
1486 // On removing a delegate
1487 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1488 mContext.packageName = admin1.getPackageName();
1489 dpm.setCertInstallerPackage(admin1, null);
1490
1491 // DPMS does not allow access to ex-delegate
1492 mContext.binder.callingUid = CERT_DELEGATE_UID;
1493 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001494 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1495 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001496
1497 // But still allows access to other existing delegates
1498 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1499 mContext.packageName = RESTRICTIONS_DELEGATE;
1500 try {
1501 dpm.getApplicationRestrictions(null, "pkg");
1502 } catch (SecurityException expected) {
1503 fail("Threw SecurityException on authorized access");
1504 }
1505 }
1506
Esteban Talaverabf60f722015-12-10 16:26:44 +00001507 public void testApplicationRestrictionsManagingApp() throws Exception {
1508 setAsProfileOwner(admin1);
1509
Rubin Xued1928a2016-02-11 17:23:06 +00001510 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001511 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001512 final String nonDelegateExceptionMessageRegex =
1513 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001514 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001515 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1516 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001517
Esteban Talaverabf60f722015-12-10 16:26:44 +00001518 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1519 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001520 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1521 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001522 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001523 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001524 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001525 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1526 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001527
1528 // Check via the profile owner that no restrictions were set.
1529 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001530 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001531 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1532
Rubin Xued1928a2016-02-11 17:23:06 +00001533 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001534 assertExpectException(PackageManager.NameNotFoundException.class,
1535 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1536 () -> dpm.setApplicationRestrictionsManagingPackage(
1537 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001538
Esteban Talaverabf60f722015-12-10 16:26:44 +00001539 // Let appRestrictionsManagerPackage manage app restrictions
1540 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1541 assertEquals(appRestrictionsManagerPackage,
1542 dpm.getApplicationRestrictionsManagingPackage(admin1));
1543
1544 // Now that package should be able to set and retrieve app restrictions.
1545 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001546 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001547 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1548 dpm.setApplicationRestrictions(null, "pkg1", rest);
1549 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1550 assertEquals(1, returned.size(), 1);
1551 assertEquals("Foo1", returned.get("KEY_STRING"));
1552
1553 // The same app running on a separate user shouldn't be able to manage app restrictions.
1554 mContext.binder.callingUid = UserHandle.getUid(
1555 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1556 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001557 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1558 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001559
1560 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1561 // too.
1562 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001563 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001564 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1565 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1566 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1567
1568 // Removing the ability for the package to manage app restrictions.
1569 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1570 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1571 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001572 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001573 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001574 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1575 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001576 }
1577
Makoto Onukia4f11972015-10-01 13:19:58 -07001578 public void testSetUserRestriction_asDo() throws Exception {
1579 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001580 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001581 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1582 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1583
1584 // First, set DO.
1585
1586 // Call from a process on the system user.
1587 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1588
1589 // Make sure admin1 is installed on system user.
1590 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001591
1592 // Call.
1593 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001594 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001595 UserHandle.USER_SYSTEM));
1596
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001597 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001598 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001599 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001600 DpmTestUtils.assertRestrictions(
1601 DpmTestUtils.newRestrictions(defaultRestrictions),
1602 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1603 );
1604 DpmTestUtils.assertRestrictions(
1605 DpmTestUtils.newRestrictions(defaultRestrictions),
1606 dpm.getUserRestrictions(admin1)
1607 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001608 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001609 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001610 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001611 eq(true) /* isDeviceOwner */,
1612 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001613 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001614 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001615
1616 for (String restriction : defaultRestrictions) {
1617 dpm.clearUserRestriction(admin1, restriction);
1618 }
1619
Esteban Talavera548a04b2016-12-20 15:22:30 +00001620 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001621 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001622
1623 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001624 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001625 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001626 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1627 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001628 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001629
Makoto Onukia4f11972015-10-01 13:19:58 -07001630 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001631 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001632 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001633 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1634 UserManager.DISALLOW_ADD_USER),
1635 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001636 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001637
Makoto Onuki068c54a2015-10-13 14:34:03 -07001638 DpmTestUtils.assertRestrictions(
1639 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001640 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001641 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1642 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001643 DpmTestUtils.assertRestrictions(
1644 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001645 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001646 dpm.getUserRestrictions(admin1)
1647 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001648
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001650 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001651 eq(UserHandle.USER_SYSTEM),
1652 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001653 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001654 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001655
Makoto Onuki068c54a2015-10-13 14:34:03 -07001656 DpmTestUtils.assertRestrictions(
1657 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1658 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1659 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001660 DpmTestUtils.assertRestrictions(
1661 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1662 dpm.getUserRestrictions(admin1)
1663 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001664
1665 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001666 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001667 eq(UserHandle.USER_SYSTEM),
1668 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001669 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001670 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001671
Esteban Talavera548a04b2016-12-20 15:22:30 +00001672 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001673
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1675 // DO sets them, the scope is global.
1676 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001677 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001678 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001679 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001680 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001682 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1683 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001684 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001685
1686 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1687 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001688 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689
1690 // More tests.
1691 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001692 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001693 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001694 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1695 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001696 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001697
1698 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001699 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001701 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001702 UserManager.DISALLOW_ADD_USER),
1703 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001704 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001705
1706 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001707 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001708 eq(UserHandle.USER_SYSTEM),
1709 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001711 UserManager.DISALLOW_ADD_USER),
1712 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001713 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001714 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715
Eric Sandnessca5969d2018-08-10 13:28:46 +01001716 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1717 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1718 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001719
Eric Sandnessca5969d2018-08-10 13:28:46 +01001720 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1721 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722
Eric Sandnessca5969d2018-08-10 13:28:46 +01001723 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1724 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1725 () -> dpm.setCameraDisabled(admin1, true));
1726 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1727
1728 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1729 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1730 () -> dpm.setKeyguardDisabledFeatures(admin1,
1731 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1732 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1733
1734 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1735 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1736 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1737 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1738
1739 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1740 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1741 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1742 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001743 }
1744
1745 public void testSetUserRestriction_asPo() {
1746 setAsProfileOwner(admin1);
1747
Makoto Onuki068c54a2015-10-13 14:34:03 -07001748 DpmTestUtils.assertRestrictions(
1749 DpmTestUtils.newRestrictions(),
1750 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1751 .ensureUserRestrictions()
1752 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001753
1754 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001755 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001756 eq(DpmMockContext.CALLER_USER_HANDLE),
1757 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001758 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001759 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001760
Makoto Onukia4f11972015-10-01 13:19:58 -07001761 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001762 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001763 eq(DpmMockContext.CALLER_USER_HANDLE),
1764 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1765 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001766 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001767 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001768
Makoto Onuki068c54a2015-10-13 14:34:03 -07001769 DpmTestUtils.assertRestrictions(
1770 DpmTestUtils.newRestrictions(
1771 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1772 UserManager.DISALLOW_OUTGOING_CALLS
1773 ),
1774 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1775 .ensureUserRestrictions()
1776 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001777 DpmTestUtils.assertRestrictions(
1778 DpmTestUtils.newRestrictions(
1779 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1780 UserManager.DISALLOW_OUTGOING_CALLS
1781 ),
1782 dpm.getUserRestrictions(admin1)
1783 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001784
1785 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001786 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001787 eq(DpmMockContext.CALLER_USER_HANDLE),
1788 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001789 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001790 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001791
1792 DpmTestUtils.assertRestrictions(
1793 DpmTestUtils.newRestrictions(
1794 UserManager.DISALLOW_OUTGOING_CALLS
1795 ),
1796 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1797 .ensureUserRestrictions()
1798 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001799 DpmTestUtils.assertRestrictions(
1800 DpmTestUtils.newRestrictions(
1801 UserManager.DISALLOW_OUTGOING_CALLS
1802 ),
1803 dpm.getUserRestrictions(admin1)
1804 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001805
1806 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001807 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001808 eq(DpmMockContext.CALLER_USER_HANDLE),
1809 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001810 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001811 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001812
Makoto Onuki068c54a2015-10-13 14:34:03 -07001813 DpmTestUtils.assertRestrictions(
1814 DpmTestUtils.newRestrictions(),
1815 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1816 .ensureUserRestrictions()
1817 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001818 DpmTestUtils.assertRestrictions(
1819 DpmTestUtils.newRestrictions(),
1820 dpm.getUserRestrictions(admin1)
1821 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001822
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001823 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1824 // though when DO sets them they'll be applied globally.
1825 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001826 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001827 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001828 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001829 eq(DpmMockContext.CALLER_USER_HANDLE),
1830 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1831 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001832 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001833 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001834
1835 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001836 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001837 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001838 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001839 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001840 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001841 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001842
Makoto Onukia4f11972015-10-01 13:19:58 -07001843 // TODO Make sure restrictions are written to the file.
1844 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001845
Esteban Talavera548a04b2016-12-20 15:22:30 +00001846
1847 public void testDefaultEnabledUserRestrictions() throws Exception {
1848 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1849 mContext.callerPermissions.add(permission.MANAGE_USERS);
1850 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1851 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1852
1853 // First, set DO.
1854
1855 // Call from a process on the system user.
1856 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1857
1858 // Make sure admin1 is installed on system user.
1859 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1860
1861 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1862 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1863 UserHandle.USER_SYSTEM));
1864
1865 // Check that the user restrictions that are enabled by default are set. Then unset them.
1866 String[] defaultRestrictions = UserRestrictionsUtils
1867 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1868 assertTrue(defaultRestrictions.length > 0);
1869 DpmTestUtils.assertRestrictions(
1870 DpmTestUtils.newRestrictions(defaultRestrictions),
1871 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1872 );
1873 DpmTestUtils.assertRestrictions(
1874 DpmTestUtils.newRestrictions(defaultRestrictions),
1875 dpm.getUserRestrictions(admin1)
1876 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001877 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001878 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001879 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001880 eq(true) /* isDeviceOwner */,
1881 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001882 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001883 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001884
1885 for (String restriction : defaultRestrictions) {
1886 dpm.clearUserRestriction(admin1, restriction);
1887 }
1888
1889 assertNoDeviceOwnerRestrictions();
1890
1891 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001892 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001893 initializeDpms();
1894 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1895 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1896
1897 assertNoDeviceOwnerRestrictions();
1898
1899 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1900 // is set as it wasn't enabled during setDeviceOwner.
1901 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1902 assertFalse(UserRestrictionsUtils
1903 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1904 UserRestrictionsUtils
1905 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1906 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001907 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001908 initializeDpms();
1909 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1910 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1911
1912 DpmTestUtils.assertRestrictions(
1913 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1914 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1915 );
1916 DpmTestUtils.assertRestrictions(
1917 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1918 dpm.getUserRestrictions(admin1)
1919 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001920 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001921 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001922 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001923 eq(true) /* isDeviceOwner */,
1924 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001925 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001926 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001927
1928 // Remove the restriction.
1929 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1930
1931 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1932 initializeDpms();
1933 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1934 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1935 assertNoDeviceOwnerRestrictions();
1936 } finally {
1937 UserRestrictionsUtils
1938 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1939 }
1940 }
1941
1942 private void assertNoDeviceOwnerRestrictions() {
1943 DpmTestUtils.assertRestrictions(
1944 DpmTestUtils.newRestrictions(),
1945 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1946 );
1947 DpmTestUtils.assertRestrictions(
1948 DpmTestUtils.newRestrictions(),
1949 dpm.getUserRestrictions(admin1)
1950 );
1951 }
1952
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001953 public void testGetMacAddress() throws Exception {
1954 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1955 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1956 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1957
1958 // In this test, change the caller user to "system".
1959 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1960
1961 // Make sure admin1 is installed on system user.
1962 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1963
1964 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001965 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1966 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001967
1968 // DO needs to be an DA.
1969 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1970 assertTrue(dpm.isAdminActive(admin1));
1971
1972 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001973 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1974 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001975
1976 // Test 3. Caller has PO, but not DO.
1977 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001978 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1979 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001980
1981 // Remove PO.
1982 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001983 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001984 // Test 4, Caller is DO now.
1985 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1986
xshu425b9a62018-12-13 14:18:18 -08001987 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001988 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001989
xshu425b9a62018-12-13 14:18:18 -08001990 // 4-2. When WifiManager returns an empty array, dpm should also output null.
1991 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001992 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001993
1994 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08001995 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
1996 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001997 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001998 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001999
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002000 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002001 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2002 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2003
2004 // In this test, change the caller user to "system".
2005 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2006
2007 // Make sure admin1 is installed on system user.
2008 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2009
2010 // Set admin1 as DA.
2011 dpm.setActiveAdmin(admin1, false);
2012 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002013 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2014 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002015
2016 // Set admin1 as PO.
2017 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002018 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2019 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002020
2021 // Remove PO and add DO.
2022 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002023 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002024 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2025
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002026 // admin1 is DO.
2027 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002028 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002029 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002030 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2031 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002032
2033 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002034 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002035 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002036 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2037 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002038
2039 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002040 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002041 dpm.reboot(admin1);
2042 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002043
2044 public void testSetGetSupportText() {
2045 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2046 dpm.setActiveAdmin(admin1, true);
2047 dpm.setActiveAdmin(admin2, true);
2048 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2049
2050 // Null default support messages.
2051 {
2052 assertNull(dpm.getLongSupportMessage(admin1));
2053 assertNull(dpm.getShortSupportMessage(admin1));
2054 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2055 assertNull(dpm.getShortSupportMessageForUser(admin1,
2056 DpmMockContext.CALLER_USER_HANDLE));
2057 assertNull(dpm.getLongSupportMessageForUser(admin1,
2058 DpmMockContext.CALLER_USER_HANDLE));
2059 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2060 }
2061
2062 // Only system can call the per user versions.
2063 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002064 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2065 () -> dpm.getShortSupportMessageForUser(admin1,
2066 DpmMockContext.CALLER_USER_HANDLE));
2067 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2068 () -> dpm.getLongSupportMessageForUser(admin1,
2069 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002070 }
2071
2072 // Can't set message for admin in another uid.
2073 {
2074 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002075 assertExpectException(SecurityException.class,
2076 /* messageRegex= */ "is not owned by uid",
2077 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002078 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2079 }
2080
2081 // Set/Get short returns what it sets and other admins text isn't changed.
2082 {
2083 final String supportText = "Some text to test with.";
2084 dpm.setShortSupportMessage(admin1, supportText);
2085 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2086 assertNull(dpm.getLongSupportMessage(admin1));
2087 assertNull(dpm.getShortSupportMessage(admin2));
2088
2089 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2090 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2091 DpmMockContext.CALLER_USER_HANDLE));
2092 assertNull(dpm.getShortSupportMessageForUser(admin2,
2093 DpmMockContext.CALLER_USER_HANDLE));
2094 assertNull(dpm.getLongSupportMessageForUser(admin1,
2095 DpmMockContext.CALLER_USER_HANDLE));
2096 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2097
2098 dpm.setShortSupportMessage(admin1, null);
2099 assertNull(dpm.getShortSupportMessage(admin1));
2100 }
2101
2102 // Set/Get long returns what it sets and other admins text isn't changed.
2103 {
2104 final String supportText = "Some text to test with.\nWith more text.";
2105 dpm.setLongSupportMessage(admin1, supportText);
2106 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2107 assertNull(dpm.getShortSupportMessage(admin1));
2108 assertNull(dpm.getLongSupportMessage(admin2));
2109
2110 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2111 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2112 DpmMockContext.CALLER_USER_HANDLE));
2113 assertNull(dpm.getLongSupportMessageForUser(admin2,
2114 DpmMockContext.CALLER_USER_HANDLE));
2115 assertNull(dpm.getShortSupportMessageForUser(admin1,
2116 DpmMockContext.CALLER_USER_HANDLE));
2117 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2118
2119 dpm.setLongSupportMessage(admin1, null);
2120 assertNull(dpm.getLongSupportMessage(admin1));
2121 }
2122 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002123
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002124 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002125 setAsProfileOwner(admin1);
2126
2127 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002128 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002129
2130 // Setup
2131 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2132 final String package1 = "com.example.one";
2133 final String package2 = "com.example.two";
2134 pkgsToRestrict.add(package1);
2135 pkgsToRestrict.add(package2);
2136 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2137 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002138 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002139
2140 // Verify
2141 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002142 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002143 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2144 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2145 eq(DpmMockContext.CALLER_USER_HANDLE));
2146
2147 // Setup
2148 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002149 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002150
2151 // Verify
2152 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002153 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002154 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2155 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2156 eq(DpmMockContext.CALLER_USER_HANDLE));
2157 }
2158
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002159 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002160 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2161 dpm.setActiveAdmin(admin1, true);
2162 assertTrue(dpm.isAdminActive(admin1));
2163 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2164
2165 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002166 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002167 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002168 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002169 }
2170
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002171 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002172 setAsProfileOwner(admin1);
2173
2174 // Setup
2175 final ArrayList<String> emptyList = new ArrayList<>();
2176 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2177 final String package1 = "com.example.one";
2178 final String package2 = "com.example.two";
2179 final String package3 = "com.example.three";
2180 pkgsToRestrict.add(package1);
2181 pkgsToRestrict.add(package2);
2182 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2183 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002184 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002185
2186 // Verify
2187 assertEquals(emptyList, excludedPkgs);
2188 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2189 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002190 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002191 DpmMockContext.CALLER_USER_HANDLE));
2192 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002193 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002194 DpmMockContext.CALLER_USER_HANDLE));
2195 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002196 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002197 DpmMockContext.CALLER_USER_HANDLE));
2198 }
2199
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002200 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002201 setAsProfileOwner(admin1);
2202 assertExpectException(SecurityException.class,
2203 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002204 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002205 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2206 dpm.clearProfileOwner(admin1);
2207
2208 setDeviceOwner();
2209 assertExpectException(SecurityException.class,
2210 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002211 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002212 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2213 clearDeviceOwner();
2214 }
2215
phweiss73145f42017-01-17 19:06:38 +01002216 public void testCreateAdminSupportIntent() throws Exception {
2217 // Setup device owner.
2218 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2219 setupDeviceOwner();
2220
2221 // Nonexisting permission returns null
2222 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2223 assertNull(intent);
2224
2225 // Existing permission that is not set returns null
2226 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2227 assertNull(intent);
2228
2229 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002230 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002231 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2232 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2233 .thenReturn(true);
2234 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2235 assertNull(intent);
2236
2237 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002238 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002239 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2240 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2241 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2242 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2243 assertNotNull(intent);
2244 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2245 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2246 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002247 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002248 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2249 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2250
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002251 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2252 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002253
2254 // Camera is not disabled
2255 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2256 assertNull(intent);
2257
2258 // Camera is disabled
2259 dpm.setCameraDisabled(admin1, true);
2260 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2261 assertNotNull(intent);
2262 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2263 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2264
2265 // Screen capture is not disabled
2266 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2267 assertNull(intent);
2268
2269 // Screen capture is disabled
2270 dpm.setScreenCaptureDisabled(admin1, true);
2271 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2272 assertNotNull(intent);
2273 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2274 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2275
2276 // Same checks for different user
2277 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2278 // Camera should be disabled by device owner
2279 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2280 assertNotNull(intent);
2281 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2282 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2283 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2284 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2285 // ScreenCapture should not be disabled by device owner
2286 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2287 assertNull(intent);
2288 }
2289
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002290 /**
2291 * Test for:
2292 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002293 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002294 * {@link DevicePolicyManager#isAffiliatedUser}
2295 */
2296 public void testUserAffiliation() throws Exception {
2297 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2298 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2299 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2300
2301 // Check that the system user is unaffiliated.
2302 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2303 assertFalse(dpm.isAffiliatedUser());
2304
2305 // Set a device owner on the system user. Check that the system user becomes affiliated.
2306 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2307 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2308 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2309 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002310 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002311
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002312 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002313 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2314 setAsProfileOwner(admin2);
2315 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002316 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002317
2318 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2319 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002320 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002321 userAffiliationIds.add("red");
2322 userAffiliationIds.add("green");
2323 userAffiliationIds.add("blue");
2324 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002325 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002326 assertFalse(dpm.isAffiliatedUser());
2327
2328 // Have the device owner specify a set of affiliation ids that do not intersect with those
2329 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002330 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002331 deviceAffiliationIds.add("cyan");
2332 deviceAffiliationIds.add("yellow");
2333 deviceAffiliationIds.add("magenta");
2334 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2335 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002336 MoreAsserts.assertContentsInAnyOrder(
2337 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002338 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2339 assertFalse(dpm.isAffiliatedUser());
2340
2341 // Have the profile owner specify a set of affiliation ids that intersect with those
2342 // specified by the device owner. Check that the test user becomes affiliated.
2343 userAffiliationIds.add("yellow");
2344 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002345 MoreAsserts.assertContentsInAnyOrder(
2346 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002347 assertTrue(dpm.isAffiliatedUser());
2348
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002349 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002350 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002351 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002352 assertFalse(dpm.isAffiliatedUser());
2353
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002354 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2355 dpm.setAffiliationIds(admin2, userAffiliationIds);
2356 assertTrue(dpm.isAffiliatedUser());
2357 dpm.clearProfileOwner(admin2);
2358 assertFalse(dpm.isAffiliatedUser());
2359
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002360 // Check that the system user remains affiliated.
2361 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2362 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002363
2364 // Clear the device owner - the user becomes unaffiliated.
2365 clearDeviceOwner();
2366 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002367 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002368
2369 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002370 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002371 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2372 }
2373
2374 public void testSetUserProvisioningState_permission() throws Exception {
2375 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002376
2377 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2378 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2379 }
2380
2381 public void testSetUserProvisioningState_unprivileged() throws Exception {
2382 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002383 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2384 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2385 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002386 }
2387
2388 public void testSetUserProvisioningState_noManagement() {
2389 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002390 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002391 assertExpectException(IllegalStateException.class,
2392 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2393 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2394 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002395 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2396 }
2397
2398 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2399 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2400 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002401
2402 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2403 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2404 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2405 }
2406
2407 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2408 throws Exception {
2409 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2410 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002411
2412 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2413 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2414 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2415 }
2416
2417 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2418 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2419 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002420
2421 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2422 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2423 }
2424
2425 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2426 throws Exception {
2427 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002428
2429 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2430 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2431 DevicePolicyManager.STATE_USER_UNMANAGED);
2432 }
2433
2434 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2435 throws Exception {
2436 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002437
2438 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2439 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2440 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2441 }
2442
2443 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2444 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002445
2446 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2447 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2448 }
2449
2450 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2451 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002452
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002453 assertExpectException(IllegalStateException.class,
2454 /* messageRegex= */ "Cannot move to user provisioning state",
2455 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2456 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2457 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002458 }
2459
2460 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2461 throws Exception {
2462 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002463
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002464 assertExpectException(IllegalStateException.class,
2465 /* messageRegex= */ "Cannot move to user provisioning state",
2466 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2467 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2468 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002469 }
2470
2471 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002472 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2473 mContext.callerPermissions.add(permission.MANAGE_USERS);
2474
Alan Treadwayafad8782016-01-19 15:15:08 +00002475 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2476 for (int state : states) {
2477 dpm.setUserProvisioningState(state, userId);
2478 assertEquals(state, dpm.getUserProvisioningState());
2479 }
2480 }
2481
2482 private void setupProfileOwner() throws Exception {
2483 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2484
2485 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2486 dpm.setActiveAdmin(admin1, false);
2487 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2488
2489 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2490 }
2491
2492 private void setupDeviceOwner() throws Exception {
2493 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2494
2495 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2496 dpm.setActiveAdmin(admin1, false);
2497 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2498
2499 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2500 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002501
2502 public void testSetMaximumTimeToLock() {
2503 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2504
2505 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2506 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2507
Pavel Grafov75c0a892017-05-18 17:28:27 +01002508 reset(getServices().powerManagerInternal);
2509 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002510
2511 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002512 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2513 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002514 reset(getServices().powerManagerInternal);
2515 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002516
2517 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002518 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2519 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002520 reset(getServices().powerManagerInternal);
2521 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002522
2523 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002524 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2525 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002526 reset(getServices().powerManagerInternal);
2527 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002528
2529 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002530 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2531 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002532 reset(getServices().powerManagerInternal);
2533 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002534
2535 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002536 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2537 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002538 reset(getServices().powerManagerInternal);
2539 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002540
2541 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002542 reset(getServices().powerManagerInternal);
2543 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002544
Pavel Grafov28939982017-10-03 15:11:52 +01002545 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2546 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2547 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002548 reset(getServices().powerManagerInternal);
2549 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002550
2551 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002552 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2553 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002554 reset(getServices().powerManagerInternal);
2555 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002556
Pavel Grafov28939982017-10-03 15:11:52 +01002557 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002558 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002559 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2560 verifyStayOnWhilePluggedCleared(false);
2561 }
2562
2563 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2564 // uses separate challenge.
2565 public void testSetMaximumTimeToLockProfile() throws Exception {
2566 final int PROFILE_USER = 15;
2567 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2568 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2569 mContext.binder.callingUid = PROFILE_ADMIN;
2570 final DevicePolicyManagerInternal dpmi =
2571 LocalServices.getService(DevicePolicyManagerInternal.class);
2572
2573 dpm.setMaximumTimeToLock(admin1, 0);
2574
2575 reset(getServices().powerManagerInternal);
2576 reset(getServices().settings);
2577
2578 // First add timeout for the profile.
2579 dpm.setMaximumTimeToLock(admin1, 10);
2580 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2581
2582 reset(getServices().powerManagerInternal);
2583 reset(getServices().settings);
2584
2585 // Add separate challenge
2586 when(getServices().lockPatternUtils
2587 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2588 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2589
2590 verifyScreenTimeoutCall(10L, PROFILE_USER);
2591 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2592
2593 reset(getServices().powerManagerInternal);
2594 reset(getServices().settings);
2595
2596 // Remove the timeout.
2597 dpm.setMaximumTimeToLock(admin1, 0);
2598 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2599 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2600
2601 reset(getServices().powerManagerInternal);
2602 reset(getServices().settings);
2603
2604 // Add it back.
2605 dpm.setMaximumTimeToLock(admin1, 10);
2606 verifyScreenTimeoutCall(10L, PROFILE_USER);
2607 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2608
2609 reset(getServices().powerManagerInternal);
2610 reset(getServices().settings);
2611
2612 // Remove separate challenge.
2613 reset(getServices().lockPatternUtils);
2614 when(getServices().lockPatternUtils
2615 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2616 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2617
2618 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2619 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2620
2621 reset(getServices().powerManagerInternal);
2622 reset(getServices().settings);
2623
2624 // Remove the timeout.
2625 dpm.setMaximumTimeToLock(admin1, 0);
2626 verifyScreenTimeoutCall(null, PROFILE_USER);
2627 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002628 }
2629
Michal Karpinski943aabd2016-10-06 11:09:25 +01002630 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2631 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2632 setupDeviceOwner();
2633 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2634
Michal Karpinskid084ca52017-01-18 15:54:18 +00002635 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2636 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2637 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2638 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2639 - ONE_MINUTE;
2640
2641 // verify that the minimum timeout cannot be modified on user builds (system property is
2642 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002643 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002644
2645 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2646 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2647 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2648
Pavel Grafov75c0a892017-05-18 17:28:27 +01002649 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002650
2651 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002652 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002653
Michal Karpinskid084ca52017-01-18 15:54:18 +00002654 // reset to default (0 means the admin is not participating, so default should be returned)
2655 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002656
2657 // aggregation should be the default if unset by any admin
2658 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2659 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2660
2661 // admin not participating by default
2662 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2663
2664 //clamping from the top
2665 dpm.setRequiredStrongAuthTimeout(admin1,
2666 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2667 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2668 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2669 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2670 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2671
Michal Karpinskid084ca52017-01-18 15:54:18 +00002672 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002673 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2674 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2675 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2676 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2677
2678 // clamping from the bottom
2679 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2680 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2681 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2682
Michal Karpinskid084ca52017-01-18 15:54:18 +00002683 // values within range
2684 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2685 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2686 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2687
2688 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2689 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2690 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002691
2692 // reset to default
2693 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2694 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2695 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2696 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2697
2698 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002699 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2700 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002701 }
2702
Pavel Grafov28939982017-10-03 15:11:52 +01002703 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002704 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002705 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002706 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002707 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002708 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002709 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002710 }
Pavel Grafov28939982017-10-03 15:11:52 +01002711 }
2712
2713 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002714 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2715 // UnfinishedVerificationException.
2716 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002717
Esteban Talavera01576862016-12-15 11:16:44 +00002718 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002719 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002720 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002721 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002722 .thenReturn(false);
2723 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002724 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2725 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002726 .thenReturn(true);
2727 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2728
2729 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002730 }
Victor Chang3e794af2016-03-04 13:48:17 +00002731
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002732 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2733 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002734 mContext.packageName = admin1.getPackageName();
2735 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002736 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2737 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2738 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2739 false);
2740 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2741 }
2742
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002743 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2744 setup_DeviceAdminFeatureOff();
2745 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2746 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2747 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2748 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2749 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2750 assertCheckProvisioningPreCondition(
2751 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2752 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2753 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2754 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2755 }
2756
Esteban Talavera01576862016-12-15 11:16:44 +00002757 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002758 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002759 .thenReturn(false);
2760 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002761 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2762 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002763 .thenReturn(true);
2764 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2765
2766 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002767 }
Victor Chang3e794af2016-03-04 13:48:17 +00002768
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002769 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2770 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002771 mContext.packageName = admin1.getPackageName();
2772 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002773 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2774 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2775 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2776 false);
2777 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2778
2779 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002780 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002781 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2782 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2784 true);
2785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2786 }
2787
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002788 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2789 setup_ManagedProfileFeatureOff();
2790 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2791 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2792 DevicePolicyManager.CODE_OK);
2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2794 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2795 assertCheckProvisioningPreCondition(
2796 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2797 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2798 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2799 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2800
2801 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002802 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002803 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2804 DevicePolicyManager.CODE_OK);
2805 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2806 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2807 assertCheckProvisioningPreCondition(
2808 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2809 DevicePolicyManager.CODE_OK);
2810 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2811 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2812 }
2813
Esteban Talavera01576862016-12-15 11:16:44 +00002814 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002815 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002816 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002817 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2818 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002819 .thenReturn(true);
2820 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2821
2822 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002823 }
Victor Chang3e794af2016-03-04 13:48:17 +00002824
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002825 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2826 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002827 mContext.packageName = admin1.getPackageName();
2828 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002829 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2830 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2831 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2832 false /* because of non-split user */);
2833 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2834 false /* because of non-split user */);
2835 }
2836
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002837 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002838 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002839 setup_nonSplitUser_firstBoot_primaryUser();
2840 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2841 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2842 DevicePolicyManager.CODE_OK);
2843 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2844 DevicePolicyManager.CODE_OK);
2845 assertCheckProvisioningPreCondition(
2846 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2847 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2848 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2849 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2850 }
2851
Esteban Talavera01576862016-12-15 11:16:44 +00002852 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002853 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002854 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002855 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2856 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002857 .thenReturn(true);
2858 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2859
2860 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002861 }
Victor Chang3e794af2016-03-04 13:48:17 +00002862
Nicolas Prevot45d29072017-01-18 16:11:19 +00002863 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2864 setDeviceOwner();
2865 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2866 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2867 }
2868
2869 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2870 setup_nonSplitUser_withDo_primaryUser();
2871 final int MANAGED_PROFILE_USER_ID = 18;
2872 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2873 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002874 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002875 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002876 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002877 true)).thenReturn(true);
2878 }
2879
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002880 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2881 throws Exception {
2882 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002883 mContext.packageName = admin1.getPackageName();
2884 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002885 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2886 false/* because of completed device setup */);
2887 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2888 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2889 false/* because of non-split user */);
2890 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2891 false/* because of non-split user */);
2892 }
2893
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002894 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2895 throws Exception {
2896 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2897 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2898 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2899 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2900 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2901 DevicePolicyManager.CODE_OK);
2902 assertCheckProvisioningPreCondition(
2903 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2904 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2905 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2906 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2907 }
2908
Nicolas Prevot45d29072017-01-18 16:11:19 +00002909 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2910 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002911 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002912 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2913
2914 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2915 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002916 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002917
2918 // COMP mode is allowed.
2919 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2920 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002921 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002922
Nicolas Prevot45d29072017-01-18 16:11:19 +00002923 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002924 assertCheckProvisioningPreCondition(
2925 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002926 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002927 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002928 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2929 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2930 }
Esteban Talavera01576862016-12-15 11:16:44 +00002931
Nicolas Prevot45d29072017-01-18 16:11:19 +00002932 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2933 setup_nonSplitUser_withDo_primaryUser();
2934 mContext.packageName = admin1.getPackageName();
2935 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2936 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2937 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002938 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002939 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2940 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2941 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002942 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002943 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2944 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2945 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2946 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2947 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002948 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002949 assertCheckProvisioningPreCondition(
2950 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002951 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002952 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002953 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2954 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2955 }
Esteban Talavera01576862016-12-15 11:16:44 +00002956
Nicolas Prevot45d29072017-01-18 16:11:19 +00002957 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2958 throws Exception {
2959 setup_nonSplitUser_withDo_primaryUser();
2960 mContext.packageName = admin1.getPackageName();
2961 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002962 // The DO should not be allowed to initiate provisioning if the restriction is set by
2963 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002964 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002965 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2966 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2967 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002968 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002969 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2970 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2971 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2972 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2973 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002974 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2975
2976 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002977 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002978 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002979 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002980 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2981 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2982 }
2983
2984 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2985 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2986 mContext.packageName = admin1.getPackageName();
2987 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2988
2989 // We can delete the managed profile to create a new one, so provisioning is allowed.
2990 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2991 DevicePolicyManager.CODE_OK);
2992 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2993 assertCheckProvisioningPreCondition(
2994 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2995 DpmMockContext.ANOTHER_PACKAGE_NAME,
2996 DevicePolicyManager.CODE_OK);
2997 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2998 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2999 }
3000
3001 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3002 throws Exception {
3003 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3004 mContext.packageName = admin1.getPackageName();
3005 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003006 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003007 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3008 eq(UserHandle.SYSTEM)))
3009 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003010 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003011 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3012 eq(UserHandle.SYSTEM)))
3013 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003014
3015 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003016 assertCheckProvisioningPreCondition(
3017 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3018 DpmMockContext.ANOTHER_PACKAGE_NAME,
3019 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3020 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3021 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003022
3023 // But the device owner can still do it because it has set the restriction itself.
3024 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3025 DevicePolicyManager.CODE_OK);
3026 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003027 }
3028
3029 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003030 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003031 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003032 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3033 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003034 .thenReturn(false);
3035 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3036
3037 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003038 }
Victor Chang3e794af2016-03-04 13:48:17 +00003039
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003040 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3041 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003042 mContext.packageName = admin1.getPackageName();
3043 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003044 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3045 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3046 false /* because canAddMoreManagedProfiles returns false */);
3047 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3048 true);
3049 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3050 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003051 }
3052
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003053 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3054 throws Exception {
3055 setup_splitUser_firstBoot_systemUser();
3056 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3057 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3058 DevicePolicyManager.CODE_OK);
3059 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003060 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003061 assertCheckProvisioningPreCondition(
3062 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3063 DevicePolicyManager.CODE_OK);
3064 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3065 DevicePolicyManager.CODE_SYSTEM_USER);
3066 }
3067
Esteban Talavera01576862016-12-15 11:16:44 +00003068 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003069 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003070 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003071 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3072 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003073 .thenReturn(false);
3074 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3075
3076 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003077 }
Victor Chang3e794af2016-03-04 13:48:17 +00003078
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003079 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3080 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003081 mContext.packageName = admin1.getPackageName();
3082 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003083 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3084 true/* it's undefined behavior. Can be changed into false in the future */);
3085 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3086 false /* because canAddMoreManagedProfiles returns false */);
3087 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3088 true/* it's undefined behavior. Can be changed into false in the future */);
3089 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3090 false/* because calling uid is system user */);
3091 }
3092
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003093 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3094 throws Exception {
3095 setup_splitUser_afterDeviceSetup_systemUser();
3096 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3097 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3098 DevicePolicyManager.CODE_OK);
3099 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003100 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003101 assertCheckProvisioningPreCondition(
3102 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3103 DevicePolicyManager.CODE_OK);
3104 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3105 DevicePolicyManager.CODE_SYSTEM_USER);
3106 }
3107
Esteban Talavera01576862016-12-15 11:16:44 +00003108 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003109 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003110 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003111 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3112 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003113 true)).thenReturn(true);
3114 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3115
3116 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003117 }
Victor Chang3e794af2016-03-04 13:48:17 +00003118
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003119 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3120 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003121 mContext.packageName = admin1.getPackageName();
3122 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003123 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3124 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3125 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3126 true);
3127 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003128 }
3129
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003130 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003131 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003132 setup_splitUser_firstBoot_primaryUser();
3133 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3134 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3135 DevicePolicyManager.CODE_OK);
3136 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3137 DevicePolicyManager.CODE_OK);
3138 assertCheckProvisioningPreCondition(
3139 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3140 DevicePolicyManager.CODE_OK);
3141 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3142 DevicePolicyManager.CODE_OK);
3143 }
3144
Esteban Talavera01576862016-12-15 11:16:44 +00003145 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003146 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003147 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003148 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3149 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003150 true)).thenReturn(true);
3151 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3152
3153 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003154 }
Victor Chang3e794af2016-03-04 13:48:17 +00003155
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003156 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3157 throws Exception {
3158 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003159 mContext.packageName = admin1.getPackageName();
3160 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003161 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3162 true/* it's undefined behavior. Can be changed into false in the future */);
3163 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3164 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3165 true/* it's undefined behavior. Can be changed into false in the future */);
3166 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3167 false/* because user setup completed */);
3168 }
3169
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003170 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003171 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003172 setup_splitUser_afterDeviceSetup_primaryUser();
3173 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3174 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3175 DevicePolicyManager.CODE_OK);
3176 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3177 DevicePolicyManager.CODE_OK);
3178 assertCheckProvisioningPreCondition(
3179 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3180 DevicePolicyManager.CODE_OK);
3181 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3182 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3183 }
3184
Esteban Talavera01576862016-12-15 11:16:44 +00003185 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003186 setDeviceOwner();
3187
Pavel Grafov75c0a892017-05-18 17:28:27 +01003188 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003189 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003190 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3191 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003192 .thenReturn(false);
3193 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3194
3195 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003196 }
Victor Chang3e794af2016-03-04 13:48:17 +00003197
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003198 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3199 throws Exception {
3200 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003201 mContext.packageName = admin1.getPackageName();
3202 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003203 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3204 false /* can't provision managed profile on system user */);
3205 }
3206
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003207 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003208 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003209 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3210 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3211 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3212 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3213 }
3214
3215 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003216 setDeviceOwner();
3217
Pavel Grafov75c0a892017-05-18 17:28:27 +01003218 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003219 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003220 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3221 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003222 true)).thenReturn(true);
3223 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3224
3225 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003226 }
Victor Chang3e794af2016-03-04 13:48:17 +00003227
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003228 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3229 throws Exception {
3230 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003231 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3232 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003233 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3234 }
3235
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003236 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003237 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003238 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3239 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003240
3241 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003242 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3243 DevicePolicyManager.CODE_OK);
3244 }
3245
3246 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003247 setDeviceOwner();
3248
Pavel Grafov75c0a892017-05-18 17:28:27 +01003249 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003250 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003251 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3252 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003253 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3254 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003255 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003256 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003257 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003258 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003259 true)).thenReturn(true);
3260 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3261
3262 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003263 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003264
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003265 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3266 throws Exception {
3267 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003268 mContext.packageName = admin1.getPackageName();
3269 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003270 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3271 }
3272
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003273 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3274 throws Exception {
3275 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3276 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3277 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3278 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3279 }
3280
3281 public void testCheckProvisioningPreCondition_permission() {
3282 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003283 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3284 () -> dpm.checkProvisioningPreCondition(
3285 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003286 }
3287
Victor Chang3577ed22016-08-25 18:49:26 +01003288 public void testForceUpdateUserSetupComplete_permission() {
3289 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003290 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3291 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003292 }
3293
3294 public void testForceUpdateUserSetupComplete_systemUser() {
3295 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3296 // GIVEN calling from user 20
3297 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003298 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3299 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003300 }
3301
3302 public void testForceUpdateUserSetupComplete_userbuild() {
3303 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3304 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3305
3306 final int userId = UserHandle.USER_SYSTEM;
3307 // GIVEN userComplete is false in SettingsProvider
3308 setUserSetupCompleteForUser(false, userId);
3309
3310 // GIVEN userComplete is true in DPM
3311 DevicePolicyManagerService.DevicePolicyData userData =
3312 new DevicePolicyManagerService.DevicePolicyData(userId);
3313 userData.mUserSetupComplete = true;
3314 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3315
3316 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003317 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003318
3319 assertTrue(dpms.hasUserSetupCompleted());
3320
3321 dpm.forceUpdateUserSetupComplete();
3322
3323 // THEN the state in dpms is not changed
3324 assertTrue(dpms.hasUserSetupCompleted());
3325 }
3326
3327 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3328 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3329 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3330
3331 final int userId = UserHandle.USER_SYSTEM;
3332 // GIVEN userComplete is false in SettingsProvider
3333 setUserSetupCompleteForUser(false, userId);
3334
3335 // GIVEN userComplete is true in DPM
3336 DevicePolicyManagerService.DevicePolicyData userData =
3337 new DevicePolicyManagerService.DevicePolicyData(userId);
3338 userData.mUserSetupComplete = true;
3339 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3340
3341 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003342 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003343
3344 assertTrue(dpms.hasUserSetupCompleted());
3345
3346 dpm.forceUpdateUserSetupComplete();
3347
3348 // THEN the state in dpms is not changed
3349 assertFalse(dpms.hasUserSetupCompleted());
3350 }
3351
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003352 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003353 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003354 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003355
3356 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3357 runAsCaller(mAdmin1Context, dpms, dpm -> {
3358 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3359 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003360 }
3361
3362 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3363 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3364 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003365
3366 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3367 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003368 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003369 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3370 .thenReturn(true);
3371
3372 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003373 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003374
3375 // Enabling logging should not change the timestamp.
3376 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003377 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003378 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003379 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003380 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003381 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003382
3383 // Retrieving the logs should update the timestamp.
3384 final long beforeRetrieval = System.currentTimeMillis();
3385 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003386 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003387 final long afterRetrieval = System.currentTimeMillis();
3388 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3389 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3390
3391 // Retrieving the pre-boot logs should update the timestamp.
3392 Thread.sleep(2);
3393 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003394 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003395 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3396
3397 // Checking the timestamp again should not change it.
3398 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003399 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003400
3401 // Retrieving the logs again should update the timestamp.
3402 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003403 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003404 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3405
3406 // Disabling logging should not change the timestamp.
3407 Thread.sleep(2);
3408 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003409 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003410
3411 // Restarting the DPMS should not lose the timestamp.
3412 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003413 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003414
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003415 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3416 mContext.binder.callingUid = 1234567;
3417 mContext.callerPermissions.add(permission.MANAGE_USERS);
3418 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3419 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3420
3421 // System can retrieve the timestamp.
3422 mContext.binder.clearCallingIdentity();
3423 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3424
3425 // Removing the device owner should clear the timestamp.
3426 clearDeviceOwner();
3427 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003428 }
3429
yuemingw0de748d2017-11-15 19:22:27 +00003430 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3431 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3432 setupDeviceOwner();
3433 assertExpectException(SecurityException.class, null, () ->
3434 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3435 }
3436
yuemingwc0281f12018-03-28 15:58:49 +01003437 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003438 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3439 setupDeviceOwner();
3440 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003441 verify(getServices().settings).settingsSystemPutStringForUser(
3442 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3443 }
3444
3445 public void testSetSystemSettingWithPO() throws Exception {
3446 setupProfileOwner();
3447 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3448 verify(getServices().settings).settingsSystemPutStringForUser(
3449 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003450 }
3451
yuemingwe43cdf72017-10-12 16:52:11 +01003452 public void testSetTime() throws Exception {
3453 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3454 setupDeviceOwner();
3455 dpm.setTime(admin1, 0);
3456 verify(getServices().alarmManager).setTime(0);
3457 }
3458
3459 public void testSetTimeFailWithPO() throws Exception {
3460 setupProfileOwner();
3461 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3462 }
3463
3464 public void testSetTimeWithAutoTimeOn() throws Exception {
3465 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3466 setupDeviceOwner();
3467 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3468 .thenReturn(1);
3469 assertFalse(dpm.setTime(admin1, 0));
3470 }
3471
3472 public void testSetTimeZone() throws Exception {
3473 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3474 setupDeviceOwner();
3475 dpm.setTimeZone(admin1, "Asia/Shanghai");
3476 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3477 }
3478
3479 public void testSetTimeZoneFailWithPO() throws Exception {
3480 setupProfileOwner();
3481 assertExpectException(SecurityException.class, null,
3482 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3483 }
3484
3485 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3486 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3487 setupDeviceOwner();
3488 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3489 .thenReturn(1);
3490 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3491 }
3492
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003493 public void testGetLastBugReportRequestTime() throws Exception {
3494 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3495 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003496
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003497 mContext.packageName = admin1.getPackageName();
3498 mContext.applicationInfo = new ApplicationInfo();
3499 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3500 .thenReturn(Color.WHITE);
3501 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3502 anyObject())).thenReturn(Color.WHITE);
3503
Esteban Talaverad36dd152016-12-15 08:51:45 +00003504 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3505 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003506 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003507
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003508 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003509 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003510
3511 // Requesting a bug report should update the timestamp.
3512 final long beforeRequest = System.currentTimeMillis();
3513 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003514 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003515 final long afterRequest = System.currentTimeMillis();
3516 assertTrue(bugReportRequestTime >= beforeRequest);
3517 assertTrue(bugReportRequestTime <= afterRequest);
3518
3519 // Checking the timestamp again should not change it.
3520 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003521 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003522
3523 // Restarting the DPMS should not lose the timestamp.
3524 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003525 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003526
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003527 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3528 mContext.binder.callingUid = 1234567;
3529 mContext.callerPermissions.add(permission.MANAGE_USERS);
3530 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3531 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3532
3533 // System can retrieve the timestamp.
3534 mContext.binder.clearCallingIdentity();
3535 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3536
3537 // Removing the device owner should clear the timestamp.
3538 clearDeviceOwner();
3539 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003540 }
3541
3542 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3543 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3544 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003545 mContext.packageName = admin1.getPackageName();
3546 mContext.applicationInfo = new ApplicationInfo();
3547 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3548 .thenReturn(Color.WHITE);
3549 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3550 anyObject())).thenReturn(Color.WHITE);
3551
3552 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3553 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003554 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003555 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003556 .thenReturn(true);
3557
3558 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003559 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003560
3561 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3562 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003563 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003564
3565 // Enabling logging should not change the timestamp.
3566 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003567 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003568
3569 // Retrieving the logs should update the timestamp.
3570 final long beforeRetrieval = System.currentTimeMillis();
3571 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003572 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003573 final long afterRetrieval = System.currentTimeMillis();
3574 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3575 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3576
3577 // Checking the timestamp again should not change it.
3578 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003579 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003580
3581 // Retrieving the logs again should update the timestamp.
3582 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003583 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003584 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3585
3586 // Disabling logging should not change the timestamp.
3587 Thread.sleep(2);
3588 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003589 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003590
3591 // Restarting the DPMS should not lose the timestamp.
3592 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003593 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3594
3595 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3596 mContext.binder.callingUid = 1234567;
3597 mContext.callerPermissions.add(permission.MANAGE_USERS);
3598 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3599 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3600
3601 // System can retrieve the timestamp.
3602 mContext.binder.clearCallingIdentity();
3603 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3604
3605 // Removing the device owner should clear the timestamp.
3606 clearDeviceOwner();
3607 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003608 }
3609
Tony Mak2f26b792016-11-28 17:54:51 +00003610 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3611 // Setup device owner.
3612 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3613 setupDeviceOwner();
3614
3615 // Only device owner is setup, the result list should be empty.
3616 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3617 MoreAsserts.assertEmpty(targetUsers);
3618
3619 // Setup a managed profile managed by the same admin.
3620 final int MANAGED_PROFILE_USER_ID = 15;
3621 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3622 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3623
3624 // Add a secondary user, it should never talk with.
3625 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003626 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003627
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003628 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3629 // other.
3630 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3631 MoreAsserts.assertEmpty(targetUsers);
3632
3633 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3634 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3635 MoreAsserts.assertEmpty(targetUsers);
3636
3637 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003638 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003639 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3640 dpm.setAffiliationIds(admin1, userAffiliationIds);
3641
3642 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3643 dpm.setAffiliationIds(admin1, userAffiliationIds);
3644
Tony Mak2f26b792016-11-28 17:54:51 +00003645 // Calling from device owner admin, the result list should just contain the managed
3646 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003647 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003648 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3649 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3650
3651 // Calling from managed profile admin, the result list should just contain the system
3652 // user id.
3653 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3654 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3655 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003656
3657 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003658 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003659
3660 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3661 // to each other.
3662 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3663 MoreAsserts.assertEmpty(targetUsers);
3664
3665 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3666 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3667 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003668 }
3669
3670 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3671 // Setup a device owner.
3672 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3673 setupDeviceOwner();
3674
3675 // Set up a managed profile managed by different package.
3676 final int MANAGED_PROFILE_USER_ID = 15;
3677 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3678 final ComponentName adminDifferentPackage =
3679 new ComponentName("another.package", "whatever.class");
3680 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3681
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003682 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003683 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003684 dpm.setAffiliationIds(admin1, userAffiliationIds);
3685
3686 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3687 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3688
Tony Mak2f26b792016-11-28 17:54:51 +00003689 // Calling from device owner admin, we should get zero bind device admin target users as
3690 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003691 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003692 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3693 MoreAsserts.assertEmpty(targetUsers);
3694
3695 // Calling from managed profile admin, we should still get zero target users for the same
3696 // reason.
3697 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3698 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3699 MoreAsserts.assertEmpty(targetUsers);
3700 }
3701
Jason Parks3c13b642017-11-28 15:39:43 -06003702 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003703 verifyLockTaskState(userId, new String[0],
3704 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003705 }
3706
3707 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3708 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003709 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003710 }
3711
3712 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3713 int flags) throws Exception {
3714 mContext.binder.callingUid = uid;
3715 dpm.setLockTaskPackages(who, packages);
3716 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3717 for (String p : packages) {
3718 assertTrue(dpm.isLockTaskPermitted(p));
3719 }
3720 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3721 // Test to see if set lock task features can be set
3722 dpm.setLockTaskFeatures(who, flags);
3723 verifyLockTaskState(userId, packages, flags);
3724 }
3725
3726 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3727 int flags) throws Exception {
3728 mContext.binder.callingUid = uid;
3729 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3730 () -> dpm.setLockTaskPackages(who, packages));
3731 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3732 () -> dpm.getLockTaskPackages(who));
3733 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3734 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3735 () -> dpm.setLockTaskFeatures(who, flags));
3736 }
3737
Charles Hee078db72017-10-19 18:03:20 +01003738 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003739 // Setup a device owner.
3740 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3741 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003742 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003743 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003744
3745 // Set up a managed profile managed by different package (package name shouldn't matter)
3746 final int MANAGED_PROFILE_USER_ID = 15;
3747 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3748 final ComponentName adminDifferentPackage =
3749 new ComponentName("another.package", "whatever.class");
3750 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003751 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3752
3753 // Setup a PO on the secondary user
3754 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3755 setAsProfileOwner(admin3);
3756 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003757
3758 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003759 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003760 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003761 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3762 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003763 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3764
3765 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3766 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003767 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3768 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003769 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003770
3771 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3772 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3773 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003774 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003775 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3776 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003777 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003778
3779 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003780 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003781 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3782 dpm.setAffiliationIds(admin1, userAffiliationIds);
3783
3784 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3785 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3786
3787 // Now the managed profile can set lock task packages.
3788 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3789 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3790 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3791 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003792 // And it can set lock task features.
3793 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003794 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003795
3796 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003797 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003798 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3799 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003800 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3801 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003802 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003803 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003804
Jason Parks3c13b642017-11-28 15:39:43 -06003805 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003806 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3807 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003808
3809 }
3810
3811 public void testLockTaskPolicyForProfileOwner() throws Exception {
3812 // Setup a PO
3813 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3814 setAsProfileOwner(admin1);
3815 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3816
3817 final String[] poPackages = {"poPackage1", "poPackage2"};
3818 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003819 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3820 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003821 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3822 poPackages, poFlags);
3823
3824 // Set up a managed profile managed by different package (package name shouldn't matter)
3825 final int MANAGED_PROFILE_USER_ID = 15;
3826 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3827 final ComponentName adminDifferentPackage =
3828 new ComponentName("another.package", "whatever.class");
3829 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3830 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3831
3832 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3833 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3834 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3835 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003836 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3837 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003838 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003839 }
3840
Benjamin Franzcaffa772018-02-05 16:36:10 +00003841 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3842 // Setup a device owner.
3843 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3844 setupDeviceOwner();
3845 // Lock task policy is updated when loading user data.
3846 verifyLockTaskState(UserHandle.USER_SYSTEM);
3847
3848 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3849 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3850 assertExpectException(IllegalArgumentException.class,
3851 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3852 () -> dpm.setLockTaskFeatures(admin1, flags));
3853 }
3854
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003855 public void testIsDeviceManaged() throws Exception {
3856 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3857 setupDeviceOwner();
3858
3859 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3860 // find out that the device has a device owner.
3861 assertTrue(dpm.isDeviceManaged());
3862 mContext.binder.callingUid = 1234567;
3863 mContext.callerPermissions.add(permission.MANAGE_USERS);
3864 assertTrue(dpm.isDeviceManaged());
3865 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3866 mContext.binder.clearCallingIdentity();
3867 assertTrue(dpm.isDeviceManaged());
3868
3869 clearDeviceOwner();
3870
3871 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3872 // not have a device owner.
3873 mContext.binder.callingUid = 1234567;
3874 mContext.callerPermissions.add(permission.MANAGE_USERS);
3875 assertFalse(dpm.isDeviceManaged());
3876 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3877 mContext.binder.clearCallingIdentity();
3878 assertFalse(dpm.isDeviceManaged());
3879 }
3880
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003881 public void testDeviceOwnerOrganizationName() throws Exception {
3882 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3883 setupDeviceOwner();
3884
3885 dpm.setOrganizationName(admin1, "organization");
3886
3887 // Device owner can retrieve organization managing the device.
3888 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3889
3890 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3891 mContext.binder.callingUid = 1234567;
3892 mContext.callerPermissions.add(permission.MANAGE_USERS);
3893 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3894 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3895
3896 // System can retrieve organization managing the device.
3897 mContext.binder.clearCallingIdentity();
3898 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3899
3900 // Removing the device owner clears the organization managing the device.
3901 clearDeviceOwner();
3902 assertNull(dpm.getDeviceOwnerOrganizationName());
3903 }
3904
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003905 public void testWipeDataManagedProfile() throws Exception {
3906 final int MANAGED_PROFILE_USER_ID = 15;
3907 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3908 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3909 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3910
3911 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003912 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003913 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003914 // Get mock reason string since we throw an IAE with empty string input.
3915 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3916 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003917
3918 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003919 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003920 MANAGED_PROFILE_USER_ID);
3921 }
3922
3923 public void testWipeDataManagedProfileDisallowed() throws Exception {
3924 final int MANAGED_PROFILE_USER_ID = 15;
3925 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3926 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3927
3928 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003929 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003930 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3931
Pavel Grafov75c0a892017-05-18 17:28:27 +01003932 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003933 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3934 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3935 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003936 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3937 thenReturn("Just a test string.");
3938
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003939 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003940 // The PO is not allowed to remove the profile if the user restriction was set on the
3941 // profile by the system
3942 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3943 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003944 }
3945
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003946 public void testWipeDataDeviceOwner() throws Exception {
3947 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003948 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003949 UserManager.DISALLOW_FACTORY_RESET,
3950 UserHandle.SYSTEM))
3951 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003952 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3953 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003954
3955 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003956 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003957 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3958 /*wipeEuicc=*/ eq(false));
3959 }
3960
3961 public void testWipeEuiccDataEnabled() throws Exception {
3962 setDeviceOwner();
3963 when(getServices().userManager.getUserRestrictionSource(
3964 UserManager.DISALLOW_FACTORY_RESET,
3965 UserHandle.SYSTEM))
3966 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003967 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3968 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003969
3970 dpm.wipeData(WIPE_EUICC);
3971 verify(getServices().recoverySystem).rebootWipeUserData(
3972 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3973 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003974 }
3975
3976 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3977 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003978 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003979 UserManager.DISALLOW_FACTORY_RESET,
3980 UserHandle.SYSTEM))
3981 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003982 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3983 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003984 // The DO is not allowed to wipe the device if the user restriction was set
3985 // by the system
3986 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3987 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003988 }
3989
3990 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3991 final int MANAGED_PROFILE_USER_ID = 15;
3992 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3993 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3994
3995 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003996 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003997 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3998
Pavel Grafov75c0a892017-05-18 17:28:27 +01003999 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004000 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4001 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4002 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4003
4004 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4005 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4006
4007 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4008 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4009 // Failed password attempts on the parent user are taken into account, as there isn't a
4010 // separate work challenge.
4011 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4012 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4013 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4014
4015 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4016 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004017 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004018 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004019 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004020 }
4021
4022 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4023 throws Exception {
4024 final int MANAGED_PROFILE_USER_ID = 15;
4025 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4026 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4027
4028 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004029 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004030 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4031
Pavel Grafov75c0a892017-05-18 17:28:27 +01004032 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004033 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4034 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4035 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4036
4037 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4038 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4039
4040 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4041 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4042 // Failed password attempts on the parent user are taken into account, as there isn't a
4043 // separate work challenge.
4044 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4045 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4046 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4047
4048 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4049 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004050 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004051 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004052 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004053 }
4054
4055 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4056 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004057 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004058 UserManager.DISALLOW_FACTORY_RESET,
4059 UserHandle.SYSTEM))
4060 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4061
4062 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4063
4064 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4065 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4066 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4067 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4068 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4069
4070 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4071 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004072 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004073 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4074 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004075 }
4076
4077 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4078 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004079 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004080 UserManager.DISALLOW_FACTORY_RESET,
4081 UserHandle.SYSTEM))
4082 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4083
4084 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4085
4086 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4087 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4088 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4089 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4090 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4091
4092 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004093 verifyZeroInteractions(getServices().recoverySystem);
4094 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004095 .removeUserEvenWhenDisallowed(anyInt());
4096 }
4097
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004098 public void testGetPermissionGrantState() throws Exception {
4099 final String permission = "some.permission";
4100 final String app1 = "com.example.app1";
4101 final String app2 = "com.example.app2";
4102
Pavel Grafov75c0a892017-05-18 17:28:27 +01004103 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004104 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004105 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004106 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004107 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004108 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4109 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004110 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004111 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004112 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004113 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004114 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004115 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4116
4117 // System can retrieve permission grant state.
4118 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004119 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004120 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4121 dpm.getPermissionGrantState(null, app1, permission));
4122 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4123 dpm.getPermissionGrantState(null, app2, permission));
4124
4125 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004126 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4127 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004128 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4129 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004130
4131 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004132 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4133 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004134 setAsProfileOwner(admin1);
4135 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4136 dpm.getPermissionGrantState(admin1, app1, permission));
4137 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4138 dpm.getPermissionGrantState(admin1, app2, permission));
4139 }
4140
Rubin Xuaab7a412016-12-30 21:13:29 +00004141 public void testResetPasswordWithToken() throws Exception {
4142 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4143 setupDeviceOwner();
4144 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004145 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4146 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4147
Rubin Xuaab7a412016-12-30 21:13:29 +00004148 // test adding a token
4149 final byte[] token = new byte[32];
4150 final long handle = 123456;
4151 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01004152 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004153 .thenReturn(handle);
4154 assertTrue(dpm.setResetPasswordToken(admin1, token));
4155
4156 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004157 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004158 .thenReturn(true);
4159 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4160
4161 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004162 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01004163 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
4164 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004165 eq(UserHandle.USER_SYSTEM)))
4166 .thenReturn(true);
4167 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4168
4169 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004170 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004171 .thenReturn(true);
4172 assertTrue(dpm.clearResetPasswordToken(admin1));
4173 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004174
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004175 public void testIsActivePasswordSufficient() throws Exception {
4176 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4177 mContext.packageName = admin1.getPackageName();
4178 setupDeviceOwner();
4179
4180 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4181 dpm.setPasswordMinimumLength(admin1, 8);
4182 dpm.setPasswordMinimumLetters(admin1, 6);
4183 dpm.setPasswordMinimumLowerCase(admin1, 3);
4184 dpm.setPasswordMinimumUpperCase(admin1, 1);
4185 dpm.setPasswordMinimumNonLetter(admin1, 1);
4186 dpm.setPasswordMinimumNumeric(admin1, 1);
4187 dpm.setPasswordMinimumSymbols(admin1, 0);
4188
Rubin Xucc391c22018-01-02 20:37:35 +00004189 reset(mContext.spiedContext);
4190
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004191 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4192 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4193 8, 2,
4194 6, 1,
4195 0, 1);
4196
4197 setActivePasswordState(passwordMetricsNoSymbols);
4198 assertTrue(dpm.isActivePasswordSufficient());
4199
4200 initializeDpms();
4201 reset(mContext.spiedContext);
4202 assertTrue(dpm.isActivePasswordSufficient());
4203
4204 // This call simulates the user entering the password for the first time after a reboot.
4205 // This causes password metrics to be reloaded into memory. Until this happens,
4206 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4207 // even if the DPC changes password requirements so that the password no longer meets the
4208 // requirements. This is a known limitation of the current implementation of
4209 // isActivePasswordSufficient() - see b/34218769.
4210 setActivePasswordState(passwordMetricsNoSymbols);
4211 assertTrue(dpm.isActivePasswordSufficient());
4212
4213 dpm.setPasswordMinimumSymbols(admin1, 1);
4214 // This assertion would fail if we had not called setActivePasswordState() again after
4215 // initializeDpms() - see previous comment.
4216 assertFalse(dpm.isActivePasswordSufficient());
4217
4218 initializeDpms();
4219 reset(mContext.spiedContext);
4220 assertFalse(dpm.isActivePasswordSufficient());
4221
4222 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4223 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4224 7, 2,
4225 5, 1,
4226 1, 2);
4227
4228 setActivePasswordState(passwordMetricsWithSymbols);
4229 assertTrue(dpm.isActivePasswordSufficient());
4230 }
4231
Pavel Grafov75c0a892017-05-18 17:28:27 +01004232 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4233 throws Exception {
4234 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004235 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004236
Pavel Grafov75c0a892017-05-18 17:28:27 +01004237 dpm.setActivePasswordState(passwordMetrics, userHandle);
4238 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004239
Rubin Xucc391c22018-01-02 20:37:35 +00004240 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4241 // reportPasswordChanged()
Eran Messeri9ecde422018-04-30 16:16:39 +01004242 // This broadcast should be sent 4 times:
4243 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4244 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
4245 // * Twice from calls to DevicePolicyManagerService.saveSettingsLocked
4246 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4247 // the password change is relevant to and another with the credential owner of said
4248 // userId.
4249 verify(mContext.spiedContext, times(4)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004250 MockUtils.checkIntentAction(
4251 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4252 MockUtils.checkUserHandle(userHandle));
4253
Pavel Grafov75c0a892017-05-18 17:28:27 +01004254 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4255 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004256 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004257
4258 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4259 MockUtils.checkIntent(intent),
4260 MockUtils.checkUserHandle(userHandle));
4261
4262 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4263 // let it finish with system uid, otherwise it will throw and crash.
4264 flushTasks();
4265
4266 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004267 }
4268
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004269 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4270 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4271 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4272 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4273 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4274 DpmMockContext.SYSTEM_UID);
4275 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4276 DpmMockContext.SYSTEM_UID);
4277
4278 // Set up a device owner.
4279 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004280 setupDeviceOwner();
4281
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004282 // First and second user set IMEs manually.
4283 mContext.binder.callingUid = firstUserSystemUid;
4284 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4285 mContext.binder.callingUid = secondUserSystemUid;
4286 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004287
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004288 // Device owner changes IME for first user.
4289 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004290 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004291 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004292 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004293 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004294 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004295 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004296 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4297 mContext.binder.callingUid = firstUserSystemUid;
4298 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4299 mContext.binder.callingUid = secondUserSystemUid;
4300 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004301
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004302 // Second user changes IME manually.
4303 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4304 mContext.binder.callingUid = firstUserSystemUid;
4305 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4306 mContext.binder.callingUid = secondUserSystemUid;
4307 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004308
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004309 // First user changes IME manually.
4310 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4311 mContext.binder.callingUid = firstUserSystemUid;
4312 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4313 mContext.binder.callingUid = secondUserSystemUid;
4314 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004315
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004316 // Device owner changes IME for first user again.
4317 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004318 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004319 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004320 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004321 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004322 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004323 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4324 mContext.binder.callingUid = firstUserSystemUid;
4325 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4326 mContext.binder.callingUid = secondUserSystemUid;
4327 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004328
4329 // Restarting the DPMS should not lose information.
4330 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004331 mContext.binder.callingUid = firstUserSystemUid;
4332 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4333 mContext.binder.callingUid = secondUserSystemUid;
4334 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004335
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004336 // Device owner can find out whether it set the current IME itself.
4337 mContext.binder.callingUid = deviceOwnerUid;
4338 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004339
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004340 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004341 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004342 mContext.binder.callingUid = firstUserSystemUid;
4343 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4344 mContext.binder.callingUid = secondUserSystemUid;
4345 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004346 }
4347
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004348 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4349 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4350 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4351 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4352 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4353 DpmMockContext.SYSTEM_UID);
4354 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4355 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004356
4357 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004358 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004359 setupProfileOwner();
4360
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004361 // First and second user set IMEs manually.
4362 mContext.binder.callingUid = firstUserSystemUid;
4363 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4364 mContext.binder.callingUid = secondUserSystemUid;
4365 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004366
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004367 // Profile owner changes IME for second user.
4368 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004369 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004370 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004371 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004372 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004373 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004374 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004375 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4376 mContext.binder.callingUid = firstUserSystemUid;
4377 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4378 mContext.binder.callingUid = secondUserSystemUid;
4379 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004380
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004381 // First user changes IME manually.
4382 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4383 mContext.binder.callingUid = firstUserSystemUid;
4384 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4385 mContext.binder.callingUid = secondUserSystemUid;
4386 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004387
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004388 // Second user changes IME manually.
4389 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4390 mContext.binder.callingUid = firstUserSystemUid;
4391 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4392 mContext.binder.callingUid = secondUserSystemUid;
4393 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004394
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004395 // Profile owner changes IME for second user again.
4396 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004397 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004398 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004399 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004400 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004401 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004402 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4403 mContext.binder.callingUid = firstUserSystemUid;
4404 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4405 mContext.binder.callingUid = secondUserSystemUid;
4406 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004407
4408 // Restarting the DPMS should not lose information.
4409 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004410 mContext.binder.callingUid = firstUserSystemUid;
4411 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4412 mContext.binder.callingUid = secondUserSystemUid;
4413 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004414
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004415 // Profile owner can find out whether it set the current IME itself.
4416 mContext.binder.callingUid = profileOwnerUid;
4417 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004418
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004419 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004420 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004421 mContext.binder.callingUid = firstUserSystemUid;
4422 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4423 mContext.binder.callingUid = secondUserSystemUid;
4424 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004425 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004426
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004427 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4428 throws Exception {
4429 // Set up a device owner.
4430 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4431 setupDeviceOwner();
4432 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4433 }
4434
4435 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4436 throws Exception {
4437 // Set up a profile owner.
4438 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4439 setupProfileOwner();
4440 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4441 }
4442
4443 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4444 int adminUid) throws Exception {
4445 mContext.binder.callingUid = adminUid;
4446 final int userId = UserHandle.getUserId(adminUid);
4447
4448 final String packageName = "some.package";
4449 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4450 admin1, Collections.singletonList(packageName)));
4451 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4452
4453 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4454 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4455
4456 // Attempt to set to empty list (which means no listener is whitelisted)
4457 mContext.binder.callingUid = adminUid;
4458 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004459 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004460 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4461
4462 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4463 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4464 }
4465
4466 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4467 // Set up a managed profile
4468 final int MANAGED_PROFILE_USER_ID = 15;
4469 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4470 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4471 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4472
4473 final String permittedListener = "some.package";
4474 setupPackageInPackageManager(
4475 permittedListener,
4476 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4477 /*appId=*/ 12345, /*flags=*/ 0);
4478
4479 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4480 admin1, Collections.singletonList(permittedListener)));
4481
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004482 // isNotificationListenerServicePermitted should throw if not called from System.
4483 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4484 () -> dpms.isNotificationListenerServicePermitted(
4485 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004486
4487 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4488 assertTrue(dpms.isNotificationListenerServicePermitted(
4489 permittedListener, MANAGED_PROFILE_USER_ID));
4490 }
4491
4492 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4493 throws Exception {
4494 // Set up a managed profile
4495 final int MANAGED_PROFILE_USER_ID = 15;
4496 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4497 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4498 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4499
4500 final String permittedListener = "permitted.package";
4501 int appId = 12345;
4502 setupPackageInPackageManager(
4503 permittedListener,
4504 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4505 appId, /*flags=*/ 0);
4506
4507 final String notPermittedListener = "not.permitted.package";
4508 setupPackageInPackageManager(
4509 notPermittedListener,
4510 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4511 ++appId, /*flags=*/ 0);
4512
4513 final String systemListener = "system.package";
4514 setupPackageInPackageManager(
4515 systemListener,
4516 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4517 ++appId, ApplicationInfo.FLAG_SYSTEM);
4518
4519 // By default all packages are allowed
4520 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4521
4522 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4523 assertTrue(dpms.isNotificationListenerServicePermitted(
4524 permittedListener, MANAGED_PROFILE_USER_ID));
4525 assertTrue(dpms.isNotificationListenerServicePermitted(
4526 notPermittedListener, MANAGED_PROFILE_USER_ID));
4527 assertTrue(dpms.isNotificationListenerServicePermitted(
4528 systemListener, MANAGED_PROFILE_USER_ID));
4529
4530 // Setting only one package in the whitelist
4531 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4532 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4533 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004534 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004535 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4536 assertEquals(1, permittedListeners.size());
4537 assertEquals(permittedListener, permittedListeners.get(0));
4538
4539 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4540 assertTrue(dpms.isNotificationListenerServicePermitted(
4541 permittedListener, MANAGED_PROFILE_USER_ID));
4542 assertFalse(dpms.isNotificationListenerServicePermitted(
4543 notPermittedListener, MANAGED_PROFILE_USER_ID));
4544 // System packages are always allowed (even if not in the whitelist)
4545 assertTrue(dpms.isNotificationListenerServicePermitted(
4546 systemListener, MANAGED_PROFILE_USER_ID));
4547
4548 // Setting an empty whitelist - only system listeners allowed
4549 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4550 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004551 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004552 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4553
4554 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4555 assertFalse(dpms.isNotificationListenerServicePermitted(
4556 permittedListener, MANAGED_PROFILE_USER_ID));
4557 assertFalse(dpms.isNotificationListenerServicePermitted(
4558 notPermittedListener, MANAGED_PROFILE_USER_ID));
4559 // System packages are always allowed (even if not in the whitelist)
4560 assertTrue(dpms.isNotificationListenerServicePermitted(
4561 systemListener, MANAGED_PROFILE_USER_ID));
4562
4563 // Setting a null whitelist - all listeners allowed
4564 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4565 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4566 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4567
4568 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4569 assertTrue(dpms.isNotificationListenerServicePermitted(
4570 permittedListener, MANAGED_PROFILE_USER_ID));
4571 assertTrue(dpms.isNotificationListenerServicePermitted(
4572 notPermittedListener, MANAGED_PROFILE_USER_ID));
4573 assertTrue(dpms.isNotificationListenerServicePermitted(
4574 systemListener, MANAGED_PROFILE_USER_ID));
4575 }
4576
4577 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4578 throws Exception {
4579 // Set up a managed profile
4580 final int MANAGED_PROFILE_USER_ID = 15;
4581 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4582 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4583 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4584
4585 final String nonSystemPackage = "non.system.package";
4586 int appId = 12345;
4587 setupPackageInPackageManager(
4588 nonSystemPackage,
4589 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4590 appId, /*flags=*/ 0);
4591
4592 final String systemListener = "system.package";
4593 setupPackageInPackageManager(
4594 systemListener,
4595 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4596 ++appId, ApplicationInfo.FLAG_SYSTEM);
4597
4598 // By default all packages are allowed (for all profiles)
4599 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4600
4601 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4602 assertTrue(dpms.isNotificationListenerServicePermitted(
4603 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4604 assertTrue(dpms.isNotificationListenerServicePermitted(
4605 systemListener, MANAGED_PROFILE_USER_ID));
4606 assertTrue(dpms.isNotificationListenerServicePermitted(
4607 nonSystemPackage, UserHandle.USER_SYSTEM));
4608 assertTrue(dpms.isNotificationListenerServicePermitted(
4609 systemListener, UserHandle.USER_SYSTEM));
4610
4611 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4612 // all allowed in primary profile
4613 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4614 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004615 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004616 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4617
4618 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4619 assertFalse(dpms.isNotificationListenerServicePermitted(
4620 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4621 assertTrue(dpms.isNotificationListenerServicePermitted(
4622 systemListener, MANAGED_PROFILE_USER_ID));
4623 assertTrue(dpms.isNotificationListenerServicePermitted(
4624 nonSystemPackage, UserHandle.USER_SYSTEM));
4625 assertTrue(dpms.isNotificationListenerServicePermitted(
4626 systemListener, UserHandle.USER_SYSTEM));
4627 }
4628
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004629 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004630 mServiceContext.packageName = mRealTestContext.getPackageName();
4631 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4632 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004633 setDeviceOwner();
4634
Pavel Grafov75c0a892017-05-18 17:28:27 +01004635 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004636 }
4637
4638 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004639 mServiceContext.packageName = mRealTestContext.getPackageName();
4640 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4641 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004642 setAsProfileOwner(admin1);
4643
Pavel Grafov75c0a892017-05-18 17:28:27 +01004644 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4645 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004646 }
4647
4648 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004649 mServiceContext.packageName = mRealTestContext.getPackageName();
4650 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4651 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004652 setAsProfileOwner(admin1);
4653
Pavel Grafov75c0a892017-05-18 17:28:27 +01004654 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4655 caller.packageName = "com.example.delegate";
4656 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4657 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004658
Pavel Grafov75c0a892017-05-18 17:28:27 +01004659 // Make caller a delegated cert installer.
4660 runAsCaller(mAdmin1Context, dpms,
4661 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004662
4663 verifyCanGetOwnerInstalledCaCerts(null, caller);
4664 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004665 }
4666
Rubin Xucc391c22018-01-02 20:37:35 +00004667 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004668 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4669 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004670 Bundle restriction = new Bundle();
4671 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4672
4673 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4674 RestrictionsListener listener = new RestrictionsListener(mContext);
4675 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4676 new Bundle());
4677 verifyDataSharingChangedBroadcast();
4678 }
4679
4680 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004681 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4682 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004683 Bundle restriction = new Bundle();
4684 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4685
4686 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4687 RestrictionsListener listener = new RestrictionsListener(mContext);
4688 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4689 restriction);
4690 verifyDataSharingChangedBroadcast();
4691 }
4692
4693 public void testDisallowSharingIntoProfileUnchanged() {
4694 RestrictionsListener listener = new RestrictionsListener(mContext);
4695 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4696 new Bundle());
4697 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4698 }
4699
4700 private void verifyDataSharingChangedBroadcast() {
4701 Intent expectedIntent = new Intent(
4702 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4703 expectedIntent.setPackage("com.android.managedprovisioning");
4704 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4705 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4706 MockUtils.checkIntent(expectedIntent),
4707 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4708 }
4709
yuemingwe3d9c092018-01-11 12:11:44 +00004710 public void testOverrideApnAPIsFailWithPO() throws Exception {
4711 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004712 ApnSetting apn = (new ApnSetting.Builder())
4713 .setApnName("test")
4714 .setEntryName("test")
4715 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4716 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004717 assertExpectException(SecurityException.class, null, () ->
4718 dpm.addOverrideApn(admin1, apn));
4719 assertExpectException(SecurityException.class, null, () ->
4720 dpm.updateOverrideApn(admin1, 0, apn));
4721 assertExpectException(SecurityException.class, null, () ->
4722 dpm.removeOverrideApn(admin1, 0));
4723 assertExpectException(SecurityException.class, null, () ->
4724 dpm.getOverrideApns(admin1));
4725 assertExpectException(SecurityException.class, null, () ->
4726 dpm.setOverrideApnsEnabled(admin1, false));
4727 assertExpectException(SecurityException.class, null, () ->
4728 dpm.isOverrideApnEnabled(admin1));
4729 }
4730
Robin Lee2c68dad2017-03-17 12:50:24 +00004731 private void verifyCanGetOwnerInstalledCaCerts(
4732 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004733 final String alias = "cert";
4734 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004735
4736 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004737 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004738 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4739 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004740 }
4741 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4742
4743 // caller: device admin or delegated certificate installer
4744 callerContext.applicationInfo = new ApplicationInfo();
4745 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4746
4747 // system_server
4748 final DpmMockContext serviceContext = mContext;
4749 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004750 getServices().addPackageContext(callerUser, admin1Context);
4751 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004752
4753 // Install a CA cert.
4754 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004755 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004756 .thenReturn(alias);
4757 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004758 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004759 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004760 });
4761
Pavel Grafov75c0a892017-05-18 17:28:27 +01004762 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4763 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4764 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004765 flushTasks();
4766
Robin Lee2c68dad2017-03-17 12:50:24 +00004767 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4768
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004769 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004770 runAsCaller(admin1Context, dpms, (dpm) -> {
4771 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004772 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004773 ownerInstalledCaCerts.addAll(installedCaCerts);
4774 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004775
4776 // Restarting the DPMS should not lose information.
4777 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004778 runAsCaller(admin1Context, dpms, (dpm) ->
4779 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004780
4781 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004782 runAsCaller(serviceContext, dpms, (dpm) -> {
4783 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004784
Robin Lee2c68dad2017-03-17 12:50:24 +00004785 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004786 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004787 });
4788
Pavel Grafov75c0a892017-05-18 17:28:27 +01004789 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4790 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4791 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004792 flushTasks();
4793
4794 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4795 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004796 runAsCaller(admin1Context, dpms, (dpm) -> {
4797 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4798 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004799 }
4800
Robin Lee2c68dad2017-03-17 12:50:24 +00004801 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4802 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004803 final String alias = "cert";
4804 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004805
4806 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004807 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004808 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4809 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004810 }
4811 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4812
4813 // caller: device admin or delegated certificate installer
4814 callerContext.applicationInfo = new ApplicationInfo();
4815 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4816
4817 // system_server
4818 final DpmMockContext serviceContext = mContext;
4819 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004820 getServices().addPackageContext(callerUser, admin1Context);
4821 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004822
4823 // Install a CA cert as caller
4824 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004825 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004826 .thenReturn(alias);
4827 assertTrue(dpm.installCaCert(callerName, caCert));
4828 });
4829
4830 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004831 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004832 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004833 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4834 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4835 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004836 flushTasks();
4837
Robin Lee2c68dad2017-03-17 12:50:24 +00004838 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004839 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004840
4841 runAsCaller(serviceContext, dpms, (dpm) -> {
4842 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4843 assertNotNull(ownerInstalledCaCerts);
4844 assertTrue(ownerInstalledCaCerts.isEmpty());
4845 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004846 }
4847
Eran Messeri94d56762017-12-21 20:50:54 +00004848 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4849 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4850 Arrays.sort(gotFlags);
4851 Arrays.sort(expectedFlags);
4852 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4853 }
4854
4855 public void testTranslationOfIdAttestationFlag() {
4856 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4857 int[] correspondingAttUtilsTypes = new int[]{
4858 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4859 AttestationUtils.ID_TYPE_MEID};
4860
4861 // Test translation of zero flags
4862 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4863
4864 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4865 // non-null array
4866 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4867
4868 // Test translation of a single flag
4869 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4870 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4871 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4872
4873 // Test translation of two flags
4874 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4875 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4876 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4877 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4878
4879 // Test translation of all three flags
4880 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4881 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4882 AttestationUtils.ID_TYPE_MEID});
4883 // Test translation of all three flags
4884 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4885 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4886 AttestationUtils.ID_TYPE_MEID});
4887 }
4888
arangelov08d534b2018-01-22 15:20:53 +00004889 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4890 setDeviceOwner();
4891 initializeDpms();
4892 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4893 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4894 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4895 }
4896
4897 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4898 DpmTestUtils.writeInputStreamToFile(
4899 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4900 getDeviceOwnerPoliciesFile());
4901 DpmTestUtils.writeInputStreamToFile(
4902 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4903 getDeviceOwnerFile());
4904 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4905 }
4906
4907 public void testRevertDeviceOwnership_deviceNotMigrated()
4908 throws Exception {
4909 DpmTestUtils.writeInputStreamToFile(
4910 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4911 getDeviceOwnerPoliciesFile());
4912 DpmTestUtils.writeInputStreamToFile(
4913 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4914 getDeviceOwnerFile());
4915 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4916 }
4917
4918 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4919 throws Exception {
4920 DpmTestUtils.writeInputStreamToFile(
4921 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4922 getDeviceOwnerPoliciesFile());
4923 DpmTestUtils.writeInputStreamToFile(
4924 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4925 getDeviceOwnerFile());
4926 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4927 }
4928
4929 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4930 setupProfileOwner();
4931 initializeDpms();
4932 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4933 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4934 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4935 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4936 }
4937
4938 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4939 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4940 UserHandle.USER_SYSTEM);
4941 DpmTestUtils.writeInputStreamToFile(
4942 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4943 getProfileOwnerPoliciesFile());
4944 DpmTestUtils.writeInputStreamToFile(
4945 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
4946 getProfileOwnerFile());
4947 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4948 }
4949
4950 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
4951 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4952 UserHandle.USER_SYSTEM);
4953 DpmTestUtils.writeInputStreamToFile(
4954 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4955 getProfileOwnerPoliciesFile());
4956 DpmTestUtils.writeInputStreamToFile(
4957 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4958 getProfileOwnerFile());
4959 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4960 }
4961
4962 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
4963 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4964 UserHandle.USER_SYSTEM);
4965 DpmTestUtils.writeInputStreamToFile(
4966 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4967 getProfileOwnerPoliciesFile());
4968 DpmTestUtils.writeInputStreamToFile(
4969 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4970 getProfileOwnerFile());
4971 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4972 }
4973
Eran Messeribb271892018-10-17 18:27:50 +01004974 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
4975 setupProfileOwner();
4976 configureContextForAccess(mContext, false);
4977
4978 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4979 () -> dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin2,
4980 UserHandle.of(DpmMockContext.CALLER_UID)));
4981 }
4982
4983 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
4984 setupProfileOwner();
4985 configureContextForAccess(mContext, false);
4986
4987 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4988 () -> dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin1,
4989 UserHandle.of(DpmMockContext.CALLER_UID)));
4990 }
4991
4992 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
4993 setupProfileOwner();
4994
4995 // This method will throw if the system context could not call
4996 // setProfileOwnerCanAccessDeviceIds successfully.
4997 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
4998 }
4999
5000 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5001 when(context.spiedContext.checkCallingPermission(
5002 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5003 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5004 : PackageManager.PERMISSION_DENIED);
5005 }
5006
5007 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5008 setupProfileOwner();
5009
5010 final long ident = mServiceContext.binder.clearCallingIdentity();
5011 configureContextForAccess(mServiceContext, true);
5012
5013 mServiceContext.binder.callingUid =
5014 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5015 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5016 try {
5017 runAsCaller(mServiceContext, dpms, dpm -> {
5018 dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin1,
5019 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE));
5020 });
5021 } finally {
5022 mServiceContext.binder.restoreCallingIdentity(ident);
5023 }
5024 }
5025
5026 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5027 throws Exception {
5028 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5029 setupDeviceOwner();
5030 configureContextForAccess(mContext, false);
5031
5032 // Device owner should be allowed to request Device ID attestation.
5033 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5034 DpmMockContext.CALLER_SYSTEM_USER_UID);
5035
5036 // Another package must not be allowed to request Device ID attestation.
5037 assertExpectException(SecurityException.class, null,
5038 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5039 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5040 // Another component that is not the admin must not be allowed to request Device ID
5041 // attestation.
5042 assertExpectException(SecurityException.class, null,
5043 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5044 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5045 }
5046
5047 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5048 throws Exception {
5049 configureContextForAccess(mContext, false);
5050
5051 // Make sure a security exception is thrown if the device has no profile owner.
5052 assertExpectException(SecurityException.class, null,
5053 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5054 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5055
5056 setupProfileOwner();
5057 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5058
5059 // The profile owner is allowed to request Device ID attestation.
5060 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5061 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5062 DpmMockContext.CALLER_UID);
5063 // But not another package.
5064 assertExpectException(SecurityException.class, null,
5065 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5066 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5067 // Or another component which is not the admin.
5068 assertExpectException(SecurityException.class, null,
5069 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5070 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5071 }
5072
5073 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5074 final long ident = mServiceContext.binder.clearCallingIdentity();
5075
5076 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5077 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5078 try {
5079 runAsCaller(mServiceContext, dpms, action);
5080 } finally {
5081 mServiceContext.binder.restoreCallingIdentity(ident);
5082 }
5083 }
5084
5085 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5086 setupProfileOwner();
5087 markDelegatedCertInstallerAsInstalled();
5088
5089 // Configure a delegated cert installer.
5090 runAsCaller(mServiceContext, dpms,
5091 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5092 Arrays.asList(DELEGATION_CERT_INSTALL)));
5093
5094 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5095
5096 // Make sure that the profile owner can still request Device ID attestation.
5097 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5098 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5099 DpmMockContext.CALLER_UID);
5100
5101 runAsDelegatedCertInstaller(dpm -> {
5102 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5103 DpmMockContext.DELEGATE_PACKAGE_NAME,
5104 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5105 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5106 });
5107 }
5108
5109 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5110 throws Exception {
5111 setupProfileOwner();
5112 markDelegatedCertInstallerAsInstalled();
5113
5114 // Configure a delegated cert installer.
5115 runAsCaller(mServiceContext, dpms,
5116 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5117 Arrays.asList(DELEGATION_CERT_INSTALL)));
5118
5119
5120 assertExpectException(SecurityException.class, null,
5121 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5122 admin1.getPackageName(),
5123 DpmMockContext.CALLER_UID));
5124
5125 runAsDelegatedCertInstaller(dpm -> {
5126 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5127 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5128 DpmMockContext.DELEGATE_PACKAGE_NAME,
5129 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5130 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5131 });
5132 }
5133
5134 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5135 final long ident = mServiceContext.binder.clearCallingIdentity();
5136 mServiceContext.binder.callingUid =
5137 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5138 runAsCaller(mServiceContext, dpms, dpm -> {
5139 dpm.setProfileOwnerCanAccessDeviceIdsForUser(who, UserHandle.of(userId));
5140 });
5141 mServiceContext.binder.restoreCallingIdentity(ident);
5142 }
5143
arangelov08d534b2018-01-22 15:20:53 +00005144 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5145 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5146 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5147 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5148
5149 final long ident = mServiceContext.binder.clearCallingIdentity();
5150 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5151 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5152 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5153 // To simulate a reboot, we just reinitialize dpms and call systemReady
5154 initializeDpms();
5155
5156 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5157 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5158 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5159 assertTrue(dpm.isAdminActive(admin1));
5160 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5161 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5162
5163 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5164 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5165 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5166 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5167
5168 mServiceContext.binder.restoreCallingIdentity(ident);
5169 }
5170
5171 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5172 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5173 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5174 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5175
5176 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5177 DpmMockContext.CALLER_SYSTEM_USER_UID);
5178 setUpPackageManagerForAdmin(admin1, uid);
5179 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5180 // To simulate a reboot, we just reinitialize dpms and call systemReady
5181 initializeDpms();
5182
5183 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5184 assertTrue(dpm.isAdminActive(admin1));
5185 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5186 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5187 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5188 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5189 }
5190
5191 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5192 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5193 metadataManager.deleteMetadataFile();
5194
5195 final TransferOwnershipMetadataManager.Metadata metadata =
5196 new TransferOwnershipMetadataManager.Metadata(
5197 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5198 callerUserHandle,
5199 adminType);
5200 metadataManager.saveMetadataFile(metadata);
5201 }
5202
5203 private File getDeviceOwnerFile() {
5204 return dpms.mOwners.getDeviceOwnerFile();
5205 }
5206
5207 private File getProfileOwnerFile() {
5208 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5209 }
5210
5211 private File getProfileOwnerPoliciesFile() {
5212 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5213 DpmMockContext.CALLER_USER_HANDLE);
5214 return getPoliciesFile(parentDir);
5215 }
5216
5217 private File getDeviceOwnerPoliciesFile() {
5218 return getPoliciesFile(getServices().systemUserDataDir);
5219 }
5220
5221 private File getPoliciesFile(File parentDir) {
5222 return new File(parentDir, "device_policies.xml");
5223 }
5224
5225 private InputStream getRawStream(@RawRes int id) {
5226 return mRealTestContext.getResources().openRawResource(id);
5227 }
5228
Victor Chang3e794af2016-03-04 13:48:17 +00005229 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005230 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005231 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5232 dpms.notifyChangeToContentObserver(
5233 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5234 }
5235
5236 private void assertProvisioningAllowed(String action, boolean expected) {
5237 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5238 dpm.isProvisioningAllowed(action));
5239 }
Tony Mak2f26b792016-11-28 17:54:51 +00005240
Nicolas Prevot45d29072017-01-18 16:11:19 +00005241 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5242 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005243 final String previousPackageName = mContext.packageName;
5244 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005245
5246 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5247 mContext.packageName = packageName;
5248 mMockContext.binder.callingUid = uid;
5249 assertProvisioningAllowed(action, expected);
5250
5251 // Set the previous package name / calling uid to go back to the initial state.
5252 mContext.packageName = previousPackageName;
5253 mMockContext.binder.callingUid = previousUid;
5254 }
5255
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005256 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005257 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5258 }
5259
5260 private void assertCheckProvisioningPreCondition(
5261 String action, String packageName, int provisioningCondition) {
5262 assertEquals("checkProvisioningPreCondition("
5263 + action + ", " + packageName + ") returning unexpected result",
5264 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005265 }
5266
Tony Mak2f26b792016-11-28 17:54:51 +00005267 /**
5268 * Setup a managed profile with the specified admin and its uid.
5269 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5270 * @param adminUid uid of the admin package.
5271 * @param copyFromAdmin package information for {@code admin} will be built based on this
5272 * component's information.
5273 */
5274 private void addManagedProfile(
5275 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5276 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005277 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005278 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5279 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5280 dpm.setActiveAdmin(admin, false, userId);
5281 assertTrue(dpm.setProfileOwner(admin, null, userId));
5282 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5283 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005284
5285 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005286 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005287 */
Robin Leeabaa0692017-02-20 20:54:22 +00005288 private static StringParceledListSlice asSlice(String[] s) {
5289 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005290 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005291
5292 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005293 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5294 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005295
Robin Lee2c68dad2017-03-17 12:50:24 +00005296 // We can't let exceptions happen on the background thread. Throw them here if they happen
5297 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005298 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005299 }
Victor Chang3e794af2016-03-04 13:48:17 +00005300}