blob: 5dc6d8373f277cb9609377847c52bac561aefb6a [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 \
Brett Chabota26eda92018-07-23 13:08:30 -0700119 -w com.android.frameworks.servicestests/androidx.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);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001715 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001716
Eric Sandnessca5969d2018-08-10 13:28:46 +01001717 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1718 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1719 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720
Eric Sandnessca5969d2018-08-10 13:28:46 +01001721 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1722 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001723
Eric Sandnessca5969d2018-08-10 13:28:46 +01001724 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1725 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1726 () -> dpm.setCameraDisabled(admin1, true));
1727 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1728
1729 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1730 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1731 () -> dpm.setKeyguardDisabledFeatures(admin1,
1732 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1733 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1734
1735 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1736 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1737 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1738 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1739
1740 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1741 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1742 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1743 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001744 }
1745
1746 public void testSetUserRestriction_asPo() {
1747 setAsProfileOwner(admin1);
1748
Makoto Onuki068c54a2015-10-13 14:34:03 -07001749 DpmTestUtils.assertRestrictions(
1750 DpmTestUtils.newRestrictions(),
1751 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1752 .ensureUserRestrictions()
1753 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001754
1755 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001756 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001757 eq(DpmMockContext.CALLER_USER_HANDLE),
1758 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001759 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001760 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001761
Makoto Onukia4f11972015-10-01 13:19:58 -07001762 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001763 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001764 eq(DpmMockContext.CALLER_USER_HANDLE),
1765 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1766 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001767 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001768 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001769
Makoto Onuki068c54a2015-10-13 14:34:03 -07001770 DpmTestUtils.assertRestrictions(
1771 DpmTestUtils.newRestrictions(
1772 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1773 UserManager.DISALLOW_OUTGOING_CALLS
1774 ),
1775 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1776 .ensureUserRestrictions()
1777 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001778 DpmTestUtils.assertRestrictions(
1779 DpmTestUtils.newRestrictions(
1780 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1781 UserManager.DISALLOW_OUTGOING_CALLS
1782 ),
1783 dpm.getUserRestrictions(admin1)
1784 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001785
1786 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001787 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788 eq(DpmMockContext.CALLER_USER_HANDLE),
1789 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001790 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001791 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001792
1793 DpmTestUtils.assertRestrictions(
1794 DpmTestUtils.newRestrictions(
1795 UserManager.DISALLOW_OUTGOING_CALLS
1796 ),
1797 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1798 .ensureUserRestrictions()
1799 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001800 DpmTestUtils.assertRestrictions(
1801 DpmTestUtils.newRestrictions(
1802 UserManager.DISALLOW_OUTGOING_CALLS
1803 ),
1804 dpm.getUserRestrictions(admin1)
1805 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001806
1807 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001808 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001809 eq(DpmMockContext.CALLER_USER_HANDLE),
1810 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001811 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001812 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001813
Makoto Onuki068c54a2015-10-13 14:34:03 -07001814 DpmTestUtils.assertRestrictions(
1815 DpmTestUtils.newRestrictions(),
1816 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1817 .ensureUserRestrictions()
1818 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001819 DpmTestUtils.assertRestrictions(
1820 DpmTestUtils.newRestrictions(),
1821 dpm.getUserRestrictions(admin1)
1822 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001823
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001824 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1825 // though when DO sets them they'll be applied globally.
1826 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001827 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001828 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001829 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001830 eq(DpmMockContext.CALLER_USER_HANDLE),
1831 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1832 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001833 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001834 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001835
1836 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001837 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001838 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001839 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001840 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001841 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001842 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001843
Makoto Onukia4f11972015-10-01 13:19:58 -07001844 // TODO Make sure restrictions are written to the file.
1845 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001846
Esteban Talavera548a04b2016-12-20 15:22:30 +00001847
1848 public void testDefaultEnabledUserRestrictions() throws Exception {
1849 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1850 mContext.callerPermissions.add(permission.MANAGE_USERS);
1851 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1852 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1853
1854 // First, set DO.
1855
1856 // Call from a process on the system user.
1857 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1858
1859 // Make sure admin1 is installed on system user.
1860 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1861
1862 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1863 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1864 UserHandle.USER_SYSTEM));
1865
1866 // Check that the user restrictions that are enabled by default are set. Then unset them.
1867 String[] defaultRestrictions = UserRestrictionsUtils
1868 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1869 assertTrue(defaultRestrictions.length > 0);
1870 DpmTestUtils.assertRestrictions(
1871 DpmTestUtils.newRestrictions(defaultRestrictions),
1872 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1873 );
1874 DpmTestUtils.assertRestrictions(
1875 DpmTestUtils.newRestrictions(defaultRestrictions),
1876 dpm.getUserRestrictions(admin1)
1877 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001878 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001879 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001880 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001881 eq(true) /* isDeviceOwner */,
1882 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001883 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001884 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001885
1886 for (String restriction : defaultRestrictions) {
1887 dpm.clearUserRestriction(admin1, restriction);
1888 }
1889
1890 assertNoDeviceOwnerRestrictions();
1891
1892 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001893 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001894 initializeDpms();
1895 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1896 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1897
1898 assertNoDeviceOwnerRestrictions();
1899
1900 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1901 // is set as it wasn't enabled during setDeviceOwner.
1902 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1903 assertFalse(UserRestrictionsUtils
1904 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1905 UserRestrictionsUtils
1906 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1907 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001908 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001909 initializeDpms();
1910 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1911 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1912
1913 DpmTestUtils.assertRestrictions(
1914 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1915 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1916 );
1917 DpmTestUtils.assertRestrictions(
1918 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1919 dpm.getUserRestrictions(admin1)
1920 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001921 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001922 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001923 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001924 eq(true) /* isDeviceOwner */,
1925 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001926 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001927 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001928
1929 // Remove the restriction.
1930 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1931
1932 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1933 initializeDpms();
1934 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1935 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1936 assertNoDeviceOwnerRestrictions();
1937 } finally {
1938 UserRestrictionsUtils
1939 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1940 }
1941 }
1942
1943 private void assertNoDeviceOwnerRestrictions() {
1944 DpmTestUtils.assertRestrictions(
1945 DpmTestUtils.newRestrictions(),
1946 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1947 );
1948 DpmTestUtils.assertRestrictions(
1949 DpmTestUtils.newRestrictions(),
1950 dpm.getUserRestrictions(admin1)
1951 );
1952 }
1953
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001954 public void testGetMacAddress() throws Exception {
1955 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1956 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1957 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1958
1959 // In this test, change the caller user to "system".
1960 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1961
1962 // Make sure admin1 is installed on system user.
1963 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1964
1965 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001966 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1967 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001968
1969 // DO needs to be an DA.
1970 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1971 assertTrue(dpm.isAdminActive(admin1));
1972
1973 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001974 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1975 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001976
1977 // Test 3. Caller has PO, but not DO.
1978 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001979 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1980 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001981
1982 // Remove PO.
1983 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001984 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001985 // Test 4, Caller is DO now.
1986 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1987
1988 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001989 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001990
1991 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001992 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001993 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001994
1995 // 4-3. With a real MAC address.
1996 final WifiInfo wi = new WifiInfo();
1997 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001998 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001999 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002000 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002001
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002002 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002003 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2004 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2005
2006 // In this test, change the caller user to "system".
2007 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2008
2009 // Make sure admin1 is installed on system user.
2010 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2011
2012 // Set admin1 as DA.
2013 dpm.setActiveAdmin(admin1, false);
2014 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002015 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2016 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002017
2018 // Set admin1 as PO.
2019 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002020 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2021 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002022
2023 // Remove PO and add DO.
2024 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002025 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002026 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2027
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002028 // admin1 is DO.
2029 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002030 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002031 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002032 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2033 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002034
2035 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002036 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002037 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002038 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2039 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002040
2041 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002042 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002043 dpm.reboot(admin1);
2044 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002045
2046 public void testSetGetSupportText() {
2047 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2048 dpm.setActiveAdmin(admin1, true);
2049 dpm.setActiveAdmin(admin2, true);
2050 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2051
2052 // Null default support messages.
2053 {
2054 assertNull(dpm.getLongSupportMessage(admin1));
2055 assertNull(dpm.getShortSupportMessage(admin1));
2056 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2057 assertNull(dpm.getShortSupportMessageForUser(admin1,
2058 DpmMockContext.CALLER_USER_HANDLE));
2059 assertNull(dpm.getLongSupportMessageForUser(admin1,
2060 DpmMockContext.CALLER_USER_HANDLE));
2061 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2062 }
2063
2064 // Only system can call the per user versions.
2065 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002066 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2067 () -> dpm.getShortSupportMessageForUser(admin1,
2068 DpmMockContext.CALLER_USER_HANDLE));
2069 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2070 () -> dpm.getLongSupportMessageForUser(admin1,
2071 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002072 }
2073
2074 // Can't set message for admin in another uid.
2075 {
2076 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002077 assertExpectException(SecurityException.class,
2078 /* messageRegex= */ "is not owned by uid",
2079 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002080 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2081 }
2082
2083 // Set/Get short returns what it sets and other admins text isn't changed.
2084 {
2085 final String supportText = "Some text to test with.";
2086 dpm.setShortSupportMessage(admin1, supportText);
2087 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2088 assertNull(dpm.getLongSupportMessage(admin1));
2089 assertNull(dpm.getShortSupportMessage(admin2));
2090
2091 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2092 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2093 DpmMockContext.CALLER_USER_HANDLE));
2094 assertNull(dpm.getShortSupportMessageForUser(admin2,
2095 DpmMockContext.CALLER_USER_HANDLE));
2096 assertNull(dpm.getLongSupportMessageForUser(admin1,
2097 DpmMockContext.CALLER_USER_HANDLE));
2098 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2099
2100 dpm.setShortSupportMessage(admin1, null);
2101 assertNull(dpm.getShortSupportMessage(admin1));
2102 }
2103
2104 // Set/Get long returns what it sets and other admins text isn't changed.
2105 {
2106 final String supportText = "Some text to test with.\nWith more text.";
2107 dpm.setLongSupportMessage(admin1, supportText);
2108 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2109 assertNull(dpm.getShortSupportMessage(admin1));
2110 assertNull(dpm.getLongSupportMessage(admin2));
2111
2112 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2113 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2114 DpmMockContext.CALLER_USER_HANDLE));
2115 assertNull(dpm.getLongSupportMessageForUser(admin2,
2116 DpmMockContext.CALLER_USER_HANDLE));
2117 assertNull(dpm.getShortSupportMessageForUser(admin1,
2118 DpmMockContext.CALLER_USER_HANDLE));
2119 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2120
2121 dpm.setLongSupportMessage(admin1, null);
2122 assertNull(dpm.getLongSupportMessage(admin1));
2123 }
2124 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002125
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002126 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002127 setAsProfileOwner(admin1);
2128
2129 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002130 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002131
2132 // Setup
2133 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2134 final String package1 = "com.example.one";
2135 final String package2 = "com.example.two";
2136 pkgsToRestrict.add(package1);
2137 pkgsToRestrict.add(package2);
2138 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2139 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002140 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002141
2142 // Verify
2143 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002144 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002145 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2146 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2147 eq(DpmMockContext.CALLER_USER_HANDLE));
2148
2149 // Setup
2150 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002151 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002152
2153 // Verify
2154 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002155 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002156 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2157 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2158 eq(DpmMockContext.CALLER_USER_HANDLE));
2159 }
2160
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002161 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002162 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2163 dpm.setActiveAdmin(admin1, true);
2164 assertTrue(dpm.isAdminActive(admin1));
2165 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2166
2167 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002168 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002169 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002170 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002171 }
2172
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002173 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002174 setAsProfileOwner(admin1);
2175
2176 // Setup
2177 final ArrayList<String> emptyList = new ArrayList<>();
2178 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2179 final String package1 = "com.example.one";
2180 final String package2 = "com.example.two";
2181 final String package3 = "com.example.three";
2182 pkgsToRestrict.add(package1);
2183 pkgsToRestrict.add(package2);
2184 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2185 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002186 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002187
2188 // Verify
2189 assertEquals(emptyList, excludedPkgs);
2190 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2191 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002192 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002193 DpmMockContext.CALLER_USER_HANDLE));
2194 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002195 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002196 DpmMockContext.CALLER_USER_HANDLE));
2197 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002198 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002199 DpmMockContext.CALLER_USER_HANDLE));
2200 }
2201
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002202 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002203 setAsProfileOwner(admin1);
2204 assertExpectException(SecurityException.class,
2205 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002206 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002207 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2208 dpm.clearProfileOwner(admin1);
2209
2210 setDeviceOwner();
2211 assertExpectException(SecurityException.class,
2212 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002213 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002214 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2215 clearDeviceOwner();
2216 }
2217
phweiss73145f42017-01-17 19:06:38 +01002218 public void testCreateAdminSupportIntent() throws Exception {
2219 // Setup device owner.
2220 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2221 setupDeviceOwner();
2222
2223 // Nonexisting permission returns null
2224 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2225 assertNull(intent);
2226
2227 // Existing permission that is not set returns null
2228 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2229 assertNull(intent);
2230
2231 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002232 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002233 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2234 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2235 .thenReturn(true);
2236 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2237 assertNull(intent);
2238
2239 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002240 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002241 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2242 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2243 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2244 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2245 assertNotNull(intent);
2246 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2247 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2248 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002249 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002250 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2251 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2252
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002253 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2254 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002255
2256 // Camera is not disabled
2257 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2258 assertNull(intent);
2259
2260 // Camera is disabled
2261 dpm.setCameraDisabled(admin1, true);
2262 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2263 assertNotNull(intent);
2264 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2265 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2266
2267 // Screen capture is not disabled
2268 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2269 assertNull(intent);
2270
2271 // Screen capture is disabled
2272 dpm.setScreenCaptureDisabled(admin1, true);
2273 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2274 assertNotNull(intent);
2275 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2276 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2277
2278 // Same checks for different user
2279 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2280 // Camera should be disabled by device owner
2281 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2282 assertNotNull(intent);
2283 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2284 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2285 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2286 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2287 // ScreenCapture should not be disabled by device owner
2288 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2289 assertNull(intent);
2290 }
2291
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002292 /**
2293 * Test for:
2294 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002295 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002296 * {@link DevicePolicyManager#isAffiliatedUser}
2297 */
2298 public void testUserAffiliation() throws Exception {
2299 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2300 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2301 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2302
2303 // Check that the system user is unaffiliated.
2304 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2305 assertFalse(dpm.isAffiliatedUser());
2306
2307 // Set a device owner on the system user. Check that the system user becomes affiliated.
2308 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2309 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2310 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2311 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002312 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002313
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002314 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002315 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2316 setAsProfileOwner(admin2);
2317 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002318 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002319
2320 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2321 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002322 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002323 userAffiliationIds.add("red");
2324 userAffiliationIds.add("green");
2325 userAffiliationIds.add("blue");
2326 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002327 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002328 assertFalse(dpm.isAffiliatedUser());
2329
2330 // Have the device owner specify a set of affiliation ids that do not intersect with those
2331 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002332 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002333 deviceAffiliationIds.add("cyan");
2334 deviceAffiliationIds.add("yellow");
2335 deviceAffiliationIds.add("magenta");
2336 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2337 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002338 MoreAsserts.assertContentsInAnyOrder(
2339 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002340 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2341 assertFalse(dpm.isAffiliatedUser());
2342
2343 // Have the profile owner specify a set of affiliation ids that intersect with those
2344 // specified by the device owner. Check that the test user becomes affiliated.
2345 userAffiliationIds.add("yellow");
2346 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002347 MoreAsserts.assertContentsInAnyOrder(
2348 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002349 assertTrue(dpm.isAffiliatedUser());
2350
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002351 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002352 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002353 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002354 assertFalse(dpm.isAffiliatedUser());
2355
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002356 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2357 dpm.setAffiliationIds(admin2, userAffiliationIds);
2358 assertTrue(dpm.isAffiliatedUser());
2359 dpm.clearProfileOwner(admin2);
2360 assertFalse(dpm.isAffiliatedUser());
2361
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002362 // Check that the system user remains affiliated.
2363 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2364 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002365
2366 // Clear the device owner - the user becomes unaffiliated.
2367 clearDeviceOwner();
2368 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002369 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002370
2371 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002372 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002373 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2374 }
2375
2376 public void testSetUserProvisioningState_permission() throws Exception {
2377 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002378
2379 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2380 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2381 }
2382
2383 public void testSetUserProvisioningState_unprivileged() throws Exception {
2384 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002385 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2386 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2387 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002388 }
2389
2390 public void testSetUserProvisioningState_noManagement() {
2391 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002392 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002393 assertExpectException(IllegalStateException.class,
2394 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2395 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2396 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002397 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2398 }
2399
2400 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2401 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2402 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002403
2404 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2405 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2406 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2407 }
2408
2409 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2410 throws Exception {
2411 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2412 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002413
2414 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2415 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2416 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2417 }
2418
2419 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2420 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2421 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002422
2423 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2424 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2425 }
2426
2427 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2428 throws Exception {
2429 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002430
2431 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2432 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2433 DevicePolicyManager.STATE_USER_UNMANAGED);
2434 }
2435
2436 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2437 throws Exception {
2438 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002439
2440 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2441 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2442 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2443 }
2444
2445 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2446 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002447
2448 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2449 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2450 }
2451
2452 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2453 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002454
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002455 assertExpectException(IllegalStateException.class,
2456 /* messageRegex= */ "Cannot move to user provisioning state",
2457 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2458 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2459 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002460 }
2461
2462 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2463 throws Exception {
2464 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002465
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002466 assertExpectException(IllegalStateException.class,
2467 /* messageRegex= */ "Cannot move to user provisioning state",
2468 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2469 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2470 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002471 }
2472
2473 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002474 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2475 mContext.callerPermissions.add(permission.MANAGE_USERS);
2476
Alan Treadwayafad8782016-01-19 15:15:08 +00002477 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2478 for (int state : states) {
2479 dpm.setUserProvisioningState(state, userId);
2480 assertEquals(state, dpm.getUserProvisioningState());
2481 }
2482 }
2483
2484 private void setupProfileOwner() throws Exception {
2485 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2486
2487 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2488 dpm.setActiveAdmin(admin1, false);
2489 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2490
2491 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2492 }
2493
2494 private void setupDeviceOwner() throws Exception {
2495 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2496
2497 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2498 dpm.setActiveAdmin(admin1, false);
2499 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2500
2501 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2502 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002503
2504 public void testSetMaximumTimeToLock() {
2505 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2506
2507 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2508 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2509
Pavel Grafov75c0a892017-05-18 17:28:27 +01002510 reset(getServices().powerManagerInternal);
2511 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002512
2513 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002514 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2515 verifyStayOnWhilePluggedCleared(false);
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, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002520 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2521 verifyStayOnWhilePluggedCleared(true);
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(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002526 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2527 verifyStayOnWhilePluggedCleared(false);
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(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002532 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2533 verifyStayOnWhilePluggedCleared(true);
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(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002538 verifyScreenTimeoutCall(4L, 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(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002544 reset(getServices().powerManagerInternal);
2545 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002546
Pavel Grafov28939982017-10-03 15:11:52 +01002547 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2548 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2549 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002550 reset(getServices().powerManagerInternal);
2551 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002552
2553 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002554 verifyScreenTimeoutCall(10L, 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
Pavel Grafov28939982017-10-03 15:11:52 +01002559 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002560 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002561 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2562 verifyStayOnWhilePluggedCleared(false);
2563 }
2564
2565 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2566 // uses separate challenge.
2567 public void testSetMaximumTimeToLockProfile() throws Exception {
2568 final int PROFILE_USER = 15;
2569 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2570 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2571 mContext.binder.callingUid = PROFILE_ADMIN;
2572 final DevicePolicyManagerInternal dpmi =
2573 LocalServices.getService(DevicePolicyManagerInternal.class);
2574
2575 dpm.setMaximumTimeToLock(admin1, 0);
2576
2577 reset(getServices().powerManagerInternal);
2578 reset(getServices().settings);
2579
2580 // First add timeout for the profile.
2581 dpm.setMaximumTimeToLock(admin1, 10);
2582 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2583
2584 reset(getServices().powerManagerInternal);
2585 reset(getServices().settings);
2586
2587 // Add separate challenge
2588 when(getServices().lockPatternUtils
2589 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2590 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2591
2592 verifyScreenTimeoutCall(10L, PROFILE_USER);
2593 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2594
2595 reset(getServices().powerManagerInternal);
2596 reset(getServices().settings);
2597
2598 // Remove the timeout.
2599 dpm.setMaximumTimeToLock(admin1, 0);
2600 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2601 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2602
2603 reset(getServices().powerManagerInternal);
2604 reset(getServices().settings);
2605
2606 // Add it back.
2607 dpm.setMaximumTimeToLock(admin1, 10);
2608 verifyScreenTimeoutCall(10L, PROFILE_USER);
2609 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2610
2611 reset(getServices().powerManagerInternal);
2612 reset(getServices().settings);
2613
2614 // Remove separate challenge.
2615 reset(getServices().lockPatternUtils);
2616 when(getServices().lockPatternUtils
2617 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2618 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2619
2620 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2621 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2622
2623 reset(getServices().powerManagerInternal);
2624 reset(getServices().settings);
2625
2626 // Remove the timeout.
2627 dpm.setMaximumTimeToLock(admin1, 0);
2628 verifyScreenTimeoutCall(null, PROFILE_USER);
2629 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002630 }
2631
Michal Karpinski943aabd2016-10-06 11:09:25 +01002632 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2633 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2634 setupDeviceOwner();
2635 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2636
Michal Karpinskid084ca52017-01-18 15:54:18 +00002637 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2638 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2639 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2640 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2641 - ONE_MINUTE;
2642
2643 // verify that the minimum timeout cannot be modified on user builds (system property is
2644 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002645 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002646
2647 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2648 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2649 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2650
Pavel Grafov75c0a892017-05-18 17:28:27 +01002651 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002652
2653 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002654 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002655
Michal Karpinskid084ca52017-01-18 15:54:18 +00002656 // reset to default (0 means the admin is not participating, so default should be returned)
2657 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002658
2659 // aggregation should be the default if unset by any admin
2660 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2661 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2662
2663 // admin not participating by default
2664 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2665
2666 //clamping from the top
2667 dpm.setRequiredStrongAuthTimeout(admin1,
2668 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2669 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2670 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2671 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2672 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2673
Michal Karpinskid084ca52017-01-18 15:54:18 +00002674 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002675 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2676 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2677 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2678 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2679
2680 // clamping from the bottom
2681 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2682 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2683 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2684
Michal Karpinskid084ca52017-01-18 15:54:18 +00002685 // values within range
2686 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2687 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2688 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2689
2690 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2691 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2692 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002693
2694 // reset to default
2695 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2696 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2697 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2698 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2699
2700 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002701 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2702 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002703 }
2704
Pavel Grafov28939982017-10-03 15:11:52 +01002705 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002706 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002707 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002708 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002709 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002710 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002711 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002712 }
Pavel Grafov28939982017-10-03 15:11:52 +01002713 }
2714
2715 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002716 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2717 // UnfinishedVerificationException.
2718 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002719
Esteban Talavera01576862016-12-15 11:16:44 +00002720 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002721 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002722 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002723 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002724 .thenReturn(false);
2725 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002726 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2727 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002728 .thenReturn(true);
2729 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2730
2731 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002732 }
Victor Chang3e794af2016-03-04 13:48:17 +00002733
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002734 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2735 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002736 mContext.packageName = admin1.getPackageName();
2737 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002738 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2739 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2740 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2741 false);
2742 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2743 }
2744
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002745 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2746 setup_DeviceAdminFeatureOff();
2747 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2748 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2749 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2750 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2751 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2752 assertCheckProvisioningPreCondition(
2753 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2754 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2755 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2756 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2757 }
2758
Esteban Talavera01576862016-12-15 11:16:44 +00002759 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002760 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002761 .thenReturn(false);
2762 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002763 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2764 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002765 .thenReturn(true);
2766 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2767
2768 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002769 }
Victor Chang3e794af2016-03-04 13:48:17 +00002770
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002771 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2772 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002773 mContext.packageName = admin1.getPackageName();
2774 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002775 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2776 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2777 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2778 false);
2779 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2780
2781 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002782 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2784 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2786 true);
2787 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2788 }
2789
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002790 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2791 setup_ManagedProfileFeatureOff();
2792 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2794 DevicePolicyManager.CODE_OK);
2795 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2796 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2797 assertCheckProvisioningPreCondition(
2798 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2799 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2800 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2801 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2802
2803 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002804 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002805 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2806 DevicePolicyManager.CODE_OK);
2807 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2808 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2809 assertCheckProvisioningPreCondition(
2810 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2811 DevicePolicyManager.CODE_OK);
2812 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2813 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2814 }
2815
Esteban Talavera01576862016-12-15 11:16:44 +00002816 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002817 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002818 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002819 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2820 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002821 .thenReturn(true);
2822 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2823
2824 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002825 }
Victor Chang3e794af2016-03-04 13:48:17 +00002826
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002827 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2828 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002829 mContext.packageName = admin1.getPackageName();
2830 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002831 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2832 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2833 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2834 false /* because of non-split user */);
2835 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2836 false /* because of non-split user */);
2837 }
2838
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002839 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002840 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002841 setup_nonSplitUser_firstBoot_primaryUser();
2842 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2843 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2844 DevicePolicyManager.CODE_OK);
2845 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2846 DevicePolicyManager.CODE_OK);
2847 assertCheckProvisioningPreCondition(
2848 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2849 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2850 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2851 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2852 }
2853
Esteban Talavera01576862016-12-15 11:16:44 +00002854 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002855 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002856 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002857 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2858 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002859 .thenReturn(true);
2860 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2861
2862 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002863 }
Victor Chang3e794af2016-03-04 13:48:17 +00002864
Nicolas Prevot45d29072017-01-18 16:11:19 +00002865 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2866 setDeviceOwner();
2867 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2868 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2869 }
2870
2871 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2872 setup_nonSplitUser_withDo_primaryUser();
2873 final int MANAGED_PROFILE_USER_ID = 18;
2874 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2875 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002876 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002877 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002878 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002879 true)).thenReturn(true);
2880 }
2881
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002882 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2883 throws Exception {
2884 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002885 mContext.packageName = admin1.getPackageName();
2886 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002887 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2888 false/* because of completed device setup */);
2889 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2890 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2891 false/* because of non-split user */);
2892 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2893 false/* because of non-split user */);
2894 }
2895
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002896 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2897 throws Exception {
2898 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2899 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2900 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2901 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2902 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2903 DevicePolicyManager.CODE_OK);
2904 assertCheckProvisioningPreCondition(
2905 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2906 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2907 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2908 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2909 }
2910
Nicolas Prevot45d29072017-01-18 16:11:19 +00002911 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2912 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002913 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002914 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2915
2916 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2917 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002918 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002919
2920 // COMP mode is allowed.
2921 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2922 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002923 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002924
Nicolas Prevot45d29072017-01-18 16:11:19 +00002925 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002926 assertCheckProvisioningPreCondition(
2927 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002928 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002929 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002930 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2931 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2932 }
Esteban Talavera01576862016-12-15 11:16:44 +00002933
Nicolas Prevot45d29072017-01-18 16:11:19 +00002934 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2935 setup_nonSplitUser_withDo_primaryUser();
2936 mContext.packageName = admin1.getPackageName();
2937 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2938 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2939 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002940 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002941 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2942 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2943 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002944 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002945 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2946 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2947 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2948 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2949 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002950 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002951 assertCheckProvisioningPreCondition(
2952 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002953 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002954 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002955 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2956 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2957 }
Esteban Talavera01576862016-12-15 11:16:44 +00002958
Nicolas Prevot45d29072017-01-18 16:11:19 +00002959 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2960 throws Exception {
2961 setup_nonSplitUser_withDo_primaryUser();
2962 mContext.packageName = admin1.getPackageName();
2963 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002964 // The DO should not be allowed to initiate provisioning if the restriction is set by
2965 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002966 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002967 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2968 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2969 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002970 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002971 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2972 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2973 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2974 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2975 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002976 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2977
2978 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002979 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002980 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002981 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002982 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2983 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2984 }
2985
2986 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2987 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2988 mContext.packageName = admin1.getPackageName();
2989 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2990
2991 // We can delete the managed profile to create a new one, so provisioning is allowed.
2992 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2993 DevicePolicyManager.CODE_OK);
2994 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2995 assertCheckProvisioningPreCondition(
2996 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2997 DpmMockContext.ANOTHER_PACKAGE_NAME,
2998 DevicePolicyManager.CODE_OK);
2999 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3000 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3001 }
3002
3003 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3004 throws Exception {
3005 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3006 mContext.packageName = admin1.getPackageName();
3007 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003008 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003009 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3010 eq(UserHandle.SYSTEM)))
3011 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003012 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003013 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3014 eq(UserHandle.SYSTEM)))
3015 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003016
3017 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003018 assertCheckProvisioningPreCondition(
3019 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3020 DpmMockContext.ANOTHER_PACKAGE_NAME,
3021 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3022 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3023 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003024
3025 // But the device owner can still do it because it has set the restriction itself.
3026 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3027 DevicePolicyManager.CODE_OK);
3028 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003029 }
3030
3031 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003032 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003033 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003034 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3035 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003036 .thenReturn(false);
3037 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3038
3039 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003040 }
Victor Chang3e794af2016-03-04 13:48:17 +00003041
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003042 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3043 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003044 mContext.packageName = admin1.getPackageName();
3045 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003046 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3047 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3048 false /* because canAddMoreManagedProfiles returns false */);
3049 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3050 true);
3051 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3052 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003053 }
3054
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003055 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3056 throws Exception {
3057 setup_splitUser_firstBoot_systemUser();
3058 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3059 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3060 DevicePolicyManager.CODE_OK);
3061 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003062 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003063 assertCheckProvisioningPreCondition(
3064 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3065 DevicePolicyManager.CODE_OK);
3066 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3067 DevicePolicyManager.CODE_SYSTEM_USER);
3068 }
3069
Esteban Talavera01576862016-12-15 11:16:44 +00003070 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003071 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003072 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003073 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3074 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003075 .thenReturn(false);
3076 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3077
3078 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003079 }
Victor Chang3e794af2016-03-04 13:48:17 +00003080
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003081 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3082 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003083 mContext.packageName = admin1.getPackageName();
3084 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003085 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3086 true/* it's undefined behavior. Can be changed into false in the future */);
3087 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3088 false /* because canAddMoreManagedProfiles returns false */);
3089 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3090 true/* it's undefined behavior. Can be changed into false in the future */);
3091 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3092 false/* because calling uid is system user */);
3093 }
3094
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003095 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3096 throws Exception {
3097 setup_splitUser_afterDeviceSetup_systemUser();
3098 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3099 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3100 DevicePolicyManager.CODE_OK);
3101 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003102 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003103 assertCheckProvisioningPreCondition(
3104 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3105 DevicePolicyManager.CODE_OK);
3106 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3107 DevicePolicyManager.CODE_SYSTEM_USER);
3108 }
3109
Esteban Talavera01576862016-12-15 11:16:44 +00003110 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003111 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003112 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003113 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3114 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003115 true)).thenReturn(true);
3116 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3117
3118 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003119 }
Victor Chang3e794af2016-03-04 13:48:17 +00003120
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003121 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3122 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003123 mContext.packageName = admin1.getPackageName();
3124 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003125 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3126 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3127 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3128 true);
3129 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003130 }
3131
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003132 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003133 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003134 setup_splitUser_firstBoot_primaryUser();
3135 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3136 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3137 DevicePolicyManager.CODE_OK);
3138 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3139 DevicePolicyManager.CODE_OK);
3140 assertCheckProvisioningPreCondition(
3141 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3142 DevicePolicyManager.CODE_OK);
3143 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3144 DevicePolicyManager.CODE_OK);
3145 }
3146
Esteban Talavera01576862016-12-15 11:16:44 +00003147 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003148 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003149 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003150 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3151 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003152 true)).thenReturn(true);
3153 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3154
3155 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003156 }
Victor Chang3e794af2016-03-04 13:48:17 +00003157
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003158 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3159 throws Exception {
3160 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003161 mContext.packageName = admin1.getPackageName();
3162 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003163 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3164 true/* it's undefined behavior. Can be changed into false in the future */);
3165 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3166 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3167 true/* it's undefined behavior. Can be changed into false in the future */);
3168 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3169 false/* because user setup completed */);
3170 }
3171
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003172 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003173 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003174 setup_splitUser_afterDeviceSetup_primaryUser();
3175 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3176 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3177 DevicePolicyManager.CODE_OK);
3178 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3179 DevicePolicyManager.CODE_OK);
3180 assertCheckProvisioningPreCondition(
3181 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3182 DevicePolicyManager.CODE_OK);
3183 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3184 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3185 }
3186
Esteban Talavera01576862016-12-15 11:16:44 +00003187 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003188 setDeviceOwner();
3189
Pavel Grafov75c0a892017-05-18 17:28:27 +01003190 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003191 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003192 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3193 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003194 .thenReturn(false);
3195 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3196
3197 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003198 }
Victor Chang3e794af2016-03-04 13:48:17 +00003199
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003200 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3201 throws Exception {
3202 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003203 mContext.packageName = admin1.getPackageName();
3204 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003205 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3206 false /* can't provision managed profile on system user */);
3207 }
3208
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003209 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003210 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003211 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3212 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3213 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3214 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3215 }
3216
3217 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003218 setDeviceOwner();
3219
Pavel Grafov75c0a892017-05-18 17:28:27 +01003220 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003221 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003222 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3223 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003224 true)).thenReturn(true);
3225 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3226
3227 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003228 }
Victor Chang3e794af2016-03-04 13:48:17 +00003229
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003230 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3231 throws Exception {
3232 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003233 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3234 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003235 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3236 }
3237
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003238 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003239 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003240 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3241 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003242
3243 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003244 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3245 DevicePolicyManager.CODE_OK);
3246 }
3247
3248 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003249 setDeviceOwner();
3250
Pavel Grafov75c0a892017-05-18 17:28:27 +01003251 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003252 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003253 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3254 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003255 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3256 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003257 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003258 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003259 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003260 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003261 true)).thenReturn(true);
3262 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3263
3264 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003265 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003266
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003267 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3268 throws Exception {
3269 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003270 mContext.packageName = admin1.getPackageName();
3271 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003272 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3273 }
3274
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003275 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3276 throws Exception {
3277 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3278 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3279 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3280 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3281 }
3282
3283 public void testCheckProvisioningPreCondition_permission() {
3284 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003285 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3286 () -> dpm.checkProvisioningPreCondition(
3287 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003288 }
3289
Victor Chang3577ed22016-08-25 18:49:26 +01003290 public void testForceUpdateUserSetupComplete_permission() {
3291 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003292 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3293 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003294 }
3295
3296 public void testForceUpdateUserSetupComplete_systemUser() {
3297 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3298 // GIVEN calling from user 20
3299 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003300 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3301 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003302 }
3303
3304 public void testForceUpdateUserSetupComplete_userbuild() {
3305 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3306 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3307
3308 final int userId = UserHandle.USER_SYSTEM;
3309 // GIVEN userComplete is false in SettingsProvider
3310 setUserSetupCompleteForUser(false, userId);
3311
3312 // GIVEN userComplete is true in DPM
3313 DevicePolicyManagerService.DevicePolicyData userData =
3314 new DevicePolicyManagerService.DevicePolicyData(userId);
3315 userData.mUserSetupComplete = true;
3316 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3317
3318 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003319 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003320
3321 assertTrue(dpms.hasUserSetupCompleted());
3322
3323 dpm.forceUpdateUserSetupComplete();
3324
3325 // THEN the state in dpms is not changed
3326 assertTrue(dpms.hasUserSetupCompleted());
3327 }
3328
3329 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3330 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3331 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3332
3333 final int userId = UserHandle.USER_SYSTEM;
3334 // GIVEN userComplete is false in SettingsProvider
3335 setUserSetupCompleteForUser(false, userId);
3336
3337 // GIVEN userComplete is true in DPM
3338 DevicePolicyManagerService.DevicePolicyData userData =
3339 new DevicePolicyManagerService.DevicePolicyData(userId);
3340 userData.mUserSetupComplete = true;
3341 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3342
3343 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003344 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003345
3346 assertTrue(dpms.hasUserSetupCompleted());
3347
3348 dpm.forceUpdateUserSetupComplete();
3349
3350 // THEN the state in dpms is not changed
3351 assertFalse(dpms.hasUserSetupCompleted());
3352 }
3353
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003354 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003355 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003356 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003357
3358 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3359 runAsCaller(mAdmin1Context, dpms, dpm -> {
3360 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3361 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003362 }
3363
3364 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3365 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3366 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003367
3368 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3369 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003370 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003371 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3372 .thenReturn(true);
3373
3374 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003375 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003376
3377 // Enabling logging should not change the timestamp.
3378 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003379 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003380 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003381 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003382 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003383 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003384
3385 // Retrieving the logs should update the timestamp.
3386 final long beforeRetrieval = System.currentTimeMillis();
3387 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003388 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003389 final long afterRetrieval = System.currentTimeMillis();
3390 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3391 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3392
3393 // Retrieving the pre-boot logs should update the timestamp.
3394 Thread.sleep(2);
3395 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003396 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003397 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3398
3399 // Checking the timestamp again should not change it.
3400 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003401 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003402
3403 // Retrieving the logs again should update the timestamp.
3404 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003405 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003406 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3407
3408 // Disabling logging should not change the timestamp.
3409 Thread.sleep(2);
3410 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003411 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003412
3413 // Restarting the DPMS should not lose the timestamp.
3414 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003415 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003416
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003417 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3418 mContext.binder.callingUid = 1234567;
3419 mContext.callerPermissions.add(permission.MANAGE_USERS);
3420 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3421 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3422
3423 // System can retrieve the timestamp.
3424 mContext.binder.clearCallingIdentity();
3425 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3426
3427 // Removing the device owner should clear the timestamp.
3428 clearDeviceOwner();
3429 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003430 }
3431
yuemingw0de748d2017-11-15 19:22:27 +00003432 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3433 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3434 setupDeviceOwner();
3435 assertExpectException(SecurityException.class, null, () ->
3436 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3437 }
3438
yuemingwc0281f12018-03-28 15:58:49 +01003439 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003440 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3441 setupDeviceOwner();
3442 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003443 verify(getServices().settings).settingsSystemPutStringForUser(
3444 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3445 }
3446
3447 public void testSetSystemSettingWithPO() throws Exception {
3448 setupProfileOwner();
3449 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3450 verify(getServices().settings).settingsSystemPutStringForUser(
3451 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003452 }
3453
yuemingwe43cdf72017-10-12 16:52:11 +01003454 public void testSetTime() throws Exception {
3455 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3456 setupDeviceOwner();
3457 dpm.setTime(admin1, 0);
3458 verify(getServices().alarmManager).setTime(0);
3459 }
3460
3461 public void testSetTimeFailWithPO() throws Exception {
3462 setupProfileOwner();
3463 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3464 }
3465
3466 public void testSetTimeWithAutoTimeOn() throws Exception {
3467 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3468 setupDeviceOwner();
3469 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3470 .thenReturn(1);
3471 assertFalse(dpm.setTime(admin1, 0));
3472 }
3473
3474 public void testSetTimeZone() throws Exception {
3475 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3476 setupDeviceOwner();
3477 dpm.setTimeZone(admin1, "Asia/Shanghai");
3478 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3479 }
3480
3481 public void testSetTimeZoneFailWithPO() throws Exception {
3482 setupProfileOwner();
3483 assertExpectException(SecurityException.class, null,
3484 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3485 }
3486
3487 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3488 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3489 setupDeviceOwner();
3490 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3491 .thenReturn(1);
3492 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3493 }
3494
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003495 public void testGetLastBugReportRequestTime() throws Exception {
3496 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3497 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003498
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003499 mContext.packageName = admin1.getPackageName();
3500 mContext.applicationInfo = new ApplicationInfo();
3501 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3502 .thenReturn(Color.WHITE);
3503 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3504 anyObject())).thenReturn(Color.WHITE);
3505
Esteban Talaverad36dd152016-12-15 08:51:45 +00003506 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3507 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003508 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003509
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003510 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003511 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003512
3513 // Requesting a bug report should update the timestamp.
3514 final long beforeRequest = System.currentTimeMillis();
3515 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003516 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003517 final long afterRequest = System.currentTimeMillis();
3518 assertTrue(bugReportRequestTime >= beforeRequest);
3519 assertTrue(bugReportRequestTime <= afterRequest);
3520
3521 // Checking the timestamp again should not change it.
3522 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003523 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003524
3525 // Restarting the DPMS should not lose the timestamp.
3526 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003527 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003528
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003529 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3530 mContext.binder.callingUid = 1234567;
3531 mContext.callerPermissions.add(permission.MANAGE_USERS);
3532 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3533 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3534
3535 // System can retrieve the timestamp.
3536 mContext.binder.clearCallingIdentity();
3537 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3538
3539 // Removing the device owner should clear the timestamp.
3540 clearDeviceOwner();
3541 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003542 }
3543
3544 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3545 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3546 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003547 mContext.packageName = admin1.getPackageName();
3548 mContext.applicationInfo = new ApplicationInfo();
3549 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3550 .thenReturn(Color.WHITE);
3551 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3552 anyObject())).thenReturn(Color.WHITE);
3553
3554 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3555 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003556 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003557 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003558 .thenReturn(true);
3559
3560 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003561 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003562
3563 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3564 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003565 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003566
3567 // Enabling logging should not change the timestamp.
3568 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003569 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003570
3571 // Retrieving the logs should update the timestamp.
3572 final long beforeRetrieval = System.currentTimeMillis();
3573 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003574 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003575 final long afterRetrieval = System.currentTimeMillis();
3576 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3577 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3578
3579 // Checking the timestamp again should not change it.
3580 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003581 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003582
3583 // Retrieving the logs again should update the timestamp.
3584 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003585 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003586 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3587
3588 // Disabling logging should not change the timestamp.
3589 Thread.sleep(2);
3590 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003591 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003592
3593 // Restarting the DPMS should not lose the timestamp.
3594 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003595 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3596
3597 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3598 mContext.binder.callingUid = 1234567;
3599 mContext.callerPermissions.add(permission.MANAGE_USERS);
3600 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3601 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3602
3603 // System can retrieve the timestamp.
3604 mContext.binder.clearCallingIdentity();
3605 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3606
3607 // Removing the device owner should clear the timestamp.
3608 clearDeviceOwner();
3609 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003610 }
3611
Tony Mak2f26b792016-11-28 17:54:51 +00003612 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3613 // Setup device owner.
3614 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3615 setupDeviceOwner();
3616
3617 // Only device owner is setup, the result list should be empty.
3618 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3619 MoreAsserts.assertEmpty(targetUsers);
3620
3621 // Setup a managed profile managed by the same admin.
3622 final int MANAGED_PROFILE_USER_ID = 15;
3623 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3624 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3625
3626 // Add a secondary user, it should never talk with.
3627 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003628 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003629
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003630 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3631 // other.
3632 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3633 MoreAsserts.assertEmpty(targetUsers);
3634
3635 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3636 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3637 MoreAsserts.assertEmpty(targetUsers);
3638
3639 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003640 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003641 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3642 dpm.setAffiliationIds(admin1, userAffiliationIds);
3643
3644 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3645 dpm.setAffiliationIds(admin1, userAffiliationIds);
3646
Tony Mak2f26b792016-11-28 17:54:51 +00003647 // Calling from device owner admin, the result list should just contain the managed
3648 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003649 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003650 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3651 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3652
3653 // Calling from managed profile admin, the result list should just contain the system
3654 // user id.
3655 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3656 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3657 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003658
3659 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003660 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003661
3662 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3663 // to each other.
3664 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3665 MoreAsserts.assertEmpty(targetUsers);
3666
3667 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3668 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3669 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003670 }
3671
3672 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3673 // Setup a device owner.
3674 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3675 setupDeviceOwner();
3676
3677 // Set up a managed profile managed by different package.
3678 final int MANAGED_PROFILE_USER_ID = 15;
3679 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3680 final ComponentName adminDifferentPackage =
3681 new ComponentName("another.package", "whatever.class");
3682 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3683
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003684 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003685 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003686 dpm.setAffiliationIds(admin1, userAffiliationIds);
3687
3688 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3689 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3690
Tony Mak2f26b792016-11-28 17:54:51 +00003691 // Calling from device owner admin, we should get zero bind device admin target users as
3692 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003693 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003694 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3695 MoreAsserts.assertEmpty(targetUsers);
3696
3697 // Calling from managed profile admin, we should still get zero target users for the same
3698 // reason.
3699 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3700 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3701 MoreAsserts.assertEmpty(targetUsers);
3702 }
3703
Jason Parks3c13b642017-11-28 15:39:43 -06003704 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003705 verifyLockTaskState(userId, new String[0],
3706 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003707 }
3708
3709 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3710 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003711 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003712 }
3713
3714 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3715 int flags) throws Exception {
3716 mContext.binder.callingUid = uid;
3717 dpm.setLockTaskPackages(who, packages);
3718 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3719 for (String p : packages) {
3720 assertTrue(dpm.isLockTaskPermitted(p));
3721 }
3722 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3723 // Test to see if set lock task features can be set
3724 dpm.setLockTaskFeatures(who, flags);
3725 verifyLockTaskState(userId, packages, flags);
3726 }
3727
3728 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3729 int flags) throws Exception {
3730 mContext.binder.callingUid = uid;
3731 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3732 () -> dpm.setLockTaskPackages(who, packages));
3733 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3734 () -> dpm.getLockTaskPackages(who));
3735 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3736 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3737 () -> dpm.setLockTaskFeatures(who, flags));
3738 }
3739
Charles Hee078db72017-10-19 18:03:20 +01003740 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003741 // Setup a device owner.
3742 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3743 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003744 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003745 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003746
3747 // Set up a managed profile managed by different package (package name shouldn't matter)
3748 final int MANAGED_PROFILE_USER_ID = 15;
3749 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3750 final ComponentName adminDifferentPackage =
3751 new ComponentName("another.package", "whatever.class");
3752 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003753 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3754
3755 // Setup a PO on the secondary user
3756 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3757 setAsProfileOwner(admin3);
3758 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003759
3760 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003761 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003762 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003763 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3764 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003765 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3766
3767 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3768 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003769 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3770 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003771 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003772
3773 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3774 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3775 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003776 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003777 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3778 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003779 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003780
3781 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003782 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003783 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3784 dpm.setAffiliationIds(admin1, userAffiliationIds);
3785
3786 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3787 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3788
3789 // Now the managed profile can set lock task packages.
3790 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3791 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3792 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3793 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003794 // And it can set lock task features.
3795 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003796 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003797
3798 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003799 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003800 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3801 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003802 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3803 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003804 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003805 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003806
Jason Parks3c13b642017-11-28 15:39:43 -06003807 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003808 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3809 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003810
3811 }
3812
3813 public void testLockTaskPolicyForProfileOwner() throws Exception {
3814 // Setup a PO
3815 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3816 setAsProfileOwner(admin1);
3817 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3818
3819 final String[] poPackages = {"poPackage1", "poPackage2"};
3820 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003821 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3822 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003823 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3824 poPackages, poFlags);
3825
3826 // Set up a managed profile managed by different package (package name shouldn't matter)
3827 final int MANAGED_PROFILE_USER_ID = 15;
3828 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3829 final ComponentName adminDifferentPackage =
3830 new ComponentName("another.package", "whatever.class");
3831 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3832 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3833
3834 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3835 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3836 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3837 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003838 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3839 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003840 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003841 }
3842
Benjamin Franzcaffa772018-02-05 16:36:10 +00003843 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3844 // Setup a device owner.
3845 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3846 setupDeviceOwner();
3847 // Lock task policy is updated when loading user data.
3848 verifyLockTaskState(UserHandle.USER_SYSTEM);
3849
3850 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3851 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3852 assertExpectException(IllegalArgumentException.class,
3853 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3854 () -> dpm.setLockTaskFeatures(admin1, flags));
3855 }
3856
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003857 public void testIsDeviceManaged() throws Exception {
3858 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3859 setupDeviceOwner();
3860
3861 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3862 // find out that the device has a device owner.
3863 assertTrue(dpm.isDeviceManaged());
3864 mContext.binder.callingUid = 1234567;
3865 mContext.callerPermissions.add(permission.MANAGE_USERS);
3866 assertTrue(dpm.isDeviceManaged());
3867 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3868 mContext.binder.clearCallingIdentity();
3869 assertTrue(dpm.isDeviceManaged());
3870
3871 clearDeviceOwner();
3872
3873 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3874 // not have a device owner.
3875 mContext.binder.callingUid = 1234567;
3876 mContext.callerPermissions.add(permission.MANAGE_USERS);
3877 assertFalse(dpm.isDeviceManaged());
3878 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3879 mContext.binder.clearCallingIdentity();
3880 assertFalse(dpm.isDeviceManaged());
3881 }
3882
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003883 public void testDeviceOwnerOrganizationName() throws Exception {
3884 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3885 setupDeviceOwner();
3886
3887 dpm.setOrganizationName(admin1, "organization");
3888
3889 // Device owner can retrieve organization managing the device.
3890 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3891
3892 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3893 mContext.binder.callingUid = 1234567;
3894 mContext.callerPermissions.add(permission.MANAGE_USERS);
3895 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3896 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3897
3898 // System can retrieve organization managing the device.
3899 mContext.binder.clearCallingIdentity();
3900 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3901
3902 // Removing the device owner clears the organization managing the device.
3903 clearDeviceOwner();
3904 assertNull(dpm.getDeviceOwnerOrganizationName());
3905 }
3906
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003907 public void testWipeDataManagedProfile() throws Exception {
3908 final int MANAGED_PROFILE_USER_ID = 15;
3909 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3910 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3911 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3912
3913 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003914 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003915 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003916 // Get mock reason string since we throw an IAE with empty string input.
3917 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3918 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003919
3920 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003921 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003922 MANAGED_PROFILE_USER_ID);
3923 }
3924
3925 public void testWipeDataManagedProfileDisallowed() throws Exception {
3926 final int MANAGED_PROFILE_USER_ID = 15;
3927 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3928 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3929
3930 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003931 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003932 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3933
Pavel Grafov75c0a892017-05-18 17:28:27 +01003934 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003935 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3936 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3937 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003938 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3939 thenReturn("Just a test string.");
3940
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003941 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003942 // The PO is not allowed to remove the profile if the user restriction was set on the
3943 // profile by the system
3944 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3945 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003946 }
3947
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003948 public void testWipeDataDeviceOwner() throws Exception {
3949 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003950 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003951 UserManager.DISALLOW_FACTORY_RESET,
3952 UserHandle.SYSTEM))
3953 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003954 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3955 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003956
3957 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003958 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003959 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3960 /*wipeEuicc=*/ eq(false));
3961 }
3962
3963 public void testWipeEuiccDataEnabled() throws Exception {
3964 setDeviceOwner();
3965 when(getServices().userManager.getUserRestrictionSource(
3966 UserManager.DISALLOW_FACTORY_RESET,
3967 UserHandle.SYSTEM))
3968 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003969 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3970 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003971
3972 dpm.wipeData(WIPE_EUICC);
3973 verify(getServices().recoverySystem).rebootWipeUserData(
3974 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3975 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003976 }
3977
3978 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3979 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003980 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003981 UserManager.DISALLOW_FACTORY_RESET,
3982 UserHandle.SYSTEM))
3983 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003984 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3985 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003986 // The DO is not allowed to wipe the device if the user restriction was set
3987 // by the system
3988 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3989 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003990 }
3991
3992 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3993 final int MANAGED_PROFILE_USER_ID = 15;
3994 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3995 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3996
3997 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003998 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003999 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4000
Pavel Grafov75c0a892017-05-18 17:28:27 +01004001 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004002 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4003 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4004 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4005
4006 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4007 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4008
4009 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4010 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4011 // Failed password attempts on the parent user are taken into account, as there isn't a
4012 // separate work challenge.
4013 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4014 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4015 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4016
4017 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4018 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004019 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004020 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004021 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004022 }
4023
4024 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4025 throws Exception {
4026 final int MANAGED_PROFILE_USER_ID = 15;
4027 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4028 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4029
4030 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004031 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004032 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4033
Pavel Grafov75c0a892017-05-18 17:28:27 +01004034 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004035 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4036 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4037 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4038
4039 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4040 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4041
4042 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4043 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4044 // Failed password attempts on the parent user are taken into account, as there isn't a
4045 // separate work challenge.
4046 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4047 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4048 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4049
4050 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4051 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004052 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004053 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004054 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004055 }
4056
4057 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4058 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004059 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004060 UserManager.DISALLOW_FACTORY_RESET,
4061 UserHandle.SYSTEM))
4062 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4063
4064 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4065
4066 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4067 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4068 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4069 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4070 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4071
4072 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4073 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004074 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004075 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4076 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004077 }
4078
4079 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4080 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004081 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004082 UserManager.DISALLOW_FACTORY_RESET,
4083 UserHandle.SYSTEM))
4084 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4085
4086 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4087
4088 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4089 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4090 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4091 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4092 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4093
4094 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004095 verifyZeroInteractions(getServices().recoverySystem);
4096 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004097 .removeUserEvenWhenDisallowed(anyInt());
4098 }
4099
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004100 public void testGetPermissionGrantState() throws Exception {
4101 final String permission = "some.permission";
4102 final String app1 = "com.example.app1";
4103 final String app2 = "com.example.app2";
4104
Pavel Grafov75c0a892017-05-18 17:28:27 +01004105 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004106 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004107 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004108 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004109 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004110 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4111 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004112 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004113 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004114 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004115 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004116 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004117 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4118
4119 // System can retrieve permission grant state.
4120 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004121 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004122 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4123 dpm.getPermissionGrantState(null, app1, permission));
4124 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4125 dpm.getPermissionGrantState(null, app2, permission));
4126
4127 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004128 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4129 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004130 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4131 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004132
4133 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004134 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4135 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004136 setAsProfileOwner(admin1);
4137 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4138 dpm.getPermissionGrantState(admin1, app1, permission));
4139 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4140 dpm.getPermissionGrantState(admin1, app2, permission));
4141 }
4142
Rubin Xuaab7a412016-12-30 21:13:29 +00004143 public void testResetPasswordWithToken() throws Exception {
4144 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4145 setupDeviceOwner();
4146 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004147 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4148 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4149
Rubin Xuaab7a412016-12-30 21:13:29 +00004150 // test adding a token
4151 final byte[] token = new byte[32];
4152 final long handle = 123456;
4153 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01004154 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004155 .thenReturn(handle);
4156 assertTrue(dpm.setResetPasswordToken(admin1, token));
4157
4158 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004159 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004160 .thenReturn(true);
4161 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4162
4163 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004164 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01004165 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
4166 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004167 eq(UserHandle.USER_SYSTEM)))
4168 .thenReturn(true);
4169 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4170
4171 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004172 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004173 .thenReturn(true);
4174 assertTrue(dpm.clearResetPasswordToken(admin1));
4175 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004176
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004177 public void testIsActivePasswordSufficient() throws Exception {
4178 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4179 mContext.packageName = admin1.getPackageName();
4180 setupDeviceOwner();
4181
4182 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4183 dpm.setPasswordMinimumLength(admin1, 8);
4184 dpm.setPasswordMinimumLetters(admin1, 6);
4185 dpm.setPasswordMinimumLowerCase(admin1, 3);
4186 dpm.setPasswordMinimumUpperCase(admin1, 1);
4187 dpm.setPasswordMinimumNonLetter(admin1, 1);
4188 dpm.setPasswordMinimumNumeric(admin1, 1);
4189 dpm.setPasswordMinimumSymbols(admin1, 0);
4190
Rubin Xucc391c22018-01-02 20:37:35 +00004191 reset(mContext.spiedContext);
4192
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004193 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4194 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4195 8, 2,
4196 6, 1,
4197 0, 1);
4198
4199 setActivePasswordState(passwordMetricsNoSymbols);
4200 assertTrue(dpm.isActivePasswordSufficient());
4201
4202 initializeDpms();
4203 reset(mContext.spiedContext);
4204 assertTrue(dpm.isActivePasswordSufficient());
4205
4206 // This call simulates the user entering the password for the first time after a reboot.
4207 // This causes password metrics to be reloaded into memory. Until this happens,
4208 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4209 // even if the DPC changes password requirements so that the password no longer meets the
4210 // requirements. This is a known limitation of the current implementation of
4211 // isActivePasswordSufficient() - see b/34218769.
4212 setActivePasswordState(passwordMetricsNoSymbols);
4213 assertTrue(dpm.isActivePasswordSufficient());
4214
4215 dpm.setPasswordMinimumSymbols(admin1, 1);
4216 // This assertion would fail if we had not called setActivePasswordState() again after
4217 // initializeDpms() - see previous comment.
4218 assertFalse(dpm.isActivePasswordSufficient());
4219
4220 initializeDpms();
4221 reset(mContext.spiedContext);
4222 assertFalse(dpm.isActivePasswordSufficient());
4223
4224 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4225 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4226 7, 2,
4227 5, 1,
4228 1, 2);
4229
4230 setActivePasswordState(passwordMetricsWithSymbols);
4231 assertTrue(dpm.isActivePasswordSufficient());
4232 }
4233
Pavel Grafov75c0a892017-05-18 17:28:27 +01004234 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4235 throws Exception {
4236 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004237 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004238
Pavel Grafov75c0a892017-05-18 17:28:27 +01004239 dpm.setActivePasswordState(passwordMetrics, userHandle);
4240 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004241
Rubin Xucc391c22018-01-02 20:37:35 +00004242 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4243 // reportPasswordChanged()
Eran Messeri9ecde422018-04-30 16:16:39 +01004244 // This broadcast should be sent 4 times:
4245 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4246 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
4247 // * Twice from calls to DevicePolicyManagerService.saveSettingsLocked
4248 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4249 // the password change is relevant to and another with the credential owner of said
4250 // userId.
4251 verify(mContext.spiedContext, times(4)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004252 MockUtils.checkIntentAction(
4253 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4254 MockUtils.checkUserHandle(userHandle));
4255
Pavel Grafov75c0a892017-05-18 17:28:27 +01004256 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4257 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004258 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004259
4260 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4261 MockUtils.checkIntent(intent),
4262 MockUtils.checkUserHandle(userHandle));
4263
4264 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4265 // let it finish with system uid, otherwise it will throw and crash.
4266 flushTasks();
4267
4268 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004269 }
4270
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004271 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4272 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4273 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4274 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4275 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4276 DpmMockContext.SYSTEM_UID);
4277 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4278 DpmMockContext.SYSTEM_UID);
4279
4280 // Set up a device owner.
4281 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004282 setupDeviceOwner();
4283
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004284 // First and second user set IMEs manually.
4285 mContext.binder.callingUid = firstUserSystemUid;
4286 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4287 mContext.binder.callingUid = secondUserSystemUid;
4288 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004289
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004290 // Device owner changes IME for first user.
4291 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004292 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004293 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004294 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004295 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004296 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004297 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004298 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4299 mContext.binder.callingUid = firstUserSystemUid;
4300 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4301 mContext.binder.callingUid = secondUserSystemUid;
4302 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004303
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004304 // Second user changes IME manually.
4305 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4306 mContext.binder.callingUid = firstUserSystemUid;
4307 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4308 mContext.binder.callingUid = secondUserSystemUid;
4309 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004310
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004311 // First user changes IME manually.
4312 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4313 mContext.binder.callingUid = firstUserSystemUid;
4314 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4315 mContext.binder.callingUid = secondUserSystemUid;
4316 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004317
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004318 // Device owner changes IME for first user again.
4319 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004320 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004321 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004322 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004323 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004324 UserHandle.USER_SYSTEM);
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
4331 // Restarting the DPMS should not lose information.
4332 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004333 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 // Device owner can find out whether it set the current IME itself.
4339 mContext.binder.callingUid = deviceOwnerUid;
4340 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004341
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004342 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004343 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004344 mContext.binder.callingUid = firstUserSystemUid;
4345 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4346 mContext.binder.callingUid = secondUserSystemUid;
4347 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004348 }
4349
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004350 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4351 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4352 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4353 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4354 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4355 DpmMockContext.SYSTEM_UID);
4356 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4357 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004358
4359 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004360 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004361 setupProfileOwner();
4362
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004363 // First and second user set IMEs manually.
4364 mContext.binder.callingUid = firstUserSystemUid;
4365 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4366 mContext.binder.callingUid = secondUserSystemUid;
4367 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004368
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004369 // Profile owner changes IME for second user.
4370 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004371 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004372 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004373 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004374 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004375 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004376 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004377 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4378 mContext.binder.callingUid = firstUserSystemUid;
4379 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4380 mContext.binder.callingUid = secondUserSystemUid;
4381 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004382
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004383 // First user changes IME manually.
4384 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4385 mContext.binder.callingUid = firstUserSystemUid;
4386 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4387 mContext.binder.callingUid = secondUserSystemUid;
4388 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004389
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004390 // Second user changes IME manually.
4391 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4392 mContext.binder.callingUid = firstUserSystemUid;
4393 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4394 mContext.binder.callingUid = secondUserSystemUid;
4395 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004396
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004397 // Profile owner changes IME for second user again.
4398 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004399 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004400 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004401 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004402 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004403 DpmMockContext.CALLER_USER_HANDLE);
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
4410 // Restarting the DPMS should not lose information.
4411 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004412 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 // Profile owner can find out whether it set the current IME itself.
4418 mContext.binder.callingUid = profileOwnerUid;
4419 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004420
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004421 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004422 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004423 mContext.binder.callingUid = firstUserSystemUid;
4424 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4425 mContext.binder.callingUid = secondUserSystemUid;
4426 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004427 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004428
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004429 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4430 throws Exception {
4431 // Set up a device owner.
4432 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4433 setupDeviceOwner();
4434 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4435 }
4436
4437 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4438 throws Exception {
4439 // Set up a profile owner.
4440 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4441 setupProfileOwner();
4442 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4443 }
4444
4445 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4446 int adminUid) throws Exception {
4447 mContext.binder.callingUid = adminUid;
4448 final int userId = UserHandle.getUserId(adminUid);
4449
4450 final String packageName = "some.package";
4451 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4452 admin1, Collections.singletonList(packageName)));
4453 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4454
4455 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4456 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4457
4458 // Attempt to set to empty list (which means no listener is whitelisted)
4459 mContext.binder.callingUid = adminUid;
4460 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004461 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004462 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4463
4464 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4465 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4466 }
4467
4468 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4469 // Set up a managed profile
4470 final int MANAGED_PROFILE_USER_ID = 15;
4471 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4472 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4473 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4474
4475 final String permittedListener = "some.package";
4476 setupPackageInPackageManager(
4477 permittedListener,
4478 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4479 /*appId=*/ 12345, /*flags=*/ 0);
4480
4481 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4482 admin1, Collections.singletonList(permittedListener)));
4483
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004484 // isNotificationListenerServicePermitted should throw if not called from System.
4485 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4486 () -> dpms.isNotificationListenerServicePermitted(
4487 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004488
4489 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4490 assertTrue(dpms.isNotificationListenerServicePermitted(
4491 permittedListener, MANAGED_PROFILE_USER_ID));
4492 }
4493
4494 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4495 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 = "permitted.package";
4503 int appId = 12345;
4504 setupPackageInPackageManager(
4505 permittedListener,
4506 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4507 appId, /*flags=*/ 0);
4508
4509 final String notPermittedListener = "not.permitted.package";
4510 setupPackageInPackageManager(
4511 notPermittedListener,
4512 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4513 ++appId, /*flags=*/ 0);
4514
4515 final String systemListener = "system.package";
4516 setupPackageInPackageManager(
4517 systemListener,
4518 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4519 ++appId, ApplicationInfo.FLAG_SYSTEM);
4520
4521 // By default all packages are allowed
4522 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4523
4524 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4525 assertTrue(dpms.isNotificationListenerServicePermitted(
4526 permittedListener, MANAGED_PROFILE_USER_ID));
4527 assertTrue(dpms.isNotificationListenerServicePermitted(
4528 notPermittedListener, MANAGED_PROFILE_USER_ID));
4529 assertTrue(dpms.isNotificationListenerServicePermitted(
4530 systemListener, MANAGED_PROFILE_USER_ID));
4531
4532 // Setting only one package in the whitelist
4533 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4534 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4535 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004536 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004537 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4538 assertEquals(1, permittedListeners.size());
4539 assertEquals(permittedListener, permittedListeners.get(0));
4540
4541 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4542 assertTrue(dpms.isNotificationListenerServicePermitted(
4543 permittedListener, MANAGED_PROFILE_USER_ID));
4544 assertFalse(dpms.isNotificationListenerServicePermitted(
4545 notPermittedListener, MANAGED_PROFILE_USER_ID));
4546 // System packages are always allowed (even if not in the whitelist)
4547 assertTrue(dpms.isNotificationListenerServicePermitted(
4548 systemListener, MANAGED_PROFILE_USER_ID));
4549
4550 // Setting an empty whitelist - only system listeners allowed
4551 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4552 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004553 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004554 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4555
4556 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4557 assertFalse(dpms.isNotificationListenerServicePermitted(
4558 permittedListener, MANAGED_PROFILE_USER_ID));
4559 assertFalse(dpms.isNotificationListenerServicePermitted(
4560 notPermittedListener, MANAGED_PROFILE_USER_ID));
4561 // System packages are always allowed (even if not in the whitelist)
4562 assertTrue(dpms.isNotificationListenerServicePermitted(
4563 systemListener, MANAGED_PROFILE_USER_ID));
4564
4565 // Setting a null whitelist - all listeners allowed
4566 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4567 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4568 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4569
4570 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4571 assertTrue(dpms.isNotificationListenerServicePermitted(
4572 permittedListener, MANAGED_PROFILE_USER_ID));
4573 assertTrue(dpms.isNotificationListenerServicePermitted(
4574 notPermittedListener, MANAGED_PROFILE_USER_ID));
4575 assertTrue(dpms.isNotificationListenerServicePermitted(
4576 systemListener, MANAGED_PROFILE_USER_ID));
4577 }
4578
4579 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4580 throws Exception {
4581 // Set up a managed profile
4582 final int MANAGED_PROFILE_USER_ID = 15;
4583 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4584 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4585 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4586
4587 final String nonSystemPackage = "non.system.package";
4588 int appId = 12345;
4589 setupPackageInPackageManager(
4590 nonSystemPackage,
4591 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4592 appId, /*flags=*/ 0);
4593
4594 final String systemListener = "system.package";
4595 setupPackageInPackageManager(
4596 systemListener,
4597 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4598 ++appId, ApplicationInfo.FLAG_SYSTEM);
4599
4600 // By default all packages are allowed (for all profiles)
4601 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4602
4603 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4604 assertTrue(dpms.isNotificationListenerServicePermitted(
4605 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4606 assertTrue(dpms.isNotificationListenerServicePermitted(
4607 systemListener, MANAGED_PROFILE_USER_ID));
4608 assertTrue(dpms.isNotificationListenerServicePermitted(
4609 nonSystemPackage, UserHandle.USER_SYSTEM));
4610 assertTrue(dpms.isNotificationListenerServicePermitted(
4611 systemListener, UserHandle.USER_SYSTEM));
4612
4613 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4614 // all allowed in primary profile
4615 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4616 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004617 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004618 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4619
4620 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4621 assertFalse(dpms.isNotificationListenerServicePermitted(
4622 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4623 assertTrue(dpms.isNotificationListenerServicePermitted(
4624 systemListener, MANAGED_PROFILE_USER_ID));
4625 assertTrue(dpms.isNotificationListenerServicePermitted(
4626 nonSystemPackage, UserHandle.USER_SYSTEM));
4627 assertTrue(dpms.isNotificationListenerServicePermitted(
4628 systemListener, UserHandle.USER_SYSTEM));
4629 }
4630
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004631 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004632 mServiceContext.packageName = mRealTestContext.getPackageName();
4633 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4634 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004635 setDeviceOwner();
4636
Pavel Grafov75c0a892017-05-18 17:28:27 +01004637 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004638 }
4639
4640 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004641 mServiceContext.packageName = mRealTestContext.getPackageName();
4642 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4643 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004644 setAsProfileOwner(admin1);
4645
Pavel Grafov75c0a892017-05-18 17:28:27 +01004646 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4647 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004648 }
4649
4650 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004651 mServiceContext.packageName = mRealTestContext.getPackageName();
4652 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4653 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004654 setAsProfileOwner(admin1);
4655
Pavel Grafov75c0a892017-05-18 17:28:27 +01004656 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4657 caller.packageName = "com.example.delegate";
4658 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4659 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004660
Pavel Grafov75c0a892017-05-18 17:28:27 +01004661 // Make caller a delegated cert installer.
4662 runAsCaller(mAdmin1Context, dpms,
4663 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004664
4665 verifyCanGetOwnerInstalledCaCerts(null, caller);
4666 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004667 }
4668
Rubin Xucc391c22018-01-02 20:37:35 +00004669 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004670 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4671 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004672 Bundle restriction = new Bundle();
4673 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4674
4675 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4676 RestrictionsListener listener = new RestrictionsListener(mContext);
4677 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4678 new Bundle());
4679 verifyDataSharingChangedBroadcast();
4680 }
4681
4682 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004683 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4684 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004685 Bundle restriction = new Bundle();
4686 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4687
4688 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4689 RestrictionsListener listener = new RestrictionsListener(mContext);
4690 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4691 restriction);
4692 verifyDataSharingChangedBroadcast();
4693 }
4694
4695 public void testDisallowSharingIntoProfileUnchanged() {
4696 RestrictionsListener listener = new RestrictionsListener(mContext);
4697 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4698 new Bundle());
4699 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4700 }
4701
4702 private void verifyDataSharingChangedBroadcast() {
4703 Intent expectedIntent = new Intent(
4704 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4705 expectedIntent.setPackage("com.android.managedprovisioning");
4706 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4707 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4708 MockUtils.checkIntent(expectedIntent),
4709 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4710 }
4711
yuemingwe3d9c092018-01-11 12:11:44 +00004712 public void testOverrideApnAPIsFailWithPO() throws Exception {
4713 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004714 ApnSetting apn = (new ApnSetting.Builder())
4715 .setApnName("test")
4716 .setEntryName("test")
4717 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4718 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004719 assertExpectException(SecurityException.class, null, () ->
4720 dpm.addOverrideApn(admin1, apn));
4721 assertExpectException(SecurityException.class, null, () ->
4722 dpm.updateOverrideApn(admin1, 0, apn));
4723 assertExpectException(SecurityException.class, null, () ->
4724 dpm.removeOverrideApn(admin1, 0));
4725 assertExpectException(SecurityException.class, null, () ->
4726 dpm.getOverrideApns(admin1));
4727 assertExpectException(SecurityException.class, null, () ->
4728 dpm.setOverrideApnsEnabled(admin1, false));
4729 assertExpectException(SecurityException.class, null, () ->
4730 dpm.isOverrideApnEnabled(admin1));
4731 }
4732
Robin Lee2c68dad2017-03-17 12:50:24 +00004733 private void verifyCanGetOwnerInstalledCaCerts(
4734 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004735 final String alias = "cert";
4736 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004737
4738 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004739 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004740 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4741 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004742 }
4743 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4744
4745 // caller: device admin or delegated certificate installer
4746 callerContext.applicationInfo = new ApplicationInfo();
4747 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4748
4749 // system_server
4750 final DpmMockContext serviceContext = mContext;
4751 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004752 getServices().addPackageContext(callerUser, admin1Context);
4753 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004754
4755 // Install a CA cert.
4756 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004757 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004758 .thenReturn(alias);
4759 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004760 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004761 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004762 });
4763
Pavel Grafov75c0a892017-05-18 17:28:27 +01004764 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4765 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4766 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004767 flushTasks();
4768
Robin Lee2c68dad2017-03-17 12:50:24 +00004769 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4770
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004771 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004772 runAsCaller(admin1Context, dpms, (dpm) -> {
4773 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004774 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004775 ownerInstalledCaCerts.addAll(installedCaCerts);
4776 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004777
4778 // Restarting the DPMS should not lose information.
4779 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004780 runAsCaller(admin1Context, dpms, (dpm) ->
4781 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004782
4783 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004784 runAsCaller(serviceContext, dpms, (dpm) -> {
4785 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004786
Robin Lee2c68dad2017-03-17 12:50:24 +00004787 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004788 reset(getServices().keyChainConnection.getService());
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
4796 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4797 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004798 runAsCaller(admin1Context, dpms, (dpm) -> {
4799 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4800 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004801 }
4802
Robin Lee2c68dad2017-03-17 12:50:24 +00004803 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4804 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004805 final String alias = "cert";
4806 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004807
4808 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004809 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004810 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4811 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004812 }
4813 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4814
4815 // caller: device admin or delegated certificate installer
4816 callerContext.applicationInfo = new ApplicationInfo();
4817 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4818
4819 // system_server
4820 final DpmMockContext serviceContext = mContext;
4821 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004822 getServices().addPackageContext(callerUser, admin1Context);
4823 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004824
4825 // Install a CA cert as caller
4826 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004827 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004828 .thenReturn(alias);
4829 assertTrue(dpm.installCaCert(callerName, caCert));
4830 });
4831
4832 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004833 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004834 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004835 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4836 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4837 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004838 flushTasks();
4839
Robin Lee2c68dad2017-03-17 12:50:24 +00004840 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004841 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004842
4843 runAsCaller(serviceContext, dpms, (dpm) -> {
4844 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4845 assertNotNull(ownerInstalledCaCerts);
4846 assertTrue(ownerInstalledCaCerts.isEmpty());
4847 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004848 }
4849
Eran Messeri94d56762017-12-21 20:50:54 +00004850 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4851 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4852 Arrays.sort(gotFlags);
4853 Arrays.sort(expectedFlags);
4854 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4855 }
4856
4857 public void testTranslationOfIdAttestationFlag() {
4858 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4859 int[] correspondingAttUtilsTypes = new int[]{
4860 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4861 AttestationUtils.ID_TYPE_MEID};
4862
4863 // Test translation of zero flags
4864 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4865
4866 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4867 // non-null array
4868 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4869
4870 // Test translation of a single flag
4871 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4872 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4873 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4874
4875 // Test translation of two flags
4876 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4877 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4878 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4879 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4880
4881 // Test translation of all three flags
4882 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4883 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4884 AttestationUtils.ID_TYPE_MEID});
4885 // Test translation of all three flags
4886 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4887 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4888 AttestationUtils.ID_TYPE_MEID});
4889 }
4890
arangelov08d534b2018-01-22 15:20:53 +00004891 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4892 setDeviceOwner();
4893 initializeDpms();
4894 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4895 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4896 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4897 }
4898
4899 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4900 DpmTestUtils.writeInputStreamToFile(
4901 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4902 getDeviceOwnerPoliciesFile());
4903 DpmTestUtils.writeInputStreamToFile(
4904 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4905 getDeviceOwnerFile());
4906 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4907 }
4908
4909 public void testRevertDeviceOwnership_deviceNotMigrated()
4910 throws Exception {
4911 DpmTestUtils.writeInputStreamToFile(
4912 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4913 getDeviceOwnerPoliciesFile());
4914 DpmTestUtils.writeInputStreamToFile(
4915 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4916 getDeviceOwnerFile());
4917 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4918 }
4919
4920 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4921 throws Exception {
4922 DpmTestUtils.writeInputStreamToFile(
4923 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4924 getDeviceOwnerPoliciesFile());
4925 DpmTestUtils.writeInputStreamToFile(
4926 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4927 getDeviceOwnerFile());
4928 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4929 }
4930
4931 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4932 setupProfileOwner();
4933 initializeDpms();
4934 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4935 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4936 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4937 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4938 }
4939
4940 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4941 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4942 UserHandle.USER_SYSTEM);
4943 DpmTestUtils.writeInputStreamToFile(
4944 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4945 getProfileOwnerPoliciesFile());
4946 DpmTestUtils.writeInputStreamToFile(
4947 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
4948 getProfileOwnerFile());
4949 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4950 }
4951
4952 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
4953 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4954 UserHandle.USER_SYSTEM);
4955 DpmTestUtils.writeInputStreamToFile(
4956 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4957 getProfileOwnerPoliciesFile());
4958 DpmTestUtils.writeInputStreamToFile(
4959 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4960 getProfileOwnerFile());
4961 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4962 }
4963
4964 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
4965 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4966 UserHandle.USER_SYSTEM);
4967 DpmTestUtils.writeInputStreamToFile(
4968 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4969 getProfileOwnerPoliciesFile());
4970 DpmTestUtils.writeInputStreamToFile(
4971 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4972 getProfileOwnerFile());
4973 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4974 }
4975
Eran Messeribb271892018-10-17 18:27:50 +01004976 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
4977 setupProfileOwner();
4978 configureContextForAccess(mContext, false);
4979
4980 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4981 () -> dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin2,
4982 UserHandle.of(DpmMockContext.CALLER_UID)));
4983 }
4984
4985 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
4986 setupProfileOwner();
4987 configureContextForAccess(mContext, false);
4988
4989 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4990 () -> dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin1,
4991 UserHandle.of(DpmMockContext.CALLER_UID)));
4992 }
4993
4994 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
4995 setupProfileOwner();
4996
4997 // This method will throw if the system context could not call
4998 // setProfileOwnerCanAccessDeviceIds successfully.
4999 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5000 }
5001
5002 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5003 when(context.spiedContext.checkCallingPermission(
5004 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5005 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5006 : PackageManager.PERMISSION_DENIED);
5007 }
5008
5009 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5010 setupProfileOwner();
5011
5012 final long ident = mServiceContext.binder.clearCallingIdentity();
5013 configureContextForAccess(mServiceContext, true);
5014
5015 mServiceContext.binder.callingUid =
5016 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5017 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5018 try {
5019 runAsCaller(mServiceContext, dpms, dpm -> {
5020 dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin1,
5021 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE));
5022 });
5023 } finally {
5024 mServiceContext.binder.restoreCallingIdentity(ident);
5025 }
5026 }
5027
5028 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5029 throws Exception {
5030 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5031 setupDeviceOwner();
5032 configureContextForAccess(mContext, false);
5033
5034 // Device owner should be allowed to request Device ID attestation.
5035 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5036 DpmMockContext.CALLER_SYSTEM_USER_UID);
5037
5038 // Another package must not be allowed to request Device ID attestation.
5039 assertExpectException(SecurityException.class, null,
5040 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5041 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5042 // Another component that is not the admin must not be allowed to request Device ID
5043 // attestation.
5044 assertExpectException(SecurityException.class, null,
5045 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5046 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5047 }
5048
5049 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5050 throws Exception {
5051 configureContextForAccess(mContext, false);
5052
5053 // Make sure a security exception is thrown if the device has no profile owner.
5054 assertExpectException(SecurityException.class, null,
5055 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5056 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5057
5058 setupProfileOwner();
5059 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5060
5061 // The profile owner is allowed to request Device ID attestation.
5062 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5063 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5064 DpmMockContext.CALLER_UID);
5065 // But not another package.
5066 assertExpectException(SecurityException.class, null,
5067 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5068 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5069 // Or another component which is not the admin.
5070 assertExpectException(SecurityException.class, null,
5071 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5072 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5073 }
5074
5075 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5076 final long ident = mServiceContext.binder.clearCallingIdentity();
5077
5078 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5079 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5080 try {
5081 runAsCaller(mServiceContext, dpms, action);
5082 } finally {
5083 mServiceContext.binder.restoreCallingIdentity(ident);
5084 }
5085 }
5086
5087 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5088 setupProfileOwner();
5089 markDelegatedCertInstallerAsInstalled();
5090
5091 // Configure a delegated cert installer.
5092 runAsCaller(mServiceContext, dpms,
5093 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5094 Arrays.asList(DELEGATION_CERT_INSTALL)));
5095
5096 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5097
5098 // Make sure that the profile owner can still request Device ID attestation.
5099 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5100 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5101 DpmMockContext.CALLER_UID);
5102
5103 runAsDelegatedCertInstaller(dpm -> {
5104 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5105 DpmMockContext.DELEGATE_PACKAGE_NAME,
5106 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5107 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5108 });
5109 }
5110
5111 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5112 throws Exception {
5113 setupProfileOwner();
5114 markDelegatedCertInstallerAsInstalled();
5115
5116 // Configure a delegated cert installer.
5117 runAsCaller(mServiceContext, dpms,
5118 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5119 Arrays.asList(DELEGATION_CERT_INSTALL)));
5120
5121
5122 assertExpectException(SecurityException.class, null,
5123 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5124 admin1.getPackageName(),
5125 DpmMockContext.CALLER_UID));
5126
5127 runAsDelegatedCertInstaller(dpm -> {
5128 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5129 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5130 DpmMockContext.DELEGATE_PACKAGE_NAME,
5131 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5132 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5133 });
5134 }
5135
5136 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5137 final long ident = mServiceContext.binder.clearCallingIdentity();
5138 mServiceContext.binder.callingUid =
5139 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5140 runAsCaller(mServiceContext, dpms, dpm -> {
5141 dpm.setProfileOwnerCanAccessDeviceIdsForUser(who, UserHandle.of(userId));
5142 });
5143 mServiceContext.binder.restoreCallingIdentity(ident);
5144 }
5145
arangelov08d534b2018-01-22 15:20:53 +00005146 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5147 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5148 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5149 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5150
5151 final long ident = mServiceContext.binder.clearCallingIdentity();
5152 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5153 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5154 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5155 // To simulate a reboot, we just reinitialize dpms and call systemReady
5156 initializeDpms();
5157
5158 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5159 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5160 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5161 assertTrue(dpm.isAdminActive(admin1));
5162 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5163 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5164
5165 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5166 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5167 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5168 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5169
5170 mServiceContext.binder.restoreCallingIdentity(ident);
5171 }
5172
5173 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5174 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5175 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5176 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5177
5178 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5179 DpmMockContext.CALLER_SYSTEM_USER_UID);
5180 setUpPackageManagerForAdmin(admin1, uid);
5181 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5182 // To simulate a reboot, we just reinitialize dpms and call systemReady
5183 initializeDpms();
5184
5185 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5186 assertTrue(dpm.isAdminActive(admin1));
5187 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5188 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5189 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5190 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5191 }
5192
5193 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5194 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5195 metadataManager.deleteMetadataFile();
5196
5197 final TransferOwnershipMetadataManager.Metadata metadata =
5198 new TransferOwnershipMetadataManager.Metadata(
5199 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5200 callerUserHandle,
5201 adminType);
5202 metadataManager.saveMetadataFile(metadata);
5203 }
5204
5205 private File getDeviceOwnerFile() {
5206 return dpms.mOwners.getDeviceOwnerFile();
5207 }
5208
5209 private File getProfileOwnerFile() {
5210 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5211 }
5212
5213 private File getProfileOwnerPoliciesFile() {
5214 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5215 DpmMockContext.CALLER_USER_HANDLE);
5216 return getPoliciesFile(parentDir);
5217 }
5218
5219 private File getDeviceOwnerPoliciesFile() {
5220 return getPoliciesFile(getServices().systemUserDataDir);
5221 }
5222
5223 private File getPoliciesFile(File parentDir) {
5224 return new File(parentDir, "device_policies.xml");
5225 }
5226
5227 private InputStream getRawStream(@RawRes int id) {
5228 return mRealTestContext.getResources().openRawResource(id);
5229 }
5230
Victor Chang3e794af2016-03-04 13:48:17 +00005231 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005232 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005233 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5234 dpms.notifyChangeToContentObserver(
5235 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5236 }
5237
5238 private void assertProvisioningAllowed(String action, boolean expected) {
5239 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5240 dpm.isProvisioningAllowed(action));
5241 }
Tony Mak2f26b792016-11-28 17:54:51 +00005242
Nicolas Prevot45d29072017-01-18 16:11:19 +00005243 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5244 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005245 final String previousPackageName = mContext.packageName;
5246 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005247
5248 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5249 mContext.packageName = packageName;
5250 mMockContext.binder.callingUid = uid;
5251 assertProvisioningAllowed(action, expected);
5252
5253 // Set the previous package name / calling uid to go back to the initial state.
5254 mContext.packageName = previousPackageName;
5255 mMockContext.binder.callingUid = previousUid;
5256 }
5257
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005258 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005259 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5260 }
5261
5262 private void assertCheckProvisioningPreCondition(
5263 String action, String packageName, int provisioningCondition) {
5264 assertEquals("checkProvisioningPreCondition("
5265 + action + ", " + packageName + ") returning unexpected result",
5266 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005267 }
5268
Tony Mak2f26b792016-11-28 17:54:51 +00005269 /**
5270 * Setup a managed profile with the specified admin and its uid.
5271 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5272 * @param adminUid uid of the admin package.
5273 * @param copyFromAdmin package information for {@code admin} will be built based on this
5274 * component's information.
5275 */
5276 private void addManagedProfile(
5277 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5278 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005279 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005280 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5281 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5282 dpm.setActiveAdmin(admin, false, userId);
5283 assertTrue(dpm.setProfileOwner(admin, null, userId));
5284 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5285 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005286
5287 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005288 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005289 */
Robin Leeabaa0692017-02-20 20:54:22 +00005290 private static StringParceledListSlice asSlice(String[] s) {
5291 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005292 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005293
5294 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005295 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5296 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005297
Robin Lee2c68dad2017-03-17 12:50:24 +00005298 // We can't let exceptions happen on the background thread. Throw them here if they happen
5299 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005300 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005301 }
Victor Chang3e794af2016-03-04 13:48:17 +00005302}