blob: d2fb1cab347928ae25aef30630aa1e8682258aa5 [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 Onukia31ebbc2015-11-23 17:15:21 -080071import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080072import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070073import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080074import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070075import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070076import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010077import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080078import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010079import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000080import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000081import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000082import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080083import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000084import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010085import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070086import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070087
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010088import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000089import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000090import com.android.server.LocalServices;
91import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000092import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000093import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000094
Robin Lee7f5c91c2017-02-08 21:27:02 +000095import org.hamcrest.BaseMatcher;
96import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -080097import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -070098import org.mockito.invocation.InvocationOnMock;
99import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100
arangelov08d534b2018-01-22 15:20:53 +0000101import java.io.File;
102import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800103import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000104import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000105import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700106import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700108import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100109import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000110import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700112/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700113 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000114 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115 m FrameworksServicesTests &&
116 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000117 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800119 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700120
121 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000122 *
123 * , or:
124 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700125 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000126@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100127@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700128public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000129 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
130 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
131 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100132 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800133 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100134 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000135
Pavel Grafov75c0a892017-05-18 17:28:27 +0100136 // TODO replace all instances of this with explicit {@link #mServiceContext}.
137 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700138 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100139
140 private DpmMockContext mServiceContext;
141 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700142 public DevicePolicyManager dpm;
143 public DevicePolicyManagerServiceTestable dpms;
144
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100145 /*
146 * The CA cert below is the content of cacert.pem as generated by:
147 *
148 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
149 */
150 private static final String TEST_CA =
151 "-----BEGIN CERTIFICATE-----\n" +
152 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
153 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
154 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
155 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
156 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
157 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
158 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
159 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
160 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
161 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
162 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
163 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
164 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
165 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
166 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
167 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
168 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
169 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
170 "wQ==\n" +
171 "-----END CERTIFICATE-----\n";
172
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700173 @Override
174 protected void setUp() throws Exception {
175 super.setUp();
176
177 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100178 mServiceContext = mContext;
179 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
180 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700181 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100182 doReturn(Collections.singletonList(new ResolveInfo()))
183 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
184 any(Intent.class),
185 anyInt(),
186 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700187
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800188 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100189 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800190
Makoto Onukia52562c2015-10-01 16:12:31 -0700191 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700192
Sudheer Shanka101c3532018-01-08 16:28:42 -0800193 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800194 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700195 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
196 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
197 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800198 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700199
Pavel Grafov75c0a892017-05-18 17:28:27 +0100200 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
201 mAdmin1Context.packageName = admin1.getPackageName();
202 mAdmin1Context.applicationInfo = new ApplicationInfo();
203 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
204
Makoto Onukib643fb02015-09-22 15:03:44 -0700205 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700206 }
207
arangelov08d534b2018-01-22 15:20:53 +0000208 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
209 return dpms.mTransferOwnershipMetadataManager;
210 }
211
Robin Lee2c68dad2017-03-17 12:50:24 +0000212 @Override
213 protected void tearDown() throws Exception {
214 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000215 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000216 super.tearDown();
217 }
218
Makoto Onukia52562c2015-10-01 16:12:31 -0700219 private void initializeDpms() {
220 // Need clearCallingIdentity() to pass permission checks.
221 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100222 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700223
Pavel Grafov75c0a892017-05-18 17:28:27 +0100224 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
225 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
226 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700227
Pavel Grafov75c0a892017-05-18 17:28:27 +0100228 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700229
Pavel Grafov75c0a892017-05-18 17:28:27 +0100230 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700231 }
232
Makoto Onukib643fb02015-09-22 15:03:44 -0700233 private void setUpUserManager() {
234 // Emulate UserManager.set/getApplicationRestriction().
235 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
236
237 // UM.setApplicationRestrictions() will save to appRestrictions.
238 doAnswer(new Answer<Void>() {
239 @Override
240 public Void answer(InvocationOnMock invocation) throws Throwable {
241 String pkg = (String) invocation.getArguments()[0];
242 Bundle bundle = (Bundle) invocation.getArguments()[1];
243 UserHandle user = (UserHandle) invocation.getArguments()[2];
244
245 appRestrictions.put(Pair.create(pkg, user), bundle);
246
247 return null;
248 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100249 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100250 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700251
252 // UM.getApplicationRestrictions() will read from appRestrictions.
253 doAnswer(new Answer<Bundle>() {
254 @Override
255 public Bundle answer(InvocationOnMock invocation) throws Throwable {
256 String pkg = (String) invocation.getArguments()[0];
257 UserHandle user = (UserHandle) invocation.getArguments()[1];
258
259 return appRestrictions.get(Pair.create(pkg, user));
260 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100261 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700262 anyString(), any(UserHandle.class));
263
Makoto Onukid932f762015-09-29 16:53:38 -0700264 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100265 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700266 }
267
268 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100269 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700270
Pavel Grafov75c0a892017-05-18 17:28:27 +0100271 mServiceContext.binder.callingUid =
272 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
273 runAsCaller(mServiceContext, dpms, dpm -> {
274 // PO needs to be a DA.
275 dpm.setActiveAdmin(admin, /*replace=*/ false);
276 // Fire!
277 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
278 // Check
279 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
280 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700281
Pavel Grafov75c0a892017-05-18 17:28:27 +0100282 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700283 }
284
285 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100286 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700287 .thenReturn(false);
288
289 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100290 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700291
292 // If the device has no DPMS feature, it shouldn't register the local service.
293 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
294 }
295
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800296 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800297 // Device owner in SYSTEM_USER
298 setDeviceOwner();
299 // Profile owner in CALLER_USER_HANDLE
300 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
301 setAsProfileOwner(admin2);
302 // Active admin in CALLER_USER_HANDLE
303 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
304 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
305 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
306 DpmMockContext.CALLER_USER_HANDLE);
307 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
308 DpmMockContext.CALLER_USER_HANDLE));
309
310 initializeDpms();
311
312 // Verify
313 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800314 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800315 eq(UserHandle.USER_SYSTEM));
316 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800317 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800318 adminAnotherPackage.getPackageName()),
319 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800320 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
321 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
322 }
323
324 public void testLoadAdminData_noAdmins() throws Exception {
325 final int ANOTHER_USER_ID = 15;
326 getServices().addUser(ANOTHER_USER_ID, 0);
327
328 initializeDpms();
329
330 // Verify
331 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
332 null, DpmMockContext.CALLER_USER_HANDLE);
333 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
334 null, ANOTHER_USER_ID);
335 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
336 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800337 }
338
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700339 /**
340 * Caller doesn't have proper permissions.
341 */
342 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700343 // 1. Failure cases.
344
345 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100346 assertExpectException(SecurityException.class, /* messageRegex= */ null,
347 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700348
349 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
350 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100351
352 assertExpectException(SecurityException.class, /* messageRegex= */ null,
353 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700354 }
355
Makoto Onukif76b06a2015-09-22 15:03:44 -0700356 /**
357 * Test for:
358 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800359 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700360 * {@link DevicePolicyManager#isAdminActive}
361 * {@link DevicePolicyManager#isAdminActiveAsUser}
362 * {@link DevicePolicyManager#getActiveAdmins}
363 * {@link DevicePolicyManager#getActiveAdminsAsUser}
364 */
365 public void testSetActiveAdmin() throws Exception {
366 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700367 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
368
Makoto Onukif76b06a2015-09-22 15:03:44 -0700369 // 2. Call the API.
370 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700371
372 // 3. Verify internal calls.
373
374 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700375 verify(mContext.spiedContext).sendBroadcastAsUser(
376 MockUtils.checkIntentAction(
377 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
378 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
379 verify(mContext.spiedContext).sendBroadcastAsUser(
380 MockUtils.checkIntentAction(
381 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700382 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
383
Pavel Grafov75c0a892017-05-18 17:28:27 +0100384 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700385 eq(admin1.getPackageName()),
386 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
387 eq(PackageManager.DONT_KILL_APP),
388 eq(DpmMockContext.CALLER_USER_HANDLE),
389 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700390
Sudheer Shanka101c3532018-01-08 16:28:42 -0800391 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
392 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
393
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700394 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700395
396 // Make sure it's active admin1.
397 assertTrue(dpm.isAdminActive(admin1));
398 assertFalse(dpm.isAdminActive(admin2));
399 assertFalse(dpm.isAdminActive(admin3));
400
401 // But not admin1 for a different user.
402
403 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
404 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
405 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
406
407 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
408 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
409
410 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
411
412 // Next, add one more admin.
413 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700414 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700415 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700416
417 dpm.setActiveAdmin(admin2, /* replace =*/ false);
418
419 // Now we have two admins.
420 assertTrue(dpm.isAdminActive(admin1));
421 assertTrue(dpm.isAdminActive(admin2));
422 assertFalse(dpm.isAdminActive(admin3));
423
424 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
425 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100426 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700427 eq(admin1.getPackageName()),
428 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
429 eq(PackageManager.DONT_KILL_APP),
430 eq(DpmMockContext.CALLER_USER_HANDLE),
431 anyString());
432
Sudheer Shanka101c3532018-01-08 16:28:42 -0800433 // times(2) because it was previously called for admin1 which is in the same package
434 // as admin2.
435 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
436 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
437
Makoto Onukif76b06a2015-09-22 15:03:44 -0700438 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100439 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
440 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700441
442 // 5. Add the same admin1 again with replace, which should succeed.
443 dpm.setActiveAdmin(admin1, /* replace =*/ true);
444
445 // TODO make sure it's replaced.
446
447 // 6. Test getActiveAdmins()
448 List<ComponentName> admins = dpm.getActiveAdmins();
449 assertEquals(2, admins.size());
450 assertEquals(admin1, admins.get(0));
451 assertEquals(admin2, admins.get(1));
452
Sudheer Shanka101c3532018-01-08 16:28:42 -0800453 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
454 // replaced
455 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
456
Makoto Onukif76b06a2015-09-22 15:03:44 -0700457 // Another user has no admins.
458 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
459
460 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
461 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
462
463 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
464 }
465
Makoto Onukid932f762015-09-29 16:53:38 -0700466 public void testSetActiveAdmin_multiUsers() throws Exception {
467
468 final int ANOTHER_USER_ID = 100;
469 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
470
Pavel Grafov75c0a892017-05-18 17:28:27 +0100471 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700472
473 // Set up pacakge manager for the other user.
474 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700475
476 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
477
478 dpm.setActiveAdmin(admin1, /* replace =*/ false);
479
480 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
481 dpm.setActiveAdmin(admin2, /* replace =*/ false);
482
483
484 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
485 assertTrue(dpm.isAdminActive(admin1));
486 assertFalse(dpm.isAdminActive(admin2));
487
488 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
489 assertFalse(dpm.isAdminActive(admin1));
490 assertTrue(dpm.isAdminActive(admin2));
491 }
492
Makoto Onukif76b06a2015-09-22 15:03:44 -0700493 /**
494 * Test for:
495 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800496 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700497 */
498 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
499 // 1. Make sure the caller has proper permissions.
500 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
501
502 dpm.setActiveAdmin(admin1, /* replace =*/ false);
503 assertTrue(dpm.isAdminActive(admin1));
504
505 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100506 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
507 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700508 }
509
510 /**
511 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800512 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
513 * BIND_DEVICE_ADMIN.
514 */
515 public void testSetActiveAdmin_permissionCheck() throws Exception {
516 // 1. Make sure the caller has proper permissions.
517 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
518
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100519 assertExpectException(IllegalArgumentException.class,
520 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
521 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800522 assertFalse(dpm.isAdminActive(adminNoPerm));
523
524 // Change the target API level to MNC. Now it can be set as DA.
525 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
526 VERSION_CODES.M);
527 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
528 assertTrue(dpm.isAdminActive(adminNoPerm));
529
530 // TODO Test the "load from the file" case where DA will still be loaded even without
531 // BIND_DEVICE_ADMIN and target API is N.
532 }
533
534 /**
535 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700536 * {@link DevicePolicyManager#removeActiveAdmin}
537 */
538 public void testRemoveActiveAdmin_SecurityException() {
539 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
540
541 // Add admin.
542
543 dpm.setActiveAdmin(admin1, /* replace =*/ false);
544
545 assertTrue(dpm.isAdminActive(admin1));
546
547 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
548
549 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100550 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
551 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700552
553 // Try to remove active admin with a different caller userid should fail too, without
554 // having MANAGE_DEVICE_ADMINS.
555 mContext.callerPermissions.clear();
556
Makoto Onukid932f762015-09-29 16:53:38 -0700557 // Change the caller, and call into DPMS directly with a different user-id.
558
Makoto Onukif76b06a2015-09-22 15:03:44 -0700559 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100560 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
561 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700562 }
563
564 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800565 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
566 * (because we can't send the remove broadcast).
567 */
568 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
569 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
570
571 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
572
573 // Add admin.
574
575 dpm.setActiveAdmin(admin1, /* replace =*/ false);
576
577 assertTrue(dpm.isAdminActive(admin1));
578
579 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
580
581 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100582 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800583 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100584 assertExpectException(IllegalStateException.class,
585 /* messageRegex= */ "User must be running and unlocked",
586 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800587
588 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800589 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
590 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800591
592 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100593 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800594 .thenReturn(true);
595
596 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700597 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800598 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
599 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800600 }
601
602 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700603 * Test for:
604 * {@link DevicePolicyManager#removeActiveAdmin}
605 */
Makoto Onukid932f762015-09-29 16:53:38 -0700606 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700607 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
608
609 // Add admin1.
610
611 dpm.setActiveAdmin(admin1, /* replace =*/ false);
612
613 assertTrue(dpm.isAdminActive(admin1));
614 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
615
616 // Different user, but should work, because caller has proper permissions.
617 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700618
619 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700620 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700621
622 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700623 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800624 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
625 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700626
627 // TODO DO Still can't be removed in this case.
628 }
629
630 /**
631 * Test for:
632 * {@link DevicePolicyManager#removeActiveAdmin}
633 */
634 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
635 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
636 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
637
638 // Add admin1.
639
640 dpm.setActiveAdmin(admin1, /* replace =*/ false);
641
642 assertTrue(dpm.isAdminActive(admin1));
643 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
644
645 // Broadcast from saveSettingsLocked().
646 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
647 MockUtils.checkIntentAction(
648 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
649 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
650
651 // Remove. No permissions, but same user, so it'll work.
652 mContext.callerPermissions.clear();
653 dpm.removeActiveAdmin(admin1);
654
Makoto Onukif76b06a2015-09-22 15:03:44 -0700655 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
656 MockUtils.checkIntentAction(
657 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
658 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
659 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700660 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700661 eq(dpms.mHandler),
662 eq(Activity.RESULT_OK),
663 isNull(String.class),
664 isNull(Bundle.class));
665
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700666 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800667 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
668 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700669
670 // Again broadcast from saveSettingsLocked().
671 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
672 MockUtils.checkIntentAction(
673 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
674 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
675
676 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700677 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700678
Sudheer Shanka101c3532018-01-08 16:28:42 -0800679 public void testRemoveActiveAdmin_multipleAdminsInUser() {
680 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
681 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
682
683 // Add admin1.
684 dpm.setActiveAdmin(admin1, /* replace =*/ false);
685
686 assertTrue(dpm.isAdminActive(admin1));
687 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
688
689 // Add admin2.
690 dpm.setActiveAdmin(admin2, /* replace =*/ false);
691
692 assertTrue(dpm.isAdminActive(admin2));
693 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
694
695 // Broadcast from saveSettingsLocked().
696 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
697 MockUtils.checkIntentAction(
698 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
699 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
700
701 // Remove. No permissions, but same user, so it'll work.
702 mContext.callerPermissions.clear();
703 dpm.removeActiveAdmin(admin1);
704
705 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
706 MockUtils.checkIntentAction(
707 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
708 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
709 isNull(String.class),
710 any(BroadcastReceiver.class),
711 eq(dpms.mHandler),
712 eq(Activity.RESULT_OK),
713 isNull(String.class),
714 isNull(Bundle.class));
715
716 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
717 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800718 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800719 eq(DpmMockContext.CALLER_USER_HANDLE));
720
721 // Again broadcast from saveSettingsLocked().
722 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
723 MockUtils.checkIntentAction(
724 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
725 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
726 }
727
728 /**
729 * Test for:
730 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
731 */
732 public void testForceRemoveActiveAdmin() throws Exception {
733 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
734
735 // Add admin.
736 setupPackageInPackageManager(admin1.getPackageName(),
737 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
738 /* appId= */ 10138,
739 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
740 dpm.setActiveAdmin(admin1, /* replace =*/ false);
741 assertTrue(dpm.isAdminActive(admin1));
742
743 // Calling from a non-shell uid should fail with a SecurityException
744 mContext.binder.callingUid = 123456;
745 assertExpectException(SecurityException.class,
746 /* messageRegex =*/ "Non-shell user attempted to call",
747 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
748
749 mContext.binder.callingUid = Process.SHELL_UID;
750 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
751
752 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
753 // Verify
754 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
755 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
756 null, DpmMockContext.CALLER_USER_HANDLE);
757 }
758
Makoto Onukib643fb02015-09-22 15:03:44 -0700759 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000760 * Test for: @{link DevicePolicyManager#setActivePasswordState}
761 *
762 * Validates that when the password for a user changes, the notification broadcast intent
763 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
764 * addition to ones in the original user.
765 */
766 public void testSetActivePasswordState_sendToProfiles() throws Exception {
767 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
768
769 final int MANAGED_PROFILE_USER_ID = 78;
770 final int MANAGED_PROFILE_ADMIN_UID =
771 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
772
773 // Setup device owner.
774 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
775 mContext.packageName = admin1.getPackageName();
776 setupDeviceOwner();
777
778 // Add a managed profile belonging to the system user.
779 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
780
781 // Change the parent user's password.
782 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
783
784 // Both the device owner and the managed profile owner should receive this broadcast.
785 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
786 intent.setComponent(admin1);
787 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
788
789 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
790 MockUtils.checkIntent(intent),
791 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
792 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
793 MockUtils.checkIntent(intent),
794 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
795 }
796
797 /**
798 * Test for: @{link DevicePolicyManager#setActivePasswordState}
799 *
800 * Validates that when the password for a managed profile changes, the notification broadcast
801 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
802 * its parent.
803 */
804 public void testSetActivePasswordState_notSentToParent() throws Exception {
805 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
806
807 final int MANAGED_PROFILE_USER_ID = 78;
808 final int MANAGED_PROFILE_ADMIN_UID =
809 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
810
811 // Setup device owner.
812 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
813 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100814 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000815 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
816 setupDeviceOwner();
817
818 // Add a managed profile belonging to the system user.
819 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
820
821 // Change the profile's password.
822 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
823
824 // Both the device owner and the managed profile owner should receive this broadcast.
825 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
826 intent.setComponent(admin1);
827 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
828
829 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
830 MockUtils.checkIntent(intent),
831 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
832 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
833 MockUtils.checkIntent(intent),
834 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
835 }
836 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000837 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700838 */
839 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000840 setDeviceOwner();
841
842 // Try to set a profile owner on the same user, which should fail.
843 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
844 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100845 assertExpectException(IllegalStateException.class,
846 /* messageRegex= */ "already has a device owner",
847 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000848
849 // DO admin can't be deactivated.
850 dpm.removeActiveAdmin(admin1);
851 assertTrue(dpm.isAdminActive(admin1));
852
853 // TODO Test getDeviceOwnerName() too. To do so, we need to change
854 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
855 }
856
857 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700858 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800859 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700860 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
861 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
862
Makoto Onukid932f762015-09-29 16:53:38 -0700863 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
865
Makoto Onukid932f762015-09-29 16:53:38 -0700866 // Make sure admin1 is installed on system user.
867 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700868
Makoto Onukic8a5a552015-11-19 14:29:12 -0800869 // Check various get APIs.
870 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
871
Makoto Onukib643fb02015-09-22 15:03:44 -0700872 // DO needs to be an DA.
873 dpm.setActiveAdmin(admin1, /* replace =*/ false);
874
875 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700876 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700877
Makoto Onukic8a5a552015-11-19 14:29:12 -0800878 // getDeviceOwnerComponent should return the admin1 component.
879 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
880 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
881
882 // Check various get APIs.
883 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
884
885 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
886 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
887 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
888 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
889
890 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
891
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000892 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100893 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000894 eq(admin1.getPackageName()));
895
Makoto Onukib643fb02015-09-22 15:03:44 -0700896 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100897 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700898 eq(UserHandle.USER_SYSTEM), eq(false));
899
900 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
901 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
902 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
903
Makoto Onukic8a5a552015-11-19 14:29:12 -0800904 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700905 }
906
Makoto Onukic8a5a552015-11-19 14:29:12 -0800907 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
908 final int origCallingUser = mContext.binder.callingUid;
909 final List origPermissions = new ArrayList(mContext.callerPermissions);
910 mContext.callerPermissions.clear();
911
912 mContext.callerPermissions.add(permission.MANAGE_USERS);
913
914 mContext.binder.callingUid = Process.SYSTEM_UID;
915
916 // TODO Test getDeviceOwnerName() too. To do so, we need to change
917 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
918 if (hasDeviceOwner) {
919 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
920 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
921 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
922
923 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
924 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
925 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
926 } else {
927 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
928 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
929 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
930
931 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
932 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
933 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
934 }
935
936 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
937 if (hasDeviceOwner) {
938 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
939 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
940 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
941
942 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
943 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
944 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
945 } else {
946 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
947 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
948 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
949
950 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
951 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
952 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
953 }
954
955 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
956 // Still with MANAGE_USERS.
957 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
958 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
959 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
960
961 if (hasDeviceOwner) {
962 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
963 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
964 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
965 } else {
966 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
967 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
968 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
969 }
970
971 mContext.binder.callingUid = Process.SYSTEM_UID;
972 mContext.callerPermissions.remove(permission.MANAGE_USERS);
973 // System can still call "OnAnyUser" without MANAGE_USERS.
974 if (hasDeviceOwner) {
975 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
976 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
977 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
978
979 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
980 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
981 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
982 } else {
983 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
984 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
985 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
986
987 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
988 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
989 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
990 }
991
992 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
993 // Still no MANAGE_USERS.
994 if (hasDeviceOwner) {
995 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
996 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
997 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
998 } else {
999 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1000 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1001 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1002 }
1003
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001004 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1005 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1006 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1007 dpm::getDeviceOwnerComponentOnAnyUser);
1008 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1009 dpm::getDeviceOwnerUserId);
1010 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1011 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001012
1013 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1014 // Still no MANAGE_USERS.
1015 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1016 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1017 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1018
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001019 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1020 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1021 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1022 dpm::getDeviceOwnerComponentOnAnyUser);
1023 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1024 dpm::getDeviceOwnerUserId);
1025 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1026 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001027
1028 // Restore.
1029 mContext.binder.callingUid = origCallingUser;
1030 mContext.callerPermissions.addAll(origPermissions);
1031 }
1032
1033
Makoto Onukib643fb02015-09-22 15:03:44 -07001034 /**
1035 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1036 */
1037 public void testSetDeviceOwner_noSuchPackage() {
1038 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001039 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001040 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1041 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1042
1043 // Call from a process on the system user.
1044 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1045
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001046 assertExpectException(IllegalArgumentException.class,
1047 /* messageRegex= */ "Invalid component",
1048 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001049 }
1050
1051 public void testSetDeviceOwner_failures() throws Exception {
1052 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1053 }
1054
Makoto Onukia52562c2015-10-01 16:12:31 -07001055 public void testClearDeviceOwner() throws Exception {
1056 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001057 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001058 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1059 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1060
1061 // Set admin1 as a DA to the secondary user.
1062 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1063
1064 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1065
1066 // Set admin 1 as the DO to the system user.
1067
1068 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1069 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1070 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1071 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1072
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001073 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001074 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001075 eq(admin1.getPackageName()));
1076
Makoto Onukic8a5a552015-11-19 14:29:12 -08001077 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001078
Makoto Onuki90b89652016-01-28 14:44:18 -08001079 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001080 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001081 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001082
1083 assertTrue(dpm.isAdminActive(admin1));
1084 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1085
Makoto Onukia52562c2015-10-01 16:12:31 -07001086 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001087 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001088
1089 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001090 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1091 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001092
1093 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001094 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001095 assertExpectException(IllegalStateException.class,
1096 /* messageRegex= */ "User must be running and unlocked",
1097 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001098
Pavel Grafov75c0a892017-05-18 17:28:27 +01001099 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1100 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001101 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1102
1103 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001104 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001105
Pavel Grafov75c0a892017-05-18 17:28:27 +01001106 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001107 eq(false),
1108 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1109
Pavel Grafov75c0a892017-05-18 17:28:27 +01001110 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001111 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001112 eq(null),
1113 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001114
Sudheer Shanka101c3532018-01-08 16:28:42 -08001115 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1116 null, UserHandle.USER_SYSTEM);
1117
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001118 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001119
1120 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1121 // and once for clearing it.
1122 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1123 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1124 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001125 // TODO Check other calls.
1126 }
1127
1128 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1129 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001130 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001131 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1132 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1133
1134 // Set admin1 as a DA to the secondary user.
1135 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1136
1137 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1138
1139 // Set admin 1 as the DO to the system user.
1140
1141 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1142 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1143 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1144 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1145
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001146 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001147 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001148 eq(admin1.getPackageName()));
1149
Makoto Onukic8a5a552015-11-19 14:29:12 -08001150 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001151
1152 // Now call clear from the secondary user, which should throw.
1153 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1154
1155 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001156 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001157 eq(admin1.getPackageName()),
1158 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001159 assertExpectException(SecurityException.class,
1160 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1161 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001162
Makoto Onukic8a5a552015-11-19 14:29:12 -08001163 // DO shouldn't be removed.
1164 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001165 }
1166
Makoto Onukib643fb02015-09-22 15:03:44 -07001167 public void testSetProfileOwner() throws Exception {
1168 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001169
Makoto Onuki90b89652016-01-28 14:44:18 -08001170 // PO admin can't be deactivated.
1171 dpm.removeActiveAdmin(admin1);
1172 assertTrue(dpm.isAdminActive(admin1));
1173
Makoto Onuki803d6752015-10-30 12:58:39 -07001174 // Try setting DO on the same user, which should fail.
1175 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001176 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1177 runAsCaller(mServiceContext, dpms, dpm -> {
1178 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001179 assertExpectException(IllegalStateException.class,
1180 /* messageRegex= */ "already has a profile owner",
1181 () -> dpm.setDeviceOwner(admin2, "owner-name",
1182 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001183 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001184 }
1185
Makoto Onuki90b89652016-01-28 14:44:18 -08001186 public void testClearProfileOwner() throws Exception {
1187 setAsProfileOwner(admin1);
1188
1189 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1190
1191 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1192 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1193
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001194 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001195 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001196 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001197 assertExpectException(IllegalStateException.class,
1198 /* messageRegex= */ "User must be running and unlocked",
1199 () -> dpm.clearProfileOwner(admin1));
1200
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001201 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001202 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001203 dpm.clearProfileOwner(admin1);
1204
1205 // Check
1206 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001207 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001208 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1209 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001210 }
1211
Makoto Onukib643fb02015-09-22 15:03:44 -07001212 public void testSetProfileOwner_failures() throws Exception {
1213 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1214 }
1215
Makoto Onukia52562c2015-10-01 16:12:31 -07001216 public void testGetDeviceOwnerAdminLocked() throws Exception {
1217 checkDeviceOwnerWithMultipleDeviceAdmins();
1218 }
1219
1220 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1221 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1222 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1223 // make sure it gets the right component from the right user.
1224
1225 final int ANOTHER_USER_ID = 100;
1226 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1227
Pavel Grafov75c0a892017-05-18 17:28:27 +01001228 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001229
1230 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001231 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001232 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1233 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1234
1235 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1236
Pavel Grafov75c0a892017-05-18 17:28:27 +01001237 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001238
Makoto Onukia52562c2015-10-01 16:12:31 -07001239 // Make sure the admin packge is installed to each user.
1240 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1241 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1242
1243 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1244 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1245
1246 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1247
1248
1249 // Set active admins to the users.
1250 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1251 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1252
1253 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1254 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1255
1256 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1257
1258 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001259 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001260 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1261
Makoto Onukic8a5a552015-11-19 14:29:12 -08001262 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001263
1264 // Then check getDeviceOwnerAdminLocked().
1265 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1266 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1267 }
1268
1269 /**
1270 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001271 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1272 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001273 *
1274 * We didn't use to persist the DO component class name, but now we do, and the above method
1275 * finds the right component from a package name upon migration.
1276 */
1277 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001278 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001279 checkDeviceOwnerWithMultipleDeviceAdmins();
1280
1281 // Overwrite the device owner setting and clears the clas name.
1282 dpms.mOwners.setDeviceOwner(
1283 new ComponentName(admin2.getPackageName(), ""),
1284 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1285 dpms.mOwners.writeDeviceOwner();
1286
1287 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001288 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001289
1290 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001291 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001292 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001293 initializeDpms();
1294
1295 // Now the DO component name is a full name.
1296 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1297 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001298 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001299 }
1300
Makoto Onukib643fb02015-09-22 15:03:44 -07001301 public void testSetGetApplicationRestriction() {
1302 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001303 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001304
1305 {
1306 Bundle rest = new Bundle();
1307 rest.putString("KEY_STRING", "Foo1");
1308 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1309 }
1310
1311 {
1312 Bundle rest = new Bundle();
1313 rest.putString("KEY_STRING", "Foo2");
1314 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1315 }
1316
1317 {
1318 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1319 assertNotNull(returned);
1320 assertEquals(returned.size(), 1);
1321 assertEquals(returned.get("KEY_STRING"), "Foo1");
1322 }
1323
1324 {
1325 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1326 assertNotNull(returned);
1327 assertEquals(returned.size(), 1);
1328 assertEquals(returned.get("KEY_STRING"), "Foo2");
1329 }
1330
1331 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1332 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1333 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001334
Edman Anjosf9946772016-11-28 16:35:15 +01001335 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001336 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1337 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001338 *
1339 * @param packageName the name of the package to be setup
1340 * @param appId the application ID to be given to the package
1341 * @return the UID of the package as known by the mock package manager
1342 */
1343 private int setupPackageInPackageManager(final String packageName, final int appId)
1344 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001345 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001346 ApplicationInfo.FLAG_HAS_CODE);
1347 }
1348
1349 /**
1350 * Setup a package in the package manager mock. Useful for faking installed applications.
1351 *
1352 * @param packageName the name of the package to be setup
1353 * @param userId the user id where the package will be "installed"
1354 * @param appId the application ID to be given to the package
1355 * @param flags flags to set in the ApplicationInfo for this package
1356 * @return the UID of the package as known by the mock package manager
1357 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001358 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1359 int flags) throws Exception {
1360 final int uid = UserHandle.getUid(userId, appId);
1361 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001362 final PackageInfo pi = new PackageInfo();
1363 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001364 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001365 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001366 eq(packageName),
1367 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001368 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001369 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001370 eq(packageName),
1371 anyInt(),
1372 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001373 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001374 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001375 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001376 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001377 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001378 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001379 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001380 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001381 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001382 return uid;
1383 }
1384
Robin Lee7f5c91c2017-02-08 21:27:02 +00001385 public void testCertificateDisclosure() throws Exception {
1386 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1387 final UserHandle user = UserHandle.of(userId);
1388
1389 mContext.applicationInfo = new ApplicationInfo();
1390 mContext.callerPermissions.add(permission.MANAGE_USERS);
1391 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001392 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001393 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1394
Robin Leeabaa0692017-02-20 20:54:22 +00001395 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1396 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001397
1398 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1399 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1400
1401 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001402 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001403 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001404 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001405 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001406 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001407 .cancelAsUser(anyString(), anyInt(), eq(user));
1408
1409 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001410 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001411 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001412 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1413 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001414 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001415 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001416 .notifyAsUser(anyString(), anyInt(), argThat(
1417 new BaseMatcher<Notification>() {
1418 @Override
1419 public boolean matches(Object item) {
1420 final Notification noti = (Notification) item;
1421 return TEST_STRING.equals(
1422 noti.extras.getString(Notification.EXTRA_TITLE));
1423 }
1424 @Override
1425 public void describeTo(Description description) {
1426 description.appendText(
1427 "Notification{title=\"" + TEST_STRING + "\"}");
1428 }
1429 }), eq(user));
1430 }
1431
Edman Anjosf9946772016-11-28 16:35:15 +01001432 /**
1433 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1434 * privileges can acually be exercised by a delegate are not covered here.
1435 */
1436 public void testDelegation() throws Exception {
1437 setAsProfileOwner(admin1);
1438
1439 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1440
1441 // Given two packages
1442 final String CERT_DELEGATE = "com.delegate.certs";
1443 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1444 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1445 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1446 20989);
1447
1448 // On delegation
1449 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1450 mContext.packageName = admin1.getPackageName();
1451 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1452 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1453
1454 // DPMS correctly stores and retrieves the delegates
1455 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1456 assertEquals(2, policy.mDelegationMap.size());
1457 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1458 DELEGATION_CERT_INSTALL);
1459 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1460 DELEGATION_CERT_INSTALL);
1461 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1462 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1463 DELEGATION_APP_RESTRICTIONS);
1464 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1465 DELEGATION_APP_RESTRICTIONS);
1466 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1467
1468 // On calling install certificate APIs from an unauthorized process
1469 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1470 mContext.packageName = RESTRICTIONS_DELEGATE;
1471
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001472 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1473 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001474
1475 // On calling install certificate APIs from an authorized process
1476 mContext.binder.callingUid = CERT_DELEGATE_UID;
1477 mContext.packageName = CERT_DELEGATE;
1478
1479 // DPMS executes without a SecurityException
1480 try {
1481 dpm.installCaCert(null, null);
1482 } catch (SecurityException unexpected) {
1483 fail("Threw SecurityException on authorized access");
1484 } catch (NullPointerException expected) {
1485 }
1486
1487 // On removing a delegate
1488 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1489 mContext.packageName = admin1.getPackageName();
1490 dpm.setCertInstallerPackage(admin1, null);
1491
1492 // DPMS does not allow access to ex-delegate
1493 mContext.binder.callingUid = CERT_DELEGATE_UID;
1494 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001495 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1496 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001497
1498 // But still allows access to other existing delegates
1499 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1500 mContext.packageName = RESTRICTIONS_DELEGATE;
1501 try {
1502 dpm.getApplicationRestrictions(null, "pkg");
1503 } catch (SecurityException expected) {
1504 fail("Threw SecurityException on authorized access");
1505 }
1506 }
1507
Esteban Talaverabf60f722015-12-10 16:26:44 +00001508 public void testApplicationRestrictionsManagingApp() throws Exception {
1509 setAsProfileOwner(admin1);
1510
Rubin Xued1928a2016-02-11 17:23:06 +00001511 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001512 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001513 final String nonDelegateExceptionMessageRegex =
1514 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001515 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001516 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1517 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001518
Esteban Talaverabf60f722015-12-10 16:26:44 +00001519 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1520 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001521 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1522 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001523 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001524 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001525 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001526 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1527 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001528
1529 // Check via the profile owner that no restrictions were set.
1530 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001531 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001532 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1533
Rubin Xued1928a2016-02-11 17:23:06 +00001534 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001535 assertExpectException(PackageManager.NameNotFoundException.class,
1536 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1537 () -> dpm.setApplicationRestrictionsManagingPackage(
1538 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001539
Esteban Talaverabf60f722015-12-10 16:26:44 +00001540 // Let appRestrictionsManagerPackage manage app restrictions
1541 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1542 assertEquals(appRestrictionsManagerPackage,
1543 dpm.getApplicationRestrictionsManagingPackage(admin1));
1544
1545 // Now that package should be able to set and retrieve app restrictions.
1546 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001547 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001548 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1549 dpm.setApplicationRestrictions(null, "pkg1", rest);
1550 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1551 assertEquals(1, returned.size(), 1);
1552 assertEquals("Foo1", returned.get("KEY_STRING"));
1553
1554 // The same app running on a separate user shouldn't be able to manage app restrictions.
1555 mContext.binder.callingUid = UserHandle.getUid(
1556 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1557 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001558 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1559 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001560
1561 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1562 // too.
1563 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001564 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001565 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1566 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1567 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1568
1569 // Removing the ability for the package to manage app restrictions.
1570 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1571 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1572 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001573 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001574 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001575 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1576 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001577 }
1578
Makoto Onukia4f11972015-10-01 13:19:58 -07001579 public void testSetUserRestriction_asDo() throws Exception {
1580 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001581 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001582 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1583 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1584
1585 // First, set DO.
1586
1587 // Call from a process on the system user.
1588 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1589
1590 // Make sure admin1 is installed on system user.
1591 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001592
1593 // Call.
1594 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001595 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001596 UserHandle.USER_SYSTEM));
1597
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001598 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001599 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001600 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001601 DpmTestUtils.assertRestrictions(
1602 DpmTestUtils.newRestrictions(defaultRestrictions),
1603 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1604 );
1605 DpmTestUtils.assertRestrictions(
1606 DpmTestUtils.newRestrictions(defaultRestrictions),
1607 dpm.getUserRestrictions(admin1)
1608 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001609 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001610 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001611 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001612 eq(true) /* isDeviceOwner */,
1613 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001614 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001615 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001616
1617 for (String restriction : defaultRestrictions) {
1618 dpm.clearUserRestriction(admin1, restriction);
1619 }
1620
Esteban Talavera548a04b2016-12-20 15:22:30 +00001621 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001622 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001623
1624 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001625 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001626 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001627 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1628 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001629 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001630
Makoto Onukia4f11972015-10-01 13:19:58 -07001631 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001632 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001633 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001634 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1635 UserManager.DISALLOW_ADD_USER),
1636 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001637 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001638
Makoto Onuki068c54a2015-10-13 14:34:03 -07001639 DpmTestUtils.assertRestrictions(
1640 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001641 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001642 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1643 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001644 DpmTestUtils.assertRestrictions(
1645 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001646 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001647 dpm.getUserRestrictions(admin1)
1648 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001649
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001651 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001652 eq(UserHandle.USER_SYSTEM),
1653 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001654 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001655 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001656
Makoto Onuki068c54a2015-10-13 14:34:03 -07001657 DpmTestUtils.assertRestrictions(
1658 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1659 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1660 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001661 DpmTestUtils.assertRestrictions(
1662 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1663 dpm.getUserRestrictions(admin1)
1664 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001665
1666 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001667 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001668 eq(UserHandle.USER_SYSTEM),
1669 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001670 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001671 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001672
Esteban Talavera548a04b2016-12-20 15:22:30 +00001673 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001674
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001675 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1676 // DO sets them, the scope is global.
1677 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001678 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001679 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001680 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001682 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001683 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1684 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001685 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686
1687 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1688 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001689 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001690
1691 // More tests.
1692 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001693 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001694 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001695 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1696 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001697 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698
1699 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001700 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001701 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001702 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001703 UserManager.DISALLOW_ADD_USER),
1704 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001705 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706
1707 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001708 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001709 eq(UserHandle.USER_SYSTEM),
1710 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001711 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001712 UserManager.DISALLOW_ADD_USER),
1713 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001714 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715
1716 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1717 // locally.
1718 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001719 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720
1721 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1722 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1723 dpm.setCameraDisabled(admin2, true);
1724
Pavel Grafov75c0a892017-05-18 17:28:27 +01001725 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001726 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001727 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001728 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001729 UserManager.DISALLOW_ADD_USER),
1730 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001731 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001732 // TODO Make sure restrictions are written to the file.
1733 }
1734
1735 public void testSetUserRestriction_asPo() {
1736 setAsProfileOwner(admin1);
1737
Makoto Onuki068c54a2015-10-13 14:34:03 -07001738 DpmTestUtils.assertRestrictions(
1739 DpmTestUtils.newRestrictions(),
1740 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1741 .ensureUserRestrictions()
1742 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001743
1744 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001745 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001746 eq(DpmMockContext.CALLER_USER_HANDLE),
1747 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001748 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001749 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001750
Makoto Onukia4f11972015-10-01 13:19:58 -07001751 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001752 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001753 eq(DpmMockContext.CALLER_USER_HANDLE),
1754 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1755 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001756 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001757 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001758
Makoto Onuki068c54a2015-10-13 14:34:03 -07001759 DpmTestUtils.assertRestrictions(
1760 DpmTestUtils.newRestrictions(
1761 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1762 UserManager.DISALLOW_OUTGOING_CALLS
1763 ),
1764 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1765 .ensureUserRestrictions()
1766 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001767 DpmTestUtils.assertRestrictions(
1768 DpmTestUtils.newRestrictions(
1769 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1770 UserManager.DISALLOW_OUTGOING_CALLS
1771 ),
1772 dpm.getUserRestrictions(admin1)
1773 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001774
1775 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001776 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001777 eq(DpmMockContext.CALLER_USER_HANDLE),
1778 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001779 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001780 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001781
1782 DpmTestUtils.assertRestrictions(
1783 DpmTestUtils.newRestrictions(
1784 UserManager.DISALLOW_OUTGOING_CALLS
1785 ),
1786 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1787 .ensureUserRestrictions()
1788 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001789 DpmTestUtils.assertRestrictions(
1790 DpmTestUtils.newRestrictions(
1791 UserManager.DISALLOW_OUTGOING_CALLS
1792 ),
1793 dpm.getUserRestrictions(admin1)
1794 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001795
1796 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001797 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001798 eq(DpmMockContext.CALLER_USER_HANDLE),
1799 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001800 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001801 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001802
Makoto Onuki068c54a2015-10-13 14:34:03 -07001803 DpmTestUtils.assertRestrictions(
1804 DpmTestUtils.newRestrictions(),
1805 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1806 .ensureUserRestrictions()
1807 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001808 DpmTestUtils.assertRestrictions(
1809 DpmTestUtils.newRestrictions(),
1810 dpm.getUserRestrictions(admin1)
1811 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001812
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001813 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1814 // though when DO sets them they'll be applied globally.
1815 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001816 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001817 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001818 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001819 eq(DpmMockContext.CALLER_USER_HANDLE),
1820 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1821 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001822 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001823 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001824
1825 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001826 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001827 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001828 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001829 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001830 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001831 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001832
Makoto Onukia4f11972015-10-01 13:19:58 -07001833 // TODO Make sure restrictions are written to the file.
1834 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001835
Esteban Talavera548a04b2016-12-20 15:22:30 +00001836
1837 public void testDefaultEnabledUserRestrictions() throws Exception {
1838 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1839 mContext.callerPermissions.add(permission.MANAGE_USERS);
1840 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1841 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1842
1843 // First, set DO.
1844
1845 // Call from a process on the system user.
1846 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1847
1848 // Make sure admin1 is installed on system user.
1849 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1850
1851 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1852 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1853 UserHandle.USER_SYSTEM));
1854
1855 // Check that the user restrictions that are enabled by default are set. Then unset them.
1856 String[] defaultRestrictions = UserRestrictionsUtils
1857 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1858 assertTrue(defaultRestrictions.length > 0);
1859 DpmTestUtils.assertRestrictions(
1860 DpmTestUtils.newRestrictions(defaultRestrictions),
1861 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1862 );
1863 DpmTestUtils.assertRestrictions(
1864 DpmTestUtils.newRestrictions(defaultRestrictions),
1865 dpm.getUserRestrictions(admin1)
1866 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001867 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001868 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001869 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001870 eq(true) /* isDeviceOwner */,
1871 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001872 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001873 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001874
1875 for (String restriction : defaultRestrictions) {
1876 dpm.clearUserRestriction(admin1, restriction);
1877 }
1878
1879 assertNoDeviceOwnerRestrictions();
1880
1881 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001882 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001883 initializeDpms();
1884 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1885 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1886
1887 assertNoDeviceOwnerRestrictions();
1888
1889 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1890 // is set as it wasn't enabled during setDeviceOwner.
1891 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1892 assertFalse(UserRestrictionsUtils
1893 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1894 UserRestrictionsUtils
1895 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1896 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001897 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001898 initializeDpms();
1899 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1900 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1901
1902 DpmTestUtils.assertRestrictions(
1903 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1904 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1905 );
1906 DpmTestUtils.assertRestrictions(
1907 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1908 dpm.getUserRestrictions(admin1)
1909 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001910 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001911 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001912 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001913 eq(true) /* isDeviceOwner */,
1914 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001915 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001916 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001917
1918 // Remove the restriction.
1919 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1920
1921 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1922 initializeDpms();
1923 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1924 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1925 assertNoDeviceOwnerRestrictions();
1926 } finally {
1927 UserRestrictionsUtils
1928 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1929 }
1930 }
1931
1932 private void assertNoDeviceOwnerRestrictions() {
1933 DpmTestUtils.assertRestrictions(
1934 DpmTestUtils.newRestrictions(),
1935 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1936 );
1937 DpmTestUtils.assertRestrictions(
1938 DpmTestUtils.newRestrictions(),
1939 dpm.getUserRestrictions(admin1)
1940 );
1941 }
1942
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001943 public void testGetMacAddress() throws Exception {
1944 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1945 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1946 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1947
1948 // In this test, change the caller user to "system".
1949 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1950
1951 // Make sure admin1 is installed on system user.
1952 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1953
1954 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001955 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1956 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001957
1958 // DO needs to be an DA.
1959 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1960 assertTrue(dpm.isAdminActive(admin1));
1961
1962 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001963 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1964 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001965
1966 // Test 3. Caller has PO, but not DO.
1967 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001968 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1969 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001970
1971 // Remove PO.
1972 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001973 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001974 // Test 4, Caller is DO now.
1975 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1976
1977 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001978 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001979
1980 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001981 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001982 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001983
1984 // 4-3. With a real MAC address.
1985 final WifiInfo wi = new WifiInfo();
1986 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001987 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001988 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001989 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001990
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001991 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001992 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1993 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1994
1995 // In this test, change the caller user to "system".
1996 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1997
1998 // Make sure admin1 is installed on system user.
1999 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2000
2001 // Set admin1 as DA.
2002 dpm.setActiveAdmin(admin1, false);
2003 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002004 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2005 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002006
2007 // Set admin1 as PO.
2008 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002009 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2010 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002011
2012 // Remove PO and add DO.
2013 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002014 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002015 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2016
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002017 // admin1 is DO.
2018 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002019 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002020 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002021 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2022 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002023
2024 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002025 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002026 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002027 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2028 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002029
2030 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002031 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002032 dpm.reboot(admin1);
2033 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002034
2035 public void testSetGetSupportText() {
2036 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2037 dpm.setActiveAdmin(admin1, true);
2038 dpm.setActiveAdmin(admin2, true);
2039 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2040
2041 // Null default support messages.
2042 {
2043 assertNull(dpm.getLongSupportMessage(admin1));
2044 assertNull(dpm.getShortSupportMessage(admin1));
2045 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2046 assertNull(dpm.getShortSupportMessageForUser(admin1,
2047 DpmMockContext.CALLER_USER_HANDLE));
2048 assertNull(dpm.getLongSupportMessageForUser(admin1,
2049 DpmMockContext.CALLER_USER_HANDLE));
2050 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2051 }
2052
2053 // Only system can call the per user versions.
2054 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002055 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2056 () -> dpm.getShortSupportMessageForUser(admin1,
2057 DpmMockContext.CALLER_USER_HANDLE));
2058 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2059 () -> dpm.getLongSupportMessageForUser(admin1,
2060 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002061 }
2062
2063 // Can't set message for admin in another uid.
2064 {
2065 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002066 assertExpectException(SecurityException.class,
2067 /* messageRegex= */ "is not owned by uid",
2068 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002069 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2070 }
2071
2072 // Set/Get short returns what it sets and other admins text isn't changed.
2073 {
2074 final String supportText = "Some text to test with.";
2075 dpm.setShortSupportMessage(admin1, supportText);
2076 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2077 assertNull(dpm.getLongSupportMessage(admin1));
2078 assertNull(dpm.getShortSupportMessage(admin2));
2079
2080 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2081 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2082 DpmMockContext.CALLER_USER_HANDLE));
2083 assertNull(dpm.getShortSupportMessageForUser(admin2,
2084 DpmMockContext.CALLER_USER_HANDLE));
2085 assertNull(dpm.getLongSupportMessageForUser(admin1,
2086 DpmMockContext.CALLER_USER_HANDLE));
2087 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2088
2089 dpm.setShortSupportMessage(admin1, null);
2090 assertNull(dpm.getShortSupportMessage(admin1));
2091 }
2092
2093 // Set/Get long returns what it sets and other admins text isn't changed.
2094 {
2095 final String supportText = "Some text to test with.\nWith more text.";
2096 dpm.setLongSupportMessage(admin1, supportText);
2097 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2098 assertNull(dpm.getShortSupportMessage(admin1));
2099 assertNull(dpm.getLongSupportMessage(admin2));
2100
2101 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2102 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2103 DpmMockContext.CALLER_USER_HANDLE));
2104 assertNull(dpm.getLongSupportMessageForUser(admin2,
2105 DpmMockContext.CALLER_USER_HANDLE));
2106 assertNull(dpm.getShortSupportMessageForUser(admin1,
2107 DpmMockContext.CALLER_USER_HANDLE));
2108 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2109
2110 dpm.setLongSupportMessage(admin1, null);
2111 assertNull(dpm.getLongSupportMessage(admin1));
2112 }
2113 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002114
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002115 public void testSetGetMeteredDataDisabled() throws Exception {
2116 setAsProfileOwner(admin1);
2117
2118 final ArrayList<String> emptyList = new ArrayList<>();
2119 assertEquals(emptyList, dpm.getMeteredDataDisabled(admin1));
2120
2121 // Setup
2122 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2123 final String package1 = "com.example.one";
2124 final String package2 = "com.example.two";
2125 pkgsToRestrict.add(package1);
2126 pkgsToRestrict.add(package2);
2127 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2128 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
2129 List<String> excludedPkgs = dpm.setMeteredDataDisabled(admin1, pkgsToRestrict);
2130
2131 // Verify
2132 assertEquals(emptyList, excludedPkgs);
2133 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabled(admin1));
2134 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2135 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2136 eq(DpmMockContext.CALLER_USER_HANDLE));
2137
2138 // Setup
2139 pkgsToRestrict.remove(package1);
2140 excludedPkgs = dpm.setMeteredDataDisabled(admin1, pkgsToRestrict);
2141
2142 // Verify
2143 assertEquals(emptyList, excludedPkgs);
2144 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabled(admin1));
2145 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2146 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2147 eq(DpmMockContext.CALLER_USER_HANDLE));
2148 }
2149
2150 public void testSetGetMeteredDataDisabled_deviceAdmin() {
2151 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2152 dpm.setActiveAdmin(admin1, true);
2153 assertTrue(dpm.isAdminActive(admin1));
2154 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2155
2156 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
2157 () -> dpm.setMeteredDataDisabled(admin1, new ArrayList<>()));
2158 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
2159 () -> dpm.getMeteredDataDisabled(admin1));
2160 }
2161
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002162 public void testGetMeteredDataDisabledForUser() throws Exception {
2163 setAsProfileOwner(admin1);
2164
2165 // Setup
2166 final ArrayList<String> emptyList = new ArrayList<>();
2167 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2168 final String package1 = "com.example.one";
2169 final String package2 = "com.example.two";
2170 final String package3 = "com.example.three";
2171 pkgsToRestrict.add(package1);
2172 pkgsToRestrict.add(package2);
2173 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2174 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
2175 List<String> excludedPkgs = dpm.setMeteredDataDisabled(admin1, pkgsToRestrict);
2176
2177 // Verify
2178 assertEquals(emptyList, excludedPkgs);
2179 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2180 assertTrue(package1 + "should be restricted",
2181 dpm.isMeteredDataDisabledForUser(admin1, package1,
2182 DpmMockContext.CALLER_USER_HANDLE));
2183 assertTrue(package2 + "should be restricted",
2184 dpm.isMeteredDataDisabledForUser(admin1, package2,
2185 DpmMockContext.CALLER_USER_HANDLE));
2186 assertFalse(package3 + "should not be restricted",
2187 dpm.isMeteredDataDisabledForUser(admin1, package3,
2188 DpmMockContext.CALLER_USER_HANDLE));
2189 }
2190
2191 public void testGetMeteredDataDisabledForUser_nonSystemUidCaller() throws Exception {
2192 setAsProfileOwner(admin1);
2193 assertExpectException(SecurityException.class,
2194 /* messageRegex= */ "Only the system can query restricted pkgs",
2195 () -> dpm.isMeteredDataDisabledForUser(
2196 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2197 dpm.clearProfileOwner(admin1);
2198
2199 setDeviceOwner();
2200 assertExpectException(SecurityException.class,
2201 /* messageRegex= */ "Only the system can query restricted pkgs",
2202 () -> dpm.isMeteredDataDisabledForUser(
2203 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2204 clearDeviceOwner();
2205 }
2206
phweiss73145f42017-01-17 19:06:38 +01002207 public void testCreateAdminSupportIntent() throws Exception {
2208 // Setup device owner.
2209 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2210 setupDeviceOwner();
2211
2212 // Nonexisting permission returns null
2213 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2214 assertNull(intent);
2215
2216 // Existing permission that is not set returns null
2217 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2218 assertNull(intent);
2219
2220 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002221 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002222 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2223 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2224 .thenReturn(true);
2225 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2226 assertNull(intent);
2227
2228 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002229 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002230 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2231 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2232 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2233 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2234 assertNotNull(intent);
2235 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2236 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2237 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002238 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002239 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2240 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2241
Lenka Trochtova16a91c02018-01-17 11:03:30 +01002242 // Try with POLICY_DISABLE_CAMERA, POLICY_DISABLE_SCREEN_CAPTURE and
2243 // POLICY_MANDATORY_BACKUPS, which are not user restrictions
phweiss73145f42017-01-17 19:06:38 +01002244
2245 // Camera is not disabled
2246 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2247 assertNull(intent);
2248
2249 // Camera is disabled
2250 dpm.setCameraDisabled(admin1, true);
2251 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2252 assertNotNull(intent);
2253 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2254 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2255
2256 // Screen capture is not disabled
2257 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2258 assertNull(intent);
2259
2260 // Screen capture is disabled
2261 dpm.setScreenCaptureDisabled(admin1, true);
2262 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2263 assertNotNull(intent);
2264 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2265 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2266
Lenka Trochtova16a91c02018-01-17 11:03:30 +01002267 // Backups are not mandatory
2268 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_MANDATORY_BACKUPS);
2269 assertNull(intent);
2270
2271 // Backups are mandatory
2272 ComponentName transportComponent = ComponentName.unflattenFromString(
2273 "android/com.android.internal.backup.LocalTransport");
2274 dpm.setMandatoryBackupTransport(admin1, transportComponent);
2275 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_MANDATORY_BACKUPS);
2276 assertNotNull(intent);
2277 assertEquals(DevicePolicyManager.POLICY_MANDATORY_BACKUPS,
2278 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2279
phweiss73145f42017-01-17 19:06:38 +01002280 // Same checks for different user
2281 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2282 // Camera should be disabled by device owner
2283 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2284 assertNotNull(intent);
2285 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2286 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2287 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2288 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2289 // ScreenCapture should not be disabled by device owner
2290 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2291 assertNull(intent);
2292 }
2293
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002294 /**
2295 * Test for:
2296 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002297 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002298 * {@link DevicePolicyManager#isAffiliatedUser}
2299 */
2300 public void testUserAffiliation() throws Exception {
2301 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2302 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2303 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2304
2305 // Check that the system user is unaffiliated.
2306 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2307 assertFalse(dpm.isAffiliatedUser());
2308
2309 // Set a device owner on the system user. Check that the system user becomes affiliated.
2310 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2311 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2312 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2313 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002314 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002315
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002316 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002317 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2318 setAsProfileOwner(admin2);
2319 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002320 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002321
2322 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2323 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002324 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002325 userAffiliationIds.add("red");
2326 userAffiliationIds.add("green");
2327 userAffiliationIds.add("blue");
2328 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002329 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002330 assertFalse(dpm.isAffiliatedUser());
2331
2332 // Have the device owner specify a set of affiliation ids that do not intersect with those
2333 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002334 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002335 deviceAffiliationIds.add("cyan");
2336 deviceAffiliationIds.add("yellow");
2337 deviceAffiliationIds.add("magenta");
2338 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2339 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002340 MoreAsserts.assertContentsInAnyOrder(
2341 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002342 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2343 assertFalse(dpm.isAffiliatedUser());
2344
2345 // Have the profile owner specify a set of affiliation ids that intersect with those
2346 // specified by the device owner. Check that the test user becomes affiliated.
2347 userAffiliationIds.add("yellow");
2348 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002349 MoreAsserts.assertContentsInAnyOrder(
2350 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002351 assertTrue(dpm.isAffiliatedUser());
2352
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002353 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002354 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002355 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002356 assertFalse(dpm.isAffiliatedUser());
2357
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002358 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2359 dpm.setAffiliationIds(admin2, userAffiliationIds);
2360 assertTrue(dpm.isAffiliatedUser());
2361 dpm.clearProfileOwner(admin2);
2362 assertFalse(dpm.isAffiliatedUser());
2363
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002364 // Check that the system user remains affiliated.
2365 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2366 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002367
2368 // Clear the device owner - the user becomes unaffiliated.
2369 clearDeviceOwner();
2370 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002371 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002372
2373 public void testGetUserProvisioningState_defaultResult() {
2374 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2375 }
2376
2377 public void testSetUserProvisioningState_permission() throws Exception {
2378 setupProfileOwner();
2379 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2380
2381 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2382 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2383 }
2384
2385 public void testSetUserProvisioningState_unprivileged() throws Exception {
2386 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002387 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2388 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2389 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002390 }
2391
2392 public void testSetUserProvisioningState_noManagement() {
2393 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002394 assertExpectException(IllegalStateException.class,
2395 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2396 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2397 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002398 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2399 }
2400
2401 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2402 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2403 setupDeviceOwner();
2404 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2405
2406 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2407 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2408 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2409 }
2410
2411 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2412 throws Exception {
2413 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2414 setupDeviceOwner();
2415 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2416
2417 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2418 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2419 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2420 }
2421
2422 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2423 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2424 setupDeviceOwner();
2425 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2426
2427 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2428 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2429 }
2430
2431 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2432 throws Exception {
2433 setupProfileOwner();
2434 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2435
2436 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2437 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2438 DevicePolicyManager.STATE_USER_UNMANAGED);
2439 }
2440
2441 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2442 throws Exception {
2443 setupProfileOwner();
2444 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2445
2446 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2447 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2448 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2449 }
2450
2451 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2452 setupProfileOwner();
2453 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2454
2455 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2456 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2457 }
2458
2459 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2460 setupProfileOwner();
2461 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2462
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002463 assertExpectException(IllegalStateException.class,
2464 /* messageRegex= */ "Cannot move to user provisioning state",
2465 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2466 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2467 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002468 }
2469
2470 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2471 throws Exception {
2472 setupProfileOwner();
2473 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2474
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002475 assertExpectException(IllegalStateException.class,
2476 /* messageRegex= */ "Cannot move to user provisioning state",
2477 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2478 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2479 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002480 }
2481
2482 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2483 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2484 for (int state : states) {
2485 dpm.setUserProvisioningState(state, userId);
2486 assertEquals(state, dpm.getUserProvisioningState());
2487 }
2488 }
2489
2490 private void setupProfileOwner() throws Exception {
2491 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2492
2493 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2494 dpm.setActiveAdmin(admin1, false);
2495 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2496
2497 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2498 }
2499
2500 private void setupDeviceOwner() throws Exception {
2501 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2502
2503 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2504 dpm.setActiveAdmin(admin1, false);
2505 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2506
2507 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2508 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002509
2510 public void testSetMaximumTimeToLock() {
2511 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2512
2513 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2514 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2515
Pavel Grafov75c0a892017-05-18 17:28:27 +01002516 reset(getServices().powerManagerInternal);
2517 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002518
2519 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002520 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2521 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002522 reset(getServices().powerManagerInternal);
2523 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002524
2525 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002526 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2527 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002528 reset(getServices().powerManagerInternal);
2529 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002530
2531 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002532 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2533 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002534 reset(getServices().powerManagerInternal);
2535 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002536
2537 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002538 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2539 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002540 reset(getServices().powerManagerInternal);
2541 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002542
2543 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002544 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2545 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002546 reset(getServices().powerManagerInternal);
2547 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002548
2549 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002550 reset(getServices().powerManagerInternal);
2551 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002552
Pavel Grafov28939982017-10-03 15:11:52 +01002553 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2554 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2555 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002556 reset(getServices().powerManagerInternal);
2557 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002558
2559 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002560 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2561 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002562 reset(getServices().powerManagerInternal);
2563 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002564
Pavel Grafov28939982017-10-03 15:11:52 +01002565 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002566 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002567 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2568 verifyStayOnWhilePluggedCleared(false);
2569 }
2570
2571 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2572 // uses separate challenge.
2573 public void testSetMaximumTimeToLockProfile() throws Exception {
2574 final int PROFILE_USER = 15;
2575 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2576 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2577 mContext.binder.callingUid = PROFILE_ADMIN;
2578 final DevicePolicyManagerInternal dpmi =
2579 LocalServices.getService(DevicePolicyManagerInternal.class);
2580
2581 dpm.setMaximumTimeToLock(admin1, 0);
2582
2583 reset(getServices().powerManagerInternal);
2584 reset(getServices().settings);
2585
2586 // First add timeout for the profile.
2587 dpm.setMaximumTimeToLock(admin1, 10);
2588 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2589
2590 reset(getServices().powerManagerInternal);
2591 reset(getServices().settings);
2592
2593 // Add separate challenge
2594 when(getServices().lockPatternUtils
2595 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2596 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2597
2598 verifyScreenTimeoutCall(10L, PROFILE_USER);
2599 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2600
2601 reset(getServices().powerManagerInternal);
2602 reset(getServices().settings);
2603
2604 // Remove the timeout.
2605 dpm.setMaximumTimeToLock(admin1, 0);
2606 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2607 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2608
2609 reset(getServices().powerManagerInternal);
2610 reset(getServices().settings);
2611
2612 // Add it back.
2613 dpm.setMaximumTimeToLock(admin1, 10);
2614 verifyScreenTimeoutCall(10L, PROFILE_USER);
2615 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2616
2617 reset(getServices().powerManagerInternal);
2618 reset(getServices().settings);
2619
2620 // Remove separate challenge.
2621 reset(getServices().lockPatternUtils);
2622 when(getServices().lockPatternUtils
2623 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2624 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2625
2626 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2627 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2628
2629 reset(getServices().powerManagerInternal);
2630 reset(getServices().settings);
2631
2632 // Remove the timeout.
2633 dpm.setMaximumTimeToLock(admin1, 0);
2634 verifyScreenTimeoutCall(null, PROFILE_USER);
2635 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002636 }
2637
Michal Karpinski943aabd2016-10-06 11:09:25 +01002638 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2639 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2640 setupDeviceOwner();
2641 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2642
Michal Karpinskid084ca52017-01-18 15:54:18 +00002643 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2644 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2645 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2646 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2647 - ONE_MINUTE;
2648
2649 // verify that the minimum timeout cannot be modified on user builds (system property is
2650 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002651 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002652
2653 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2654 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2655 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2656
Pavel Grafov75c0a892017-05-18 17:28:27 +01002657 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002658
2659 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002660 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002661
Michal Karpinskid084ca52017-01-18 15:54:18 +00002662 // reset to default (0 means the admin is not participating, so default should be returned)
2663 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002664
2665 // aggregation should be the default if unset by any admin
2666 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2667 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2668
2669 // admin not participating by default
2670 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2671
2672 //clamping from the top
2673 dpm.setRequiredStrongAuthTimeout(admin1,
2674 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2675 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2676 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2677 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2678 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2679
Michal Karpinskid084ca52017-01-18 15:54:18 +00002680 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002681 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2682 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2683 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2684 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2685
2686 // clamping from the bottom
2687 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2688 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2689 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2690
Michal Karpinskid084ca52017-01-18 15:54:18 +00002691 // values within range
2692 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2693 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2694 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2695
2696 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2697 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2698 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002699
2700 // reset to default
2701 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2702 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2703 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2704 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2705
2706 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002707 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2708 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002709 }
2710
Pavel Grafov28939982017-10-03 15:11:52 +01002711 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002712 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002713 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002714 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002715 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002716 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002717 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002718 }
Pavel Grafov28939982017-10-03 15:11:52 +01002719 }
2720
2721 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002722 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2723 // UnfinishedVerificationException.
2724 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002725
Esteban Talavera01576862016-12-15 11:16:44 +00002726 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002727 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002728 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002729 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002730 .thenReturn(false);
2731 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002732 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2733 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002734 .thenReturn(true);
2735 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2736
2737 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002738 }
Victor Chang3e794af2016-03-04 13:48:17 +00002739
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002740 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2741 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002742 mContext.packageName = admin1.getPackageName();
2743 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002744 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2745 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2746 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2747 false);
2748 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2749 }
2750
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002751 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2752 setup_DeviceAdminFeatureOff();
2753 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2754 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2755 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2756 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2757 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2758 assertCheckProvisioningPreCondition(
2759 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2760 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2761 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2762 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2763 }
2764
Esteban Talavera01576862016-12-15 11:16:44 +00002765 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002766 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002767 .thenReturn(false);
2768 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002769 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2770 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002771 .thenReturn(true);
2772 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2773
2774 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002775 }
Victor Chang3e794af2016-03-04 13:48:17 +00002776
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002777 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2778 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002779 mContext.packageName = admin1.getPackageName();
2780 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
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 false);
2785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2786
2787 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002788 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002789 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2790 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2791 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2792 true);
2793 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2794 }
2795
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002796 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2797 setup_ManagedProfileFeatureOff();
2798 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2799 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2800 DevicePolicyManager.CODE_OK);
2801 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2802 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2803 assertCheckProvisioningPreCondition(
2804 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2805 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2806 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2807 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2808
2809 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002810 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002811 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2812 DevicePolicyManager.CODE_OK);
2813 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2814 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2815 assertCheckProvisioningPreCondition(
2816 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2817 DevicePolicyManager.CODE_OK);
2818 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2819 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2820 }
2821
Esteban Talavera01576862016-12-15 11:16:44 +00002822 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002823 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002824 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002825 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2826 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002827 .thenReturn(true);
2828 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2829
2830 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002831 }
Victor Chang3e794af2016-03-04 13:48:17 +00002832
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002833 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2834 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002835 mContext.packageName = admin1.getPackageName();
2836 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002837 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2838 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2839 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2840 false /* because of non-split user */);
2841 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2842 false /* because of non-split user */);
2843 }
2844
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002845 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002846 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002847 setup_nonSplitUser_firstBoot_primaryUser();
2848 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2849 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2850 DevicePolicyManager.CODE_OK);
2851 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2852 DevicePolicyManager.CODE_OK);
2853 assertCheckProvisioningPreCondition(
2854 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2855 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2856 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2857 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2858 }
2859
Esteban Talavera01576862016-12-15 11:16:44 +00002860 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002861 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002862 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002863 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2864 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002865 .thenReturn(true);
2866 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2867
2868 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002869 }
Victor Chang3e794af2016-03-04 13:48:17 +00002870
Nicolas Prevot45d29072017-01-18 16:11:19 +00002871 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2872 setDeviceOwner();
2873 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2874 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2875 }
2876
2877 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2878 setup_nonSplitUser_withDo_primaryUser();
2879 final int MANAGED_PROFILE_USER_ID = 18;
2880 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2881 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002882 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002883 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002884 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002885 true)).thenReturn(true);
2886 }
2887
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002888 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2889 throws Exception {
2890 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002891 mContext.packageName = admin1.getPackageName();
2892 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002893 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2894 false/* because of completed device setup */);
2895 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2896 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2897 false/* because of non-split user */);
2898 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2899 false/* because of non-split user */);
2900 }
2901
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002902 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2903 throws Exception {
2904 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2905 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2906 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2907 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2908 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2909 DevicePolicyManager.CODE_OK);
2910 assertCheckProvisioningPreCondition(
2911 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2912 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2913 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2914 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2915 }
2916
Nicolas Prevot45d29072017-01-18 16:11:19 +00002917 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2918 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002919 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002920 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2921
2922 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2923 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002924 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002925
2926 // COMP mode is allowed.
2927 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2928 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002929 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002930
Nicolas Prevot45d29072017-01-18 16:11:19 +00002931 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002932 assertCheckProvisioningPreCondition(
2933 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002934 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002935 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002936 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2937 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2938 }
Esteban Talavera01576862016-12-15 11:16:44 +00002939
Nicolas Prevot45d29072017-01-18 16:11:19 +00002940 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2941 setup_nonSplitUser_withDo_primaryUser();
2942 mContext.packageName = admin1.getPackageName();
2943 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2944 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2945 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002946 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002947 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2948 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2949 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002950 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002951 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2952 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2953 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2954 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2955 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002956 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002957 assertCheckProvisioningPreCondition(
2958 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002959 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002960 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002961 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2962 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2963 }
Esteban Talavera01576862016-12-15 11:16:44 +00002964
Nicolas Prevot45d29072017-01-18 16:11:19 +00002965 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2966 throws Exception {
2967 setup_nonSplitUser_withDo_primaryUser();
2968 mContext.packageName = admin1.getPackageName();
2969 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002970 // The DO should not be allowed to initiate provisioning if the restriction is set by
2971 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002972 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002973 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2974 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2975 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002976 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002977 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2978 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2979 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2980 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2981 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002982 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2983
2984 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002985 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002986 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002987 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002988 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2989 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2990 }
2991
2992 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2993 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2994 mContext.packageName = admin1.getPackageName();
2995 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2996
2997 // We can delete the managed profile to create a new one, so provisioning is allowed.
2998 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2999 DevicePolicyManager.CODE_OK);
3000 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3001 assertCheckProvisioningPreCondition(
3002 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3003 DpmMockContext.ANOTHER_PACKAGE_NAME,
3004 DevicePolicyManager.CODE_OK);
3005 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3006 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3007 }
3008
3009 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3010 throws Exception {
3011 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3012 mContext.packageName = admin1.getPackageName();
3013 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003014 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003015 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3016 eq(UserHandle.SYSTEM)))
3017 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003018 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003019 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3020 eq(UserHandle.SYSTEM)))
3021 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003022
3023 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003024 assertCheckProvisioningPreCondition(
3025 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3026 DpmMockContext.ANOTHER_PACKAGE_NAME,
3027 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3028 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3029 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003030
3031 // But the device owner can still do it because it has set the restriction itself.
3032 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3033 DevicePolicyManager.CODE_OK);
3034 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003035 }
3036
3037 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003038 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003039 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003040 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3041 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003042 .thenReturn(false);
3043 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3044
3045 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003046 }
Victor Chang3e794af2016-03-04 13:48:17 +00003047
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003048 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3049 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003050 mContext.packageName = admin1.getPackageName();
3051 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003052 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3053 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3054 false /* because canAddMoreManagedProfiles returns false */);
3055 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3056 true);
3057 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3058 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003059 }
3060
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003061 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3062 throws Exception {
3063 setup_splitUser_firstBoot_systemUser();
3064 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3065 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3066 DevicePolicyManager.CODE_OK);
3067 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003068 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003069 assertCheckProvisioningPreCondition(
3070 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3071 DevicePolicyManager.CODE_OK);
3072 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3073 DevicePolicyManager.CODE_SYSTEM_USER);
3074 }
3075
Esteban Talavera01576862016-12-15 11:16:44 +00003076 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003077 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003078 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003079 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3080 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003081 .thenReturn(false);
3082 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3083
3084 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003085 }
Victor Chang3e794af2016-03-04 13:48:17 +00003086
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003087 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3088 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003089 mContext.packageName = admin1.getPackageName();
3090 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003091 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3092 true/* it's undefined behavior. Can be changed into false in the future */);
3093 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3094 false /* because canAddMoreManagedProfiles returns false */);
3095 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3096 true/* it's undefined behavior. Can be changed into false in the future */);
3097 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3098 false/* because calling uid is system user */);
3099 }
3100
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003101 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3102 throws Exception {
3103 setup_splitUser_afterDeviceSetup_systemUser();
3104 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3105 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3106 DevicePolicyManager.CODE_OK);
3107 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003108 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003109 assertCheckProvisioningPreCondition(
3110 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3111 DevicePolicyManager.CODE_OK);
3112 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3113 DevicePolicyManager.CODE_SYSTEM_USER);
3114 }
3115
Esteban Talavera01576862016-12-15 11:16:44 +00003116 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003117 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003118 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003119 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3120 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003121 true)).thenReturn(true);
3122 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3123
3124 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003125 }
Victor Chang3e794af2016-03-04 13:48:17 +00003126
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003127 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3128 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003129 mContext.packageName = admin1.getPackageName();
3130 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003131 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3132 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3133 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3134 true);
3135 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003136 }
3137
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003138 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003139 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003140 setup_splitUser_firstBoot_primaryUser();
3141 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3142 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3143 DevicePolicyManager.CODE_OK);
3144 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3145 DevicePolicyManager.CODE_OK);
3146 assertCheckProvisioningPreCondition(
3147 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3148 DevicePolicyManager.CODE_OK);
3149 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3150 DevicePolicyManager.CODE_OK);
3151 }
3152
Esteban Talavera01576862016-12-15 11:16:44 +00003153 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003154 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003155 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003156 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3157 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003158 true)).thenReturn(true);
3159 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3160
3161 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003162 }
Victor Chang3e794af2016-03-04 13:48:17 +00003163
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003164 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3165 throws Exception {
3166 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003167 mContext.packageName = admin1.getPackageName();
3168 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003169 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3170 true/* it's undefined behavior. Can be changed into false in the future */);
3171 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3172 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3173 true/* it's undefined behavior. Can be changed into false in the future */);
3174 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3175 false/* because user setup completed */);
3176 }
3177
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003178 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003179 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003180 setup_splitUser_afterDeviceSetup_primaryUser();
3181 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3182 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3183 DevicePolicyManager.CODE_OK);
3184 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3185 DevicePolicyManager.CODE_OK);
3186 assertCheckProvisioningPreCondition(
3187 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3188 DevicePolicyManager.CODE_OK);
3189 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3190 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3191 }
3192
Esteban Talavera01576862016-12-15 11:16:44 +00003193 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003194 setDeviceOwner();
3195
Pavel Grafov75c0a892017-05-18 17:28:27 +01003196 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003197 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003198 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3199 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003200 .thenReturn(false);
3201 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3202
3203 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003204 }
Victor Chang3e794af2016-03-04 13:48:17 +00003205
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003206 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3207 throws Exception {
3208 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003209 mContext.packageName = admin1.getPackageName();
3210 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003211 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3212 false /* can't provision managed profile on system user */);
3213 }
3214
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003215 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003216 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003217 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3218 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3219 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3220 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3221 }
3222
3223 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003224 setDeviceOwner();
3225
Pavel Grafov75c0a892017-05-18 17:28:27 +01003226 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003227 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003228 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3229 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003230 true)).thenReturn(true);
3231 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3232
3233 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003234 }
Victor Chang3e794af2016-03-04 13:48:17 +00003235
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003236 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3237 throws Exception {
3238 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003239 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3240 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003241 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3242 }
3243
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003244 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003245 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003246 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3247 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003248
3249 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003250 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3251 DevicePolicyManager.CODE_OK);
3252 }
3253
3254 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003255 setDeviceOwner();
3256
Pavel Grafov75c0a892017-05-18 17:28:27 +01003257 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003258 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003259 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3260 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003261 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3262 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003263 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003264 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003265 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003266 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003267 true)).thenReturn(true);
3268 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3269
3270 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003271 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003272
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003273 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3274 throws Exception {
3275 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003276 mContext.packageName = admin1.getPackageName();
3277 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003278 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3279 }
3280
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003281 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3282 throws Exception {
3283 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3284 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3285 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3286 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3287 }
3288
3289 public void testCheckProvisioningPreCondition_permission() {
3290 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003291 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3292 () -> dpm.checkProvisioningPreCondition(
3293 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003294 }
3295
Victor Chang3577ed22016-08-25 18:49:26 +01003296 public void testForceUpdateUserSetupComplete_permission() {
3297 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
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_systemUser() {
3303 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3304 // GIVEN calling from user 20
3305 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003306 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3307 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003308 }
3309
3310 public void testForceUpdateUserSetupComplete_userbuild() {
3311 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3312 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3313
3314 final int userId = UserHandle.USER_SYSTEM;
3315 // GIVEN userComplete is false in SettingsProvider
3316 setUserSetupCompleteForUser(false, userId);
3317
3318 // GIVEN userComplete is true in DPM
3319 DevicePolicyManagerService.DevicePolicyData userData =
3320 new DevicePolicyManagerService.DevicePolicyData(userId);
3321 userData.mUserSetupComplete = true;
3322 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3323
3324 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003325 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003326
3327 assertTrue(dpms.hasUserSetupCompleted());
3328
3329 dpm.forceUpdateUserSetupComplete();
3330
3331 // THEN the state in dpms is not changed
3332 assertTrue(dpms.hasUserSetupCompleted());
3333 }
3334
3335 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3336 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3337 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3338
3339 final int userId = UserHandle.USER_SYSTEM;
3340 // GIVEN userComplete is false in SettingsProvider
3341 setUserSetupCompleteForUser(false, userId);
3342
3343 // GIVEN userComplete is true in DPM
3344 DevicePolicyManagerService.DevicePolicyData userData =
3345 new DevicePolicyManagerService.DevicePolicyData(userId);
3346 userData.mUserSetupComplete = true;
3347 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3348
3349 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003350 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003351
3352 assertTrue(dpms.hasUserSetupCompleted());
3353
3354 dpm.forceUpdateUserSetupComplete();
3355
3356 // THEN the state in dpms is not changed
3357 assertFalse(dpms.hasUserSetupCompleted());
3358 }
3359
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003360 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003361 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003362 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003363
3364 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3365 runAsCaller(mAdmin1Context, dpms, dpm -> {
3366 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3367 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003368 }
3369
3370 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3371 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3372 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003373
3374 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3375 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003376 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003377 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3378 .thenReturn(true);
3379
3380 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003381 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003382
3383 // Enabling logging should not change the timestamp.
3384 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003385 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003386 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003387 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003388 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003389 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003390
3391 // Retrieving the logs should update the timestamp.
3392 final long beforeRetrieval = System.currentTimeMillis();
3393 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003394 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003395 final long afterRetrieval = System.currentTimeMillis();
3396 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3397 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3398
3399 // Retrieving the pre-boot logs should update the timestamp.
3400 Thread.sleep(2);
3401 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003402 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003403 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3404
3405 // Checking the timestamp again should not change it.
3406 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003407 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003408
3409 // Retrieving the logs again should update the timestamp.
3410 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003411 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003412 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3413
3414 // Disabling logging should not change the timestamp.
3415 Thread.sleep(2);
3416 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003417 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003418
3419 // Restarting the DPMS should not lose the timestamp.
3420 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003421 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003422
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003423 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3424 mContext.binder.callingUid = 1234567;
3425 mContext.callerPermissions.add(permission.MANAGE_USERS);
3426 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3427 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3428
3429 // System can retrieve the timestamp.
3430 mContext.binder.clearCallingIdentity();
3431 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3432
3433 // Removing the device owner should clear the timestamp.
3434 clearDeviceOwner();
3435 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003436 }
3437
yuemingw0de748d2017-11-15 19:22:27 +00003438 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3439 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3440 setupDeviceOwner();
3441 assertExpectException(SecurityException.class, null, () ->
3442 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3443 }
3444
3445 public void testSetSystemSettingFailWithPO() throws Exception {
3446 setupProfileOwner();
3447 assertExpectException(SecurityException.class, null, () ->
3448 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"));
3449 }
3450
3451 public void testSetSystemSetting() throws Exception {
3452 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3453 setupDeviceOwner();
3454 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3455 verify(getServices().settings).settingsSystemPutString(
3456 Settings.System.SCREEN_BRIGHTNESS, "0");
3457 }
3458
yuemingwe43cdf72017-10-12 16:52:11 +01003459 public void testSetTime() throws Exception {
3460 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3461 setupDeviceOwner();
3462 dpm.setTime(admin1, 0);
3463 verify(getServices().alarmManager).setTime(0);
3464 }
3465
3466 public void testSetTimeFailWithPO() throws Exception {
3467 setupProfileOwner();
3468 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3469 }
3470
3471 public void testSetTimeWithAutoTimeOn() throws Exception {
3472 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3473 setupDeviceOwner();
3474 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3475 .thenReturn(1);
3476 assertFalse(dpm.setTime(admin1, 0));
3477 }
3478
3479 public void testSetTimeZone() throws Exception {
3480 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3481 setupDeviceOwner();
3482 dpm.setTimeZone(admin1, "Asia/Shanghai");
3483 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3484 }
3485
3486 public void testSetTimeZoneFailWithPO() throws Exception {
3487 setupProfileOwner();
3488 assertExpectException(SecurityException.class, null,
3489 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3490 }
3491
3492 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3493 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3494 setupDeviceOwner();
3495 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3496 .thenReturn(1);
3497 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3498 }
3499
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003500 public void testGetLastBugReportRequestTime() throws Exception {
3501 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3502 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003503
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003504 mContext.packageName = admin1.getPackageName();
3505 mContext.applicationInfo = new ApplicationInfo();
3506 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3507 .thenReturn(Color.WHITE);
3508 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3509 anyObject())).thenReturn(Color.WHITE);
3510
Esteban Talaverad36dd152016-12-15 08:51:45 +00003511 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3512 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003513 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003514
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003515 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003516 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003517
3518 // Requesting a bug report should update the timestamp.
3519 final long beforeRequest = System.currentTimeMillis();
3520 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003521 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003522 final long afterRequest = System.currentTimeMillis();
3523 assertTrue(bugReportRequestTime >= beforeRequest);
3524 assertTrue(bugReportRequestTime <= afterRequest);
3525
3526 // Checking the timestamp again should not change it.
3527 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003528 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003529
3530 // Restarting the DPMS should not lose the timestamp.
3531 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003532 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003533
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003534 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3535 mContext.binder.callingUid = 1234567;
3536 mContext.callerPermissions.add(permission.MANAGE_USERS);
3537 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3538 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3539
3540 // System can retrieve the timestamp.
3541 mContext.binder.clearCallingIdentity();
3542 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3543
3544 // Removing the device owner should clear the timestamp.
3545 clearDeviceOwner();
3546 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003547 }
3548
3549 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3550 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3551 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003552 mContext.packageName = admin1.getPackageName();
3553 mContext.applicationInfo = new ApplicationInfo();
3554 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3555 .thenReturn(Color.WHITE);
3556 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3557 anyObject())).thenReturn(Color.WHITE);
3558
3559 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3560 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003561 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003562 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003563 .thenReturn(true);
3564
3565 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003566 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003567
3568 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3569 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003570 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003571
3572 // Enabling logging should not change the timestamp.
3573 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003574 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003575
3576 // Retrieving the logs should update the timestamp.
3577 final long beforeRetrieval = System.currentTimeMillis();
3578 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003579 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003580 final long afterRetrieval = System.currentTimeMillis();
3581 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3582 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3583
3584 // Checking the timestamp again should not change it.
3585 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003586 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003587
3588 // Retrieving the logs again should update the timestamp.
3589 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003590 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003591 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3592
3593 // Disabling logging should not change the timestamp.
3594 Thread.sleep(2);
3595 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003596 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003597
3598 // Restarting the DPMS should not lose the timestamp.
3599 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003600 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3601
3602 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3603 mContext.binder.callingUid = 1234567;
3604 mContext.callerPermissions.add(permission.MANAGE_USERS);
3605 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3606 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3607
3608 // System can retrieve the timestamp.
3609 mContext.binder.clearCallingIdentity();
3610 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3611
3612 // Removing the device owner should clear the timestamp.
3613 clearDeviceOwner();
3614 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003615 }
3616
Tony Mak2f26b792016-11-28 17:54:51 +00003617 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3618 // Setup device owner.
3619 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3620 setupDeviceOwner();
3621
3622 // Only device owner is setup, the result list should be empty.
3623 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3624 MoreAsserts.assertEmpty(targetUsers);
3625
3626 // Setup a managed profile managed by the same admin.
3627 final int MANAGED_PROFILE_USER_ID = 15;
3628 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3629 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3630
3631 // Add a secondary user, it should never talk with.
3632 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003633 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003634
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003635 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3636 // other.
3637 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3638 MoreAsserts.assertEmpty(targetUsers);
3639
3640 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3641 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3642 MoreAsserts.assertEmpty(targetUsers);
3643
3644 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003645 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003646 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3647 dpm.setAffiliationIds(admin1, userAffiliationIds);
3648
3649 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3650 dpm.setAffiliationIds(admin1, userAffiliationIds);
3651
Tony Mak2f26b792016-11-28 17:54:51 +00003652 // Calling from device owner admin, the result list should just contain the managed
3653 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003654 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003655 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3656 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3657
3658 // Calling from managed profile admin, the result list should just contain the system
3659 // user id.
3660 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3661 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3662 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003663
3664 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003665 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003666
3667 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3668 // to each other.
3669 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3670 MoreAsserts.assertEmpty(targetUsers);
3671
3672 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3673 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3674 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003675 }
3676
3677 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3678 // Setup a device owner.
3679 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3680 setupDeviceOwner();
3681
3682 // Set up a managed profile managed by different package.
3683 final int MANAGED_PROFILE_USER_ID = 15;
3684 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3685 final ComponentName adminDifferentPackage =
3686 new ComponentName("another.package", "whatever.class");
3687 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3688
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003689 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003690 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003691 dpm.setAffiliationIds(admin1, userAffiliationIds);
3692
3693 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3694 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3695
Tony Mak2f26b792016-11-28 17:54:51 +00003696 // Calling from device owner admin, we should get zero bind device admin target users as
3697 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003698 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003699 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3700 MoreAsserts.assertEmpty(targetUsers);
3701
3702 // Calling from managed profile admin, we should still get zero target users for the same
3703 // reason.
3704 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3705 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3706 MoreAsserts.assertEmpty(targetUsers);
3707 }
3708
Jason Parks3c13b642017-11-28 15:39:43 -06003709 private void verifyLockTaskState(int userId) throws Exception {
3710 verifyLockTaskState(userId, new String[0], DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
3711 }
3712
3713 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3714 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
3715 verify(getServices().iactivityManager).updateLockTaskFeatures(userId, flags);
3716 }
3717
3718 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3719 int flags) throws Exception {
3720 mContext.binder.callingUid = uid;
3721 dpm.setLockTaskPackages(who, packages);
3722 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3723 for (String p : packages) {
3724 assertTrue(dpm.isLockTaskPermitted(p));
3725 }
3726 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3727 // Test to see if set lock task features can be set
3728 dpm.setLockTaskFeatures(who, flags);
3729 verifyLockTaskState(userId, packages, flags);
3730 }
3731
3732 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3733 int flags) throws Exception {
3734 mContext.binder.callingUid = uid;
3735 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3736 () -> dpm.setLockTaskPackages(who, packages));
3737 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3738 () -> dpm.getLockTaskPackages(who));
3739 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3740 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3741 () -> dpm.setLockTaskFeatures(who, flags));
3742 }
3743
Charles Hee078db72017-10-19 18:03:20 +01003744 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003745 // Setup a device owner.
3746 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3747 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003748 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003749 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003750
3751 // Set up a managed profile managed by different package (package name shouldn't matter)
3752 final int MANAGED_PROFILE_USER_ID = 15;
3753 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3754 final ComponentName adminDifferentPackage =
3755 new ComponentName("another.package", "whatever.class");
3756 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003757 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3758
3759 // Setup a PO on the secondary user
3760 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3761 setAsProfileOwner(admin3);
3762 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003763
3764 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003765 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003766 final int flags = 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 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3770
3771 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3772 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003773 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3774 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003775 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003776
3777 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3778 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3779 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003780 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003781 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3782 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003783 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003784
3785 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003786 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003787 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3788 dpm.setAffiliationIds(admin1, userAffiliationIds);
3789
3790 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3791 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3792
3793 // Now the managed profile can set lock task packages.
3794 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3795 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3796 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3797 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003798 // And it can set lock task features.
3799 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003800 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003801
3802 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003803 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003804 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3805 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003806 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3807 MANAGED_PROFILE_USER_ID, new String[0]);
3808 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3809 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003810
Jason Parks3c13b642017-11-28 15:39:43 -06003811 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003812 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3813 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003814
3815 }
3816
3817 public void testLockTaskPolicyForProfileOwner() throws Exception {
3818 // Setup a PO
3819 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3820 setAsProfileOwner(admin1);
3821 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3822
3823 final String[] poPackages = {"poPackage1", "poPackage2"};
3824 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003825 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3826 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003827 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3828 poPackages, poFlags);
3829
3830 // Set up a managed profile managed by different package (package name shouldn't matter)
3831 final int MANAGED_PROFILE_USER_ID = 15;
3832 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3833 final ComponentName adminDifferentPackage =
3834 new ComponentName("another.package", "whatever.class");
3835 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3836 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3837
3838 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3839 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3840 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3841 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003842 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3843 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003844 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003845 }
3846
Benjamin Franzcaffa772018-02-05 16:36:10 +00003847 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3848 // Setup a device owner.
3849 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3850 setupDeviceOwner();
3851 // Lock task policy is updated when loading user data.
3852 verifyLockTaskState(UserHandle.USER_SYSTEM);
3853
3854 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3855 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3856 assertExpectException(IllegalArgumentException.class,
3857 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3858 () -> dpm.setLockTaskFeatures(admin1, flags));
3859 }
3860
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003861 public void testIsDeviceManaged() throws Exception {
3862 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3863 setupDeviceOwner();
3864
3865 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3866 // find out that the device has a device owner.
3867 assertTrue(dpm.isDeviceManaged());
3868 mContext.binder.callingUid = 1234567;
3869 mContext.callerPermissions.add(permission.MANAGE_USERS);
3870 assertTrue(dpm.isDeviceManaged());
3871 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3872 mContext.binder.clearCallingIdentity();
3873 assertTrue(dpm.isDeviceManaged());
3874
3875 clearDeviceOwner();
3876
3877 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3878 // not have a device owner.
3879 mContext.binder.callingUid = 1234567;
3880 mContext.callerPermissions.add(permission.MANAGE_USERS);
3881 assertFalse(dpm.isDeviceManaged());
3882 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3883 mContext.binder.clearCallingIdentity();
3884 assertFalse(dpm.isDeviceManaged());
3885 }
3886
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003887 public void testDeviceOwnerOrganizationName() throws Exception {
3888 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3889 setupDeviceOwner();
3890
3891 dpm.setOrganizationName(admin1, "organization");
3892
3893 // Device owner can retrieve organization managing the device.
3894 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3895
3896 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3897 mContext.binder.callingUid = 1234567;
3898 mContext.callerPermissions.add(permission.MANAGE_USERS);
3899 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3900 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3901
3902 // System can retrieve organization managing the device.
3903 mContext.binder.clearCallingIdentity();
3904 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3905
3906 // Removing the device owner clears the organization managing the device.
3907 clearDeviceOwner();
3908 assertNull(dpm.getDeviceOwnerOrganizationName());
3909 }
3910
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003911 public void testWipeDataManagedProfile() throws Exception {
3912 final int MANAGED_PROFILE_USER_ID = 15;
3913 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3914 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3915 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3916
3917 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003918 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003919 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003920 // Get mock reason string since we throw an IAE with empty string input.
3921 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3922 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003923
3924 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003925 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003926 MANAGED_PROFILE_USER_ID);
3927 }
3928
3929 public void testWipeDataManagedProfileDisallowed() throws Exception {
3930 final int MANAGED_PROFILE_USER_ID = 15;
3931 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3932 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3933
3934 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003935 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003936 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3937
Pavel Grafov75c0a892017-05-18 17:28:27 +01003938 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003939 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3940 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3941 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003942 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3943 thenReturn("Just a test string.");
3944
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003945 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003946 // The PO is not allowed to remove the profile if the user restriction was set on the
3947 // profile by the system
3948 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3949 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003950 }
3951
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003952 public void testWipeDataDeviceOwner() throws Exception {
3953 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003954 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003955 UserManager.DISALLOW_FACTORY_RESET,
3956 UserHandle.SYSTEM))
3957 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003958 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3959 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003960
3961 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003962 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003963 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3964 /*wipeEuicc=*/ eq(false));
3965 }
3966
3967 public void testWipeEuiccDataEnabled() throws Exception {
3968 setDeviceOwner();
3969 when(getServices().userManager.getUserRestrictionSource(
3970 UserManager.DISALLOW_FACTORY_RESET,
3971 UserHandle.SYSTEM))
3972 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003973 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3974 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003975
3976 dpm.wipeData(WIPE_EUICC);
3977 verify(getServices().recoverySystem).rebootWipeUserData(
3978 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3979 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003980 }
3981
3982 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3983 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003984 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003985 UserManager.DISALLOW_FACTORY_RESET,
3986 UserHandle.SYSTEM))
3987 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003988 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3989 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003990 // The DO is not allowed to wipe the device if the user restriction was set
3991 // by the system
3992 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3993 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003994 }
3995
3996 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3997 final int MANAGED_PROFILE_USER_ID = 15;
3998 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3999 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4000
4001 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004002 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004003 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4004
Pavel Grafov75c0a892017-05-18 17:28:27 +01004005 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004006 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4007 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4008 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4009
4010 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4011 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4012
4013 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4014 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4015 // Failed password attempts on the parent user are taken into account, as there isn't a
4016 // separate work challenge.
4017 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4018 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4019 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4020
4021 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4022 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004023 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004024 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004025 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004026 }
4027
4028 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4029 throws Exception {
4030 final int MANAGED_PROFILE_USER_ID = 15;
4031 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4032 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4033
4034 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004035 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004036 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4037
Pavel Grafov75c0a892017-05-18 17:28:27 +01004038 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004039 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4040 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4041 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4042
4043 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4044 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4045
4046 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4047 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4048 // Failed password attempts on the parent user are taken into account, as there isn't a
4049 // separate work challenge.
4050 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4051 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4052 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4053
4054 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4055 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004056 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004057 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004058 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004059 }
4060
4061 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4062 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004063 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004064 UserManager.DISALLOW_FACTORY_RESET,
4065 UserHandle.SYSTEM))
4066 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4067
4068 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4069
4070 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4071 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4072 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4073 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4074 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4075
4076 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4077 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004078 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004079 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4080 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004081 }
4082
4083 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4084 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004085 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004086 UserManager.DISALLOW_FACTORY_RESET,
4087 UserHandle.SYSTEM))
4088 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4089
4090 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4091
4092 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4093 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4094 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4095 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4096 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4097
4098 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004099 verifyZeroInteractions(getServices().recoverySystem);
4100 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004101 .removeUserEvenWhenDisallowed(anyInt());
4102 }
4103
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004104 public void testGetPermissionGrantState() throws Exception {
4105 final String permission = "some.permission";
4106 final String app1 = "com.example.app1";
4107 final String app2 = "com.example.app2";
4108
Pavel Grafov75c0a892017-05-18 17:28:27 +01004109 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004110 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004111 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004112 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004113 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004114 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4115 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004116 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004117 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004118 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004119 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004120 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004121 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4122
4123 // System can retrieve permission grant state.
4124 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004125 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004126 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4127 dpm.getPermissionGrantState(null, app1, permission));
4128 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4129 dpm.getPermissionGrantState(null, app2, permission));
4130
4131 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004132 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4133 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004134 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4135 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004136
4137 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004138 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4139 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004140 setAsProfileOwner(admin1);
4141 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4142 dpm.getPermissionGrantState(admin1, app1, permission));
4143 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4144 dpm.getPermissionGrantState(admin1, app2, permission));
4145 }
4146
Rubin Xuaab7a412016-12-30 21:13:29 +00004147 public void testResetPasswordWithToken() throws Exception {
4148 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4149 setupDeviceOwner();
4150 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004151 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4152 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4153
Rubin Xuaab7a412016-12-30 21:13:29 +00004154 // test adding a token
4155 final byte[] token = new byte[32];
4156 final long handle = 123456;
4157 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01004158 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004159 .thenReturn(handle);
4160 assertTrue(dpm.setResetPasswordToken(admin1, token));
4161
4162 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004163 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004164 .thenReturn(true);
4165 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4166
4167 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004168 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01004169 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
4170 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004171 eq(UserHandle.USER_SYSTEM)))
4172 .thenReturn(true);
4173 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4174
4175 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004176 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004177 .thenReturn(true);
4178 assertTrue(dpm.clearResetPasswordToken(admin1));
4179 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004180
Alexandru-Andrei Rotaru7f31bb02017-09-07 16:29:48 +01004181 public void testSetPasswordBlacklistCannotBeCalledByNonAdmin() throws Exception {
4182 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4183 () -> dpm.setPasswordBlacklist(admin1, null, null));
4184 verifyZeroInteractions(getServices().passwordBlacklist);
4185 }
4186
4187 public void testClearingPasswordBlacklistDoesNotCreateNewBlacklist() throws Exception {
4188 setupProfileOwner();
4189 dpm.setPasswordBlacklist(admin1, null, null);
4190 verifyZeroInteractions(getServices().passwordBlacklist);
4191 }
4192
4193 public void testSetPasswordBlacklistCreatesNewBlacklist() throws Exception {
4194 final String name = "myblacklist";
4195 final List<String> explicit = Arrays.asList("password", "letmein");
4196 setupProfileOwner();
4197 dpm.setPasswordBlacklist(admin1, name, explicit);
4198 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, explicit);
4199 }
4200
4201 public void testSetPasswordBlacklistOnlyConvertsExplicitToLowerCase() throws Exception {
4202 final List<String> mixedCase = Arrays.asList("password", "LETMEIN", "FooTBAll");
4203 final List<String> lowerCase = Arrays.asList("password", "letmein", "football");
4204 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4205 setupDeviceOwner();
4206 final String name = "Name of the Blacklist";
4207 dpm.setPasswordBlacklist(admin1, name, mixedCase);
4208 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, lowerCase);
4209 }
4210
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004211 public void testIsActivePasswordSufficient() throws Exception {
4212 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4213 mContext.packageName = admin1.getPackageName();
4214 setupDeviceOwner();
4215
4216 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4217 dpm.setPasswordMinimumLength(admin1, 8);
4218 dpm.setPasswordMinimumLetters(admin1, 6);
4219 dpm.setPasswordMinimumLowerCase(admin1, 3);
4220 dpm.setPasswordMinimumUpperCase(admin1, 1);
4221 dpm.setPasswordMinimumNonLetter(admin1, 1);
4222 dpm.setPasswordMinimumNumeric(admin1, 1);
4223 dpm.setPasswordMinimumSymbols(admin1, 0);
4224
Rubin Xucc391c22018-01-02 20:37:35 +00004225 reset(mContext.spiedContext);
4226
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004227 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4228 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4229 8, 2,
4230 6, 1,
4231 0, 1);
4232
4233 setActivePasswordState(passwordMetricsNoSymbols);
4234 assertTrue(dpm.isActivePasswordSufficient());
4235
4236 initializeDpms();
4237 reset(mContext.spiedContext);
4238 assertTrue(dpm.isActivePasswordSufficient());
4239
4240 // This call simulates the user entering the password for the first time after a reboot.
4241 // This causes password metrics to be reloaded into memory. Until this happens,
4242 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4243 // even if the DPC changes password requirements so that the password no longer meets the
4244 // requirements. This is a known limitation of the current implementation of
4245 // isActivePasswordSufficient() - see b/34218769.
4246 setActivePasswordState(passwordMetricsNoSymbols);
4247 assertTrue(dpm.isActivePasswordSufficient());
4248
4249 dpm.setPasswordMinimumSymbols(admin1, 1);
4250 // This assertion would fail if we had not called setActivePasswordState() again after
4251 // initializeDpms() - see previous comment.
4252 assertFalse(dpm.isActivePasswordSufficient());
4253
4254 initializeDpms();
4255 reset(mContext.spiedContext);
4256 assertFalse(dpm.isActivePasswordSufficient());
4257
4258 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4259 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4260 7, 2,
4261 5, 1,
4262 1, 2);
4263
4264 setActivePasswordState(passwordMetricsWithSymbols);
4265 assertTrue(dpm.isActivePasswordSufficient());
4266 }
4267
Pavel Grafov75c0a892017-05-18 17:28:27 +01004268 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4269 throws Exception {
4270 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004271 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004272
Pavel Grafov75c0a892017-05-18 17:28:27 +01004273 dpm.setActivePasswordState(passwordMetrics, userHandle);
4274 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004275
Rubin Xucc391c22018-01-02 20:37:35 +00004276 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4277 // reportPasswordChanged()
4278 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
4279 MockUtils.checkIntentAction(
4280 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4281 MockUtils.checkUserHandle(userHandle));
4282
Pavel Grafov75c0a892017-05-18 17:28:27 +01004283 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4284 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004285 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004286
4287 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4288 MockUtils.checkIntent(intent),
4289 MockUtils.checkUserHandle(userHandle));
4290
4291 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4292 // let it finish with system uid, otherwise it will throw and crash.
4293 flushTasks();
4294
4295 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004296 }
4297
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004298 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4299 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4300 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4301 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4302 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4303 DpmMockContext.SYSTEM_UID);
4304 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4305 DpmMockContext.SYSTEM_UID);
4306
4307 // Set up a device owner.
4308 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004309 setupDeviceOwner();
4310
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004311 // First and second user set IMEs manually.
4312 mContext.binder.callingUid = firstUserSystemUid;
4313 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4314 mContext.binder.callingUid = secondUserSystemUid;
4315 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004316
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004317 // Device owner changes IME for first user.
4318 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004319 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004320 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004321 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004322 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004323 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004324 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004325 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4326 mContext.binder.callingUid = firstUserSystemUid;
4327 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4328 mContext.binder.callingUid = secondUserSystemUid;
4329 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004330
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004331 // Second user changes IME manually.
4332 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4333 mContext.binder.callingUid = firstUserSystemUid;
4334 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4335 mContext.binder.callingUid = secondUserSystemUid;
4336 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004337
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004338 // First user changes IME manually.
4339 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4340 mContext.binder.callingUid = firstUserSystemUid;
4341 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4342 mContext.binder.callingUid = secondUserSystemUid;
4343 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004344
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004345 // Device owner changes IME for first user again.
4346 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004347 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004348 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004349 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004350 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004351 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004352 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4353 mContext.binder.callingUid = firstUserSystemUid;
4354 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4355 mContext.binder.callingUid = secondUserSystemUid;
4356 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004357
4358 // Restarting the DPMS should not lose information.
4359 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004360 mContext.binder.callingUid = firstUserSystemUid;
4361 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4362 mContext.binder.callingUid = secondUserSystemUid;
4363 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004364
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004365 // Device owner can find out whether it set the current IME itself.
4366 mContext.binder.callingUid = deviceOwnerUid;
4367 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004368
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004369 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004370 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004371 mContext.binder.callingUid = firstUserSystemUid;
4372 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4373 mContext.binder.callingUid = secondUserSystemUid;
4374 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004375 }
4376
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004377 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4378 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4379 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4380 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4381 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4382 DpmMockContext.SYSTEM_UID);
4383 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4384 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004385
4386 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004387 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004388 setupProfileOwner();
4389
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004390 // First and second user set IMEs manually.
4391 mContext.binder.callingUid = firstUserSystemUid;
4392 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4393 mContext.binder.callingUid = secondUserSystemUid;
4394 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004395
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004396 // Profile owner changes IME for second user.
4397 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004398 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004399 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004400 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004401 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004402 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004403 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004404 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4405 mContext.binder.callingUid = firstUserSystemUid;
4406 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4407 mContext.binder.callingUid = secondUserSystemUid;
4408 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004409
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004410 // First user changes IME manually.
4411 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4412 mContext.binder.callingUid = firstUserSystemUid;
4413 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4414 mContext.binder.callingUid = secondUserSystemUid;
4415 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004416
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004417 // Second user changes IME manually.
4418 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4419 mContext.binder.callingUid = firstUserSystemUid;
4420 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4421 mContext.binder.callingUid = secondUserSystemUid;
4422 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004423
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004424 // Profile owner changes IME for second user again.
4425 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004426 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004427 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004428 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004429 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004430 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004431 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4432 mContext.binder.callingUid = firstUserSystemUid;
4433 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4434 mContext.binder.callingUid = secondUserSystemUid;
4435 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004436
4437 // Restarting the DPMS should not lose information.
4438 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004439 mContext.binder.callingUid = firstUserSystemUid;
4440 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4441 mContext.binder.callingUid = secondUserSystemUid;
4442 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004443
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004444 // Profile owner can find out whether it set the current IME itself.
4445 mContext.binder.callingUid = profileOwnerUid;
4446 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004447
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004448 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004449 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004450 mContext.binder.callingUid = firstUserSystemUid;
4451 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4452 mContext.binder.callingUid = secondUserSystemUid;
4453 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004454 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004455
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004456 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4457 throws Exception {
4458 // Set up a device owner.
4459 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4460 setupDeviceOwner();
4461 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4462 }
4463
4464 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4465 throws Exception {
4466 // Set up a profile owner.
4467 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4468 setupProfileOwner();
4469 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4470 }
4471
4472 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4473 int adminUid) throws Exception {
4474 mContext.binder.callingUid = adminUid;
4475 final int userId = UserHandle.getUserId(adminUid);
4476
4477 final String packageName = "some.package";
4478 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4479 admin1, Collections.singletonList(packageName)));
4480 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4481
4482 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4483 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4484
4485 // Attempt to set to empty list (which means no listener is whitelisted)
4486 mContext.binder.callingUid = adminUid;
4487 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004488 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004489 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4490
4491 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4492 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4493 }
4494
4495 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4496 // Set up a managed profile
4497 final int MANAGED_PROFILE_USER_ID = 15;
4498 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4499 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4500 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4501
4502 final String permittedListener = "some.package";
4503 setupPackageInPackageManager(
4504 permittedListener,
4505 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4506 /*appId=*/ 12345, /*flags=*/ 0);
4507
4508 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4509 admin1, Collections.singletonList(permittedListener)));
4510
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004511 // isNotificationListenerServicePermitted should throw if not called from System.
4512 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4513 () -> dpms.isNotificationListenerServicePermitted(
4514 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004515
4516 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4517 assertTrue(dpms.isNotificationListenerServicePermitted(
4518 permittedListener, MANAGED_PROFILE_USER_ID));
4519 }
4520
4521 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4522 throws Exception {
4523 // Set up a managed profile
4524 final int MANAGED_PROFILE_USER_ID = 15;
4525 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4526 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4527 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4528
4529 final String permittedListener = "permitted.package";
4530 int appId = 12345;
4531 setupPackageInPackageManager(
4532 permittedListener,
4533 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4534 appId, /*flags=*/ 0);
4535
4536 final String notPermittedListener = "not.permitted.package";
4537 setupPackageInPackageManager(
4538 notPermittedListener,
4539 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4540 ++appId, /*flags=*/ 0);
4541
4542 final String systemListener = "system.package";
4543 setupPackageInPackageManager(
4544 systemListener,
4545 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4546 ++appId, ApplicationInfo.FLAG_SYSTEM);
4547
4548 // By default all packages are allowed
4549 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4550
4551 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4552 assertTrue(dpms.isNotificationListenerServicePermitted(
4553 permittedListener, MANAGED_PROFILE_USER_ID));
4554 assertTrue(dpms.isNotificationListenerServicePermitted(
4555 notPermittedListener, MANAGED_PROFILE_USER_ID));
4556 assertTrue(dpms.isNotificationListenerServicePermitted(
4557 systemListener, MANAGED_PROFILE_USER_ID));
4558
4559 // Setting only one package in the whitelist
4560 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4561 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4562 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004563 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004564 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4565 assertEquals(1, permittedListeners.size());
4566 assertEquals(permittedListener, permittedListeners.get(0));
4567
4568 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4569 assertTrue(dpms.isNotificationListenerServicePermitted(
4570 permittedListener, MANAGED_PROFILE_USER_ID));
4571 assertFalse(dpms.isNotificationListenerServicePermitted(
4572 notPermittedListener, MANAGED_PROFILE_USER_ID));
4573 // System packages are always allowed (even if not in the whitelist)
4574 assertTrue(dpms.isNotificationListenerServicePermitted(
4575 systemListener, MANAGED_PROFILE_USER_ID));
4576
4577 // Setting an empty whitelist - only system listeners allowed
4578 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4579 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004580 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004581 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4582
4583 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4584 assertFalse(dpms.isNotificationListenerServicePermitted(
4585 permittedListener, MANAGED_PROFILE_USER_ID));
4586 assertFalse(dpms.isNotificationListenerServicePermitted(
4587 notPermittedListener, MANAGED_PROFILE_USER_ID));
4588 // System packages are always allowed (even if not in the whitelist)
4589 assertTrue(dpms.isNotificationListenerServicePermitted(
4590 systemListener, MANAGED_PROFILE_USER_ID));
4591
4592 // Setting a null whitelist - all listeners allowed
4593 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4594 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4595 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4596
4597 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4598 assertTrue(dpms.isNotificationListenerServicePermitted(
4599 permittedListener, MANAGED_PROFILE_USER_ID));
4600 assertTrue(dpms.isNotificationListenerServicePermitted(
4601 notPermittedListener, MANAGED_PROFILE_USER_ID));
4602 assertTrue(dpms.isNotificationListenerServicePermitted(
4603 systemListener, MANAGED_PROFILE_USER_ID));
4604 }
4605
4606 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4607 throws Exception {
4608 // Set up a managed profile
4609 final int MANAGED_PROFILE_USER_ID = 15;
4610 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4611 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4612 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4613
4614 final String nonSystemPackage = "non.system.package";
4615 int appId = 12345;
4616 setupPackageInPackageManager(
4617 nonSystemPackage,
4618 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4619 appId, /*flags=*/ 0);
4620
4621 final String systemListener = "system.package";
4622 setupPackageInPackageManager(
4623 systemListener,
4624 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4625 ++appId, ApplicationInfo.FLAG_SYSTEM);
4626
4627 // By default all packages are allowed (for all profiles)
4628 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4629
4630 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4631 assertTrue(dpms.isNotificationListenerServicePermitted(
4632 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4633 assertTrue(dpms.isNotificationListenerServicePermitted(
4634 systemListener, MANAGED_PROFILE_USER_ID));
4635 assertTrue(dpms.isNotificationListenerServicePermitted(
4636 nonSystemPackage, UserHandle.USER_SYSTEM));
4637 assertTrue(dpms.isNotificationListenerServicePermitted(
4638 systemListener, UserHandle.USER_SYSTEM));
4639
4640 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4641 // all allowed in primary profile
4642 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4643 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004644 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004645 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4646
4647 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4648 assertFalse(dpms.isNotificationListenerServicePermitted(
4649 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4650 assertTrue(dpms.isNotificationListenerServicePermitted(
4651 systemListener, MANAGED_PROFILE_USER_ID));
4652 assertTrue(dpms.isNotificationListenerServicePermitted(
4653 nonSystemPackage, UserHandle.USER_SYSTEM));
4654 assertTrue(dpms.isNotificationListenerServicePermitted(
4655 systemListener, UserHandle.USER_SYSTEM));
4656 }
4657
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004658 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004659 mServiceContext.packageName = mRealTestContext.getPackageName();
4660 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4661 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004662 setDeviceOwner();
4663
Pavel Grafov75c0a892017-05-18 17:28:27 +01004664 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004665 }
4666
4667 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004668 mServiceContext.packageName = mRealTestContext.getPackageName();
4669 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4670 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004671 setAsProfileOwner(admin1);
4672
Pavel Grafov75c0a892017-05-18 17:28:27 +01004673 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4674 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004675 }
4676
4677 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004678 mServiceContext.packageName = mRealTestContext.getPackageName();
4679 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4680 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004681 setAsProfileOwner(admin1);
4682
Pavel Grafov75c0a892017-05-18 17:28:27 +01004683 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4684 caller.packageName = "com.example.delegate";
4685 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4686 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004687
Pavel Grafov75c0a892017-05-18 17:28:27 +01004688 // Make caller a delegated cert installer.
4689 runAsCaller(mAdmin1Context, dpms,
4690 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004691
4692 verifyCanGetOwnerInstalledCaCerts(null, caller);
4693 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004694 }
4695
Rubin Xucc391c22018-01-02 20:37:35 +00004696 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004697 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4698 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004699 Bundle restriction = new Bundle();
4700 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4701
4702 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4703 RestrictionsListener listener = new RestrictionsListener(mContext);
4704 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4705 new Bundle());
4706 verifyDataSharingChangedBroadcast();
4707 }
4708
4709 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004710 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4711 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004712 Bundle restriction = new Bundle();
4713 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4714
4715 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4716 RestrictionsListener listener = new RestrictionsListener(mContext);
4717 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4718 restriction);
4719 verifyDataSharingChangedBroadcast();
4720 }
4721
4722 public void testDisallowSharingIntoProfileUnchanged() {
4723 RestrictionsListener listener = new RestrictionsListener(mContext);
4724 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4725 new Bundle());
4726 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4727 }
4728
4729 private void verifyDataSharingChangedBroadcast() {
4730 Intent expectedIntent = new Intent(
4731 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4732 expectedIntent.setPackage("com.android.managedprovisioning");
4733 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4734 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4735 MockUtils.checkIntent(expectedIntent),
4736 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4737 }
4738
yuemingwe3d9c092018-01-11 12:11:44 +00004739 public void testOverrideApnAPIsFailWithPO() throws Exception {
4740 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004741 ApnSetting apn = (new ApnSetting.Builder())
4742 .setApnName("test")
4743 .setEntryName("test")
4744 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4745 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004746 assertExpectException(SecurityException.class, null, () ->
4747 dpm.addOverrideApn(admin1, apn));
4748 assertExpectException(SecurityException.class, null, () ->
4749 dpm.updateOverrideApn(admin1, 0, apn));
4750 assertExpectException(SecurityException.class, null, () ->
4751 dpm.removeOverrideApn(admin1, 0));
4752 assertExpectException(SecurityException.class, null, () ->
4753 dpm.getOverrideApns(admin1));
4754 assertExpectException(SecurityException.class, null, () ->
4755 dpm.setOverrideApnsEnabled(admin1, false));
4756 assertExpectException(SecurityException.class, null, () ->
4757 dpm.isOverrideApnEnabled(admin1));
4758 }
4759
Robin Lee2c68dad2017-03-17 12:50:24 +00004760 private void verifyCanGetOwnerInstalledCaCerts(
4761 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004762 final String alias = "cert";
4763 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004764
4765 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004766 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004767 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4768 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004769 }
4770 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4771
4772 // caller: device admin or delegated certificate installer
4773 callerContext.applicationInfo = new ApplicationInfo();
4774 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4775
4776 // system_server
4777 final DpmMockContext serviceContext = mContext;
4778 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004779 getServices().addPackageContext(callerUser, admin1Context);
4780 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004781
4782 // Install a CA cert.
4783 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004784 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004785 .thenReturn(alias);
4786 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004787 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004788 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004789 });
4790
Pavel Grafov75c0a892017-05-18 17:28:27 +01004791 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4792 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4793 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004794 flushTasks();
4795
Robin Lee2c68dad2017-03-17 12:50:24 +00004796 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4797
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004798 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004799 runAsCaller(admin1Context, dpms, (dpm) -> {
4800 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004801 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004802 ownerInstalledCaCerts.addAll(installedCaCerts);
4803 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004804
4805 // Restarting the DPMS should not lose information.
4806 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004807 runAsCaller(admin1Context, dpms, (dpm) ->
4808 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004809
4810 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004811 runAsCaller(serviceContext, dpms, (dpm) -> {
4812 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004813
Robin Lee2c68dad2017-03-17 12:50:24 +00004814 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004815 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004816 });
4817
Pavel Grafov75c0a892017-05-18 17:28:27 +01004818 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4819 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4820 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004821 flushTasks();
4822
4823 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4824 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004825 runAsCaller(admin1Context, dpms, (dpm) -> {
4826 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4827 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004828 }
4829
Robin Lee2c68dad2017-03-17 12:50:24 +00004830 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4831 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004832 final String alias = "cert";
4833 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004834
4835 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004836 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004837 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4838 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004839 }
4840 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4841
4842 // caller: device admin or delegated certificate installer
4843 callerContext.applicationInfo = new ApplicationInfo();
4844 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4845
4846 // system_server
4847 final DpmMockContext serviceContext = mContext;
4848 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004849 getServices().addPackageContext(callerUser, admin1Context);
4850 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004851
4852 // Install a CA cert as caller
4853 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004854 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004855 .thenReturn(alias);
4856 assertTrue(dpm.installCaCert(callerName, caCert));
4857 });
4858
4859 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004860 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004861 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004862 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4863 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4864 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004865 flushTasks();
4866
Robin Lee2c68dad2017-03-17 12:50:24 +00004867 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004868 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004869
4870 runAsCaller(serviceContext, dpms, (dpm) -> {
4871 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4872 assertNotNull(ownerInstalledCaCerts);
4873 assertTrue(ownerInstalledCaCerts.isEmpty());
4874 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004875 }
4876
Eran Messeri94d56762017-12-21 20:50:54 +00004877 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4878 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4879 Arrays.sort(gotFlags);
4880 Arrays.sort(expectedFlags);
4881 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4882 }
4883
4884 public void testTranslationOfIdAttestationFlag() {
4885 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4886 int[] correspondingAttUtilsTypes = new int[]{
4887 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4888 AttestationUtils.ID_TYPE_MEID};
4889
4890 // Test translation of zero flags
4891 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4892
4893 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4894 // non-null array
4895 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4896
4897 // Test translation of a single flag
4898 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4899 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4900 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4901
4902 // Test translation of two flags
4903 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4904 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4905 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4906 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4907
4908 // Test translation of all three flags
4909 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4910 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4911 AttestationUtils.ID_TYPE_MEID});
4912 // Test translation of all three flags
4913 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4914 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4915 AttestationUtils.ID_TYPE_MEID});
4916 }
4917
arangelov08d534b2018-01-22 15:20:53 +00004918 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4919 setDeviceOwner();
4920 initializeDpms();
4921 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4922 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4923 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4924 }
4925
4926 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4927 DpmTestUtils.writeInputStreamToFile(
4928 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4929 getDeviceOwnerPoliciesFile());
4930 DpmTestUtils.writeInputStreamToFile(
4931 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4932 getDeviceOwnerFile());
4933 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4934 }
4935
4936 public void testRevertDeviceOwnership_deviceNotMigrated()
4937 throws Exception {
4938 DpmTestUtils.writeInputStreamToFile(
4939 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4940 getDeviceOwnerPoliciesFile());
4941 DpmTestUtils.writeInputStreamToFile(
4942 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4943 getDeviceOwnerFile());
4944 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4945 }
4946
4947 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4948 throws Exception {
4949 DpmTestUtils.writeInputStreamToFile(
4950 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4951 getDeviceOwnerPoliciesFile());
4952 DpmTestUtils.writeInputStreamToFile(
4953 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4954 getDeviceOwnerFile());
4955 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4956 }
4957
4958 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4959 setupProfileOwner();
4960 initializeDpms();
4961 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4962 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4963 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4964 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4965 }
4966
4967 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4968 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4969 UserHandle.USER_SYSTEM);
4970 DpmTestUtils.writeInputStreamToFile(
4971 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4972 getProfileOwnerPoliciesFile());
4973 DpmTestUtils.writeInputStreamToFile(
4974 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
4975 getProfileOwnerFile());
4976 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4977 }
4978
4979 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
4980 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4981 UserHandle.USER_SYSTEM);
4982 DpmTestUtils.writeInputStreamToFile(
4983 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4984 getProfileOwnerPoliciesFile());
4985 DpmTestUtils.writeInputStreamToFile(
4986 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4987 getProfileOwnerFile());
4988 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4989 }
4990
4991 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
4992 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4993 UserHandle.USER_SYSTEM);
4994 DpmTestUtils.writeInputStreamToFile(
4995 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4996 getProfileOwnerPoliciesFile());
4997 DpmTestUtils.writeInputStreamToFile(
4998 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4999 getProfileOwnerFile());
5000 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5001 }
5002
5003 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5004 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5005 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5006 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5007
5008 final long ident = mServiceContext.binder.clearCallingIdentity();
5009 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5010 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5011 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5012 // To simulate a reboot, we just reinitialize dpms and call systemReady
5013 initializeDpms();
5014
5015 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5016 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5017 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5018 assertTrue(dpm.isAdminActive(admin1));
5019 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5020 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5021
5022 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5023 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5024 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5025 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5026
5027 mServiceContext.binder.restoreCallingIdentity(ident);
5028 }
5029
5030 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5031 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5032 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5033 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5034
5035 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5036 DpmMockContext.CALLER_SYSTEM_USER_UID);
5037 setUpPackageManagerForAdmin(admin1, uid);
5038 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5039 // To simulate a reboot, we just reinitialize dpms and call systemReady
5040 initializeDpms();
5041
5042 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5043 assertTrue(dpm.isAdminActive(admin1));
5044 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5045 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5046 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5047 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5048 }
5049
5050 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5051 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5052 metadataManager.deleteMetadataFile();
5053
5054 final TransferOwnershipMetadataManager.Metadata metadata =
5055 new TransferOwnershipMetadataManager.Metadata(
5056 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5057 callerUserHandle,
5058 adminType);
5059 metadataManager.saveMetadataFile(metadata);
5060 }
5061
5062 private File getDeviceOwnerFile() {
5063 return dpms.mOwners.getDeviceOwnerFile();
5064 }
5065
5066 private File getProfileOwnerFile() {
5067 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5068 }
5069
5070 private File getProfileOwnerPoliciesFile() {
5071 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5072 DpmMockContext.CALLER_USER_HANDLE);
5073 return getPoliciesFile(parentDir);
5074 }
5075
5076 private File getDeviceOwnerPoliciesFile() {
5077 return getPoliciesFile(getServices().systemUserDataDir);
5078 }
5079
5080 private File getPoliciesFile(File parentDir) {
5081 return new File(parentDir, "device_policies.xml");
5082 }
5083
5084 private InputStream getRawStream(@RawRes int id) {
5085 return mRealTestContext.getResources().openRawResource(id);
5086 }
5087
Victor Chang3e794af2016-03-04 13:48:17 +00005088 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005089 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005090 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5091 dpms.notifyChangeToContentObserver(
5092 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5093 }
5094
5095 private void assertProvisioningAllowed(String action, boolean expected) {
5096 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5097 dpm.isProvisioningAllowed(action));
5098 }
Tony Mak2f26b792016-11-28 17:54:51 +00005099
Nicolas Prevot45d29072017-01-18 16:11:19 +00005100 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5101 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005102 final String previousPackageName = mContext.packageName;
5103 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005104
5105 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5106 mContext.packageName = packageName;
5107 mMockContext.binder.callingUid = uid;
5108 assertProvisioningAllowed(action, expected);
5109
5110 // Set the previous package name / calling uid to go back to the initial state.
5111 mContext.packageName = previousPackageName;
5112 mMockContext.binder.callingUid = previousUid;
5113 }
5114
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005115 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005116 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5117 }
5118
5119 private void assertCheckProvisioningPreCondition(
5120 String action, String packageName, int provisioningCondition) {
5121 assertEquals("checkProvisioningPreCondition("
5122 + action + ", " + packageName + ") returning unexpected result",
5123 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005124 }
5125
Tony Mak2f26b792016-11-28 17:54:51 +00005126 /**
5127 * Setup a managed profile with the specified admin and its uid.
5128 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5129 * @param adminUid uid of the admin package.
5130 * @param copyFromAdmin package information for {@code admin} will be built based on this
5131 * component's information.
5132 */
5133 private void addManagedProfile(
5134 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5135 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005136 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005137 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5138 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5139 dpm.setActiveAdmin(admin, false, userId);
5140 assertTrue(dpm.setProfileOwner(admin, null, userId));
5141 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5142 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005143
5144 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005145 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005146 */
Robin Leeabaa0692017-02-20 20:54:22 +00005147 private static StringParceledListSlice asSlice(String[] s) {
5148 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005149 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005150
5151 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005152 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5153 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005154
Robin Lee2c68dad2017-03-17 12:50:24 +00005155 // We can't let exceptions happen on the background thread. Throw them here if they happen
5156 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005157 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005158 }
Victor Chang3e794af2016-03-04 13:48:17 +00005159}