blob: bbf837c2f682435ac8100f700c32f1471c67b4e5 [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;
Bernard Chaue9586552018-11-29 10:59:31 +000024import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
25import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
26import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
yinxuf4f9cec2017-06-19 10:28:19 -070027import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010028import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
29import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
30import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
31
Eugene Susla4f8680b2017-08-07 17:25:30 -070032import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010033
Pavel Grafov75c0a892017-05-18 17:28:27 +010034import static org.mockito.Matchers.any;
35import static org.mockito.Matchers.anyInt;
36import static org.mockito.Matchers.anyLong;
37import static org.mockito.Matchers.anyObject;
38import static org.mockito.Matchers.anyString;
39import static org.mockito.Matchers.eq;
40import static org.mockito.Matchers.isNull;
41import static org.mockito.Mockito.atLeast;
42import static org.mockito.Mockito.doAnswer;
43import static org.mockito.Mockito.doReturn;
44import static org.mockito.Mockito.never;
45import static org.mockito.Mockito.nullable;
46import static org.mockito.Mockito.reset;
47import static org.mockito.Mockito.timeout;
48import static org.mockito.Mockito.times;
49import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080050import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010051import static org.mockito.Mockito.verifyZeroInteractions;
52import static org.mockito.Mockito.when;
53import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000054import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010055
Makoto Onukif76b06a2015-09-22 15:03:44 -070056import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000057import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070058import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000059import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070060import android.app.admin.DeviceAdminReceiver;
61import android.app.admin.DevicePolicyManager;
62import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010063import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070064import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070065import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000066import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000067import android.content.pm.ApplicationInfo;
68import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070069import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010070import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000071import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000072import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010073import android.graphics.Color;
74import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080075import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070076import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080077import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070078import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070079import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010080import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080081import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010082import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000083import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000084import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000085import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080086import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000087import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010088import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070089import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070090
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010091import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000092import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000093import com.android.server.LocalServices;
94import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000095import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000096import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000097
Robin Lee7f5c91c2017-02-08 21:27:02 +000098import org.hamcrest.BaseMatcher;
99import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800100import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700101import org.mockito.invocation.InvocationOnMock;
102import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103
arangelov08d534b2018-01-22 15:20:53 +0000104import java.io.File;
105import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800106import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000107import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000108import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700109import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700110import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700111import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100112import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000113import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700114
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700116 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000117 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118 m FrameworksServicesTests &&
119 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000120 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700122 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700123
124 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000125 *
126 * , or:
127 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700128 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000129@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100130@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700131public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000132 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
133 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
134 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100135 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800136 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100137 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000138
Pavel Grafov75c0a892017-05-18 17:28:27 +0100139 // TODO replace all instances of this with explicit {@link #mServiceContext}.
140 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700141 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100142
143 private DpmMockContext mServiceContext;
144 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700145 public DevicePolicyManager dpm;
146 public DevicePolicyManagerServiceTestable dpms;
147
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100148 /*
149 * The CA cert below is the content of cacert.pem as generated by:
150 *
151 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
152 */
153 private static final String TEST_CA =
154 "-----BEGIN CERTIFICATE-----\n" +
155 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
156 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
157 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
158 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
159 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
160 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
161 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
162 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
163 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
164 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
165 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
166 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
167 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
168 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
169 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
170 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
171 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
172 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
173 "wQ==\n" +
174 "-----END CERTIFICATE-----\n";
175
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700176 @Override
177 protected void setUp() throws Exception {
178 super.setUp();
179
180 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100181 mServiceContext = mContext;
182 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
183 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700184 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100185 doReturn(Collections.singletonList(new ResolveInfo()))
186 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
187 any(Intent.class),
188 anyInt(),
189 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700190
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800191 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100192 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800193
Makoto Onukia52562c2015-10-01 16:12:31 -0700194 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700195
Sudheer Shanka101c3532018-01-08 16:28:42 -0800196 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800197 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700198 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
199 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
200 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800201 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700202
Pavel Grafov75c0a892017-05-18 17:28:27 +0100203 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
204 mAdmin1Context.packageName = admin1.getPackageName();
205 mAdmin1Context.applicationInfo = new ApplicationInfo();
206 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
207
Makoto Onukib643fb02015-09-22 15:03:44 -0700208 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100209
210 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700211 }
212
arangelov08d534b2018-01-22 15:20:53 +0000213 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
214 return dpms.mTransferOwnershipMetadataManager;
215 }
216
Robin Lee2c68dad2017-03-17 12:50:24 +0000217 @Override
218 protected void tearDown() throws Exception {
219 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000220 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000221 super.tearDown();
222 }
223
Makoto Onukia52562c2015-10-01 16:12:31 -0700224 private void initializeDpms() {
225 // Need clearCallingIdentity() to pass permission checks.
226 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100227 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700228
Pavel Grafov75c0a892017-05-18 17:28:27 +0100229 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
230 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
231 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700232
Pavel Grafov75c0a892017-05-18 17:28:27 +0100233 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700234
Pavel Grafov75c0a892017-05-18 17:28:27 +0100235 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700236 }
237
Makoto Onukib643fb02015-09-22 15:03:44 -0700238 private void setUpUserManager() {
239 // Emulate UserManager.set/getApplicationRestriction().
240 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
241
242 // UM.setApplicationRestrictions() will save to appRestrictions.
243 doAnswer(new Answer<Void>() {
244 @Override
245 public Void answer(InvocationOnMock invocation) throws Throwable {
246 String pkg = (String) invocation.getArguments()[0];
247 Bundle bundle = (Bundle) invocation.getArguments()[1];
248 UserHandle user = (UserHandle) invocation.getArguments()[2];
249
250 appRestrictions.put(Pair.create(pkg, user), bundle);
251
252 return null;
253 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100254 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100255 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700256
257 // UM.getApplicationRestrictions() will read from appRestrictions.
258 doAnswer(new Answer<Bundle>() {
259 @Override
260 public Bundle answer(InvocationOnMock invocation) throws Throwable {
261 String pkg = (String) invocation.getArguments()[0];
262 UserHandle user = (UserHandle) invocation.getArguments()[1];
263
264 return appRestrictions.get(Pair.create(pkg, user));
265 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100266 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700267 anyString(), any(UserHandle.class));
268
Makoto Onukid932f762015-09-29 16:53:38 -0700269 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100270 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700271 }
272
273 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100274 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700275
Pavel Grafov75c0a892017-05-18 17:28:27 +0100276 mServiceContext.binder.callingUid =
277 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
278 runAsCaller(mServiceContext, dpms, dpm -> {
279 // PO needs to be a DA.
280 dpm.setActiveAdmin(admin, /*replace=*/ false);
281 // Fire!
282 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
283 // Check
284 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
285 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700286
Pavel Grafov75c0a892017-05-18 17:28:27 +0100287 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700288 }
289
290 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100291 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700292 .thenReturn(false);
293
294 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100295 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700296
297 // If the device has no DPMS feature, it shouldn't register the local service.
298 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
299 }
300
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800301 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800302 // Device owner in SYSTEM_USER
303 setDeviceOwner();
304 // Profile owner in CALLER_USER_HANDLE
305 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
306 setAsProfileOwner(admin2);
307 // Active admin in CALLER_USER_HANDLE
308 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
309 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
310 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
311 DpmMockContext.CALLER_USER_HANDLE);
312 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
313 DpmMockContext.CALLER_USER_HANDLE));
314
315 initializeDpms();
316
317 // Verify
318 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800319 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800320 eq(UserHandle.USER_SYSTEM));
321 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800322 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800323 adminAnotherPackage.getPackageName()),
324 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800325 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
326 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
327 }
328
329 public void testLoadAdminData_noAdmins() throws Exception {
330 final int ANOTHER_USER_ID = 15;
331 getServices().addUser(ANOTHER_USER_ID, 0);
332
333 initializeDpms();
334
335 // Verify
336 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
337 null, DpmMockContext.CALLER_USER_HANDLE);
338 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
339 null, ANOTHER_USER_ID);
340 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
341 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800342 }
343
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700344 /**
345 * Caller doesn't have proper permissions.
346 */
347 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700348 // 1. Failure cases.
349
350 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100351 assertExpectException(SecurityException.class, /* messageRegex= */ null,
352 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700353
354 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
355 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100356
357 assertExpectException(SecurityException.class, /* messageRegex= */ null,
358 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700359 }
360
Makoto Onukif76b06a2015-09-22 15:03:44 -0700361 /**
362 * Test for:
363 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800364 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700365 * {@link DevicePolicyManager#isAdminActive}
366 * {@link DevicePolicyManager#isAdminActiveAsUser}
367 * {@link DevicePolicyManager#getActiveAdmins}
368 * {@link DevicePolicyManager#getActiveAdminsAsUser}
369 */
370 public void testSetActiveAdmin() throws Exception {
371 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700372 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
373
Makoto Onukif76b06a2015-09-22 15:03:44 -0700374 // 2. Call the API.
375 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700376
377 // 3. Verify internal calls.
378
379 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700380 verify(mContext.spiedContext).sendBroadcastAsUser(
381 MockUtils.checkIntentAction(
382 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
383 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
384 verify(mContext.spiedContext).sendBroadcastAsUser(
385 MockUtils.checkIntentAction(
386 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700387 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
388
Pavel Grafov75c0a892017-05-18 17:28:27 +0100389 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700390 eq(admin1.getPackageName()),
391 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
392 eq(PackageManager.DONT_KILL_APP),
393 eq(DpmMockContext.CALLER_USER_HANDLE),
394 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700395
Sudheer Shanka101c3532018-01-08 16:28:42 -0800396 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
397 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
398
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700399 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700400
401 // Make sure it's active admin1.
402 assertTrue(dpm.isAdminActive(admin1));
403 assertFalse(dpm.isAdminActive(admin2));
404 assertFalse(dpm.isAdminActive(admin3));
405
406 // But not admin1 for a different user.
407
408 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
409 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
410 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
411
412 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
413 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
414
415 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
416
417 // Next, add one more admin.
418 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700419 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700420 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700421
422 dpm.setActiveAdmin(admin2, /* replace =*/ false);
423
424 // Now we have two admins.
425 assertTrue(dpm.isAdminActive(admin1));
426 assertTrue(dpm.isAdminActive(admin2));
427 assertFalse(dpm.isAdminActive(admin3));
428
429 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
430 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100431 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700432 eq(admin1.getPackageName()),
433 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
434 eq(PackageManager.DONT_KILL_APP),
435 eq(DpmMockContext.CALLER_USER_HANDLE),
436 anyString());
437
Sudheer Shanka101c3532018-01-08 16:28:42 -0800438 // times(2) because it was previously called for admin1 which is in the same package
439 // as admin2.
440 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
441 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
442
Makoto Onukif76b06a2015-09-22 15:03:44 -0700443 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100444 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
445 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700446
447 // 5. Add the same admin1 again with replace, which should succeed.
448 dpm.setActiveAdmin(admin1, /* replace =*/ true);
449
450 // TODO make sure it's replaced.
451
452 // 6. Test getActiveAdmins()
453 List<ComponentName> admins = dpm.getActiveAdmins();
454 assertEquals(2, admins.size());
455 assertEquals(admin1, admins.get(0));
456 assertEquals(admin2, admins.get(1));
457
Sudheer Shanka101c3532018-01-08 16:28:42 -0800458 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
459 // replaced
460 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
461
Makoto Onukif76b06a2015-09-22 15:03:44 -0700462 // Another user has no admins.
463 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
464
465 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
466 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
467
468 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
469 }
470
Makoto Onukid932f762015-09-29 16:53:38 -0700471 public void testSetActiveAdmin_multiUsers() throws Exception {
472
473 final int ANOTHER_USER_ID = 100;
474 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
475
Pavel Grafov75c0a892017-05-18 17:28:27 +0100476 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700477
478 // Set up pacakge manager for the other user.
479 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700480
481 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
482
483 dpm.setActiveAdmin(admin1, /* replace =*/ false);
484
485 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
486 dpm.setActiveAdmin(admin2, /* replace =*/ false);
487
488
489 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
490 assertTrue(dpm.isAdminActive(admin1));
491 assertFalse(dpm.isAdminActive(admin2));
492
493 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
494 assertFalse(dpm.isAdminActive(admin1));
495 assertTrue(dpm.isAdminActive(admin2));
496 }
497
Makoto Onukif76b06a2015-09-22 15:03:44 -0700498 /**
499 * Test for:
500 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800501 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700502 */
503 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
504 // 1. Make sure the caller has proper permissions.
505 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
506
507 dpm.setActiveAdmin(admin1, /* replace =*/ false);
508 assertTrue(dpm.isAdminActive(admin1));
509
510 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100511 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
512 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700513 }
514
515 /**
516 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800517 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
518 * BIND_DEVICE_ADMIN.
519 */
520 public void testSetActiveAdmin_permissionCheck() throws Exception {
521 // 1. Make sure the caller has proper permissions.
522 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
523
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100524 assertExpectException(IllegalArgumentException.class,
525 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
526 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800527 assertFalse(dpm.isAdminActive(adminNoPerm));
528
529 // Change the target API level to MNC. Now it can be set as DA.
530 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
531 VERSION_CODES.M);
532 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
533 assertTrue(dpm.isAdminActive(adminNoPerm));
534
535 // TODO Test the "load from the file" case where DA will still be loaded even without
536 // BIND_DEVICE_ADMIN and target API is N.
537 }
538
539 /**
540 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700541 * {@link DevicePolicyManager#removeActiveAdmin}
542 */
543 public void testRemoveActiveAdmin_SecurityException() {
544 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
545
546 // Add admin.
547
548 dpm.setActiveAdmin(admin1, /* replace =*/ false);
549
550 assertTrue(dpm.isAdminActive(admin1));
551
552 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
553
554 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100555 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
556 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700557
558 // Try to remove active admin with a different caller userid should fail too, without
559 // having MANAGE_DEVICE_ADMINS.
560 mContext.callerPermissions.clear();
561
Makoto Onukid932f762015-09-29 16:53:38 -0700562 // Change the caller, and call into DPMS directly with a different user-id.
563
Makoto Onukif76b06a2015-09-22 15:03:44 -0700564 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100565 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
566 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700567 }
568
569 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800570 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
571 * (because we can't send the remove broadcast).
572 */
573 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
574 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
575
576 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
577
578 // Add admin.
579
580 dpm.setActiveAdmin(admin1, /* replace =*/ false);
581
582 assertTrue(dpm.isAdminActive(admin1));
583
584 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
585
586 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100587 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800588 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100589 assertExpectException(IllegalStateException.class,
590 /* messageRegex= */ "User must be running and unlocked",
591 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800592
593 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800594 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
595 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800596
597 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100598 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800599 .thenReturn(true);
600
601 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700602 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800603 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
604 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800605 }
606
607 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700608 * Test for:
609 * {@link DevicePolicyManager#removeActiveAdmin}
610 */
Makoto Onukid932f762015-09-29 16:53:38 -0700611 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700612 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
613
614 // Add admin1.
615
616 dpm.setActiveAdmin(admin1, /* replace =*/ false);
617
618 assertTrue(dpm.isAdminActive(admin1));
619 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
620
621 // Different user, but should work, because caller has proper permissions.
622 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700623
624 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700625 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700626
627 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700628 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800629 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
630 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700631
632 // TODO DO Still can't be removed in this case.
633 }
634
635 /**
636 * Test for:
637 * {@link DevicePolicyManager#removeActiveAdmin}
638 */
639 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
640 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
641 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
642
643 // Add admin1.
644
645 dpm.setActiveAdmin(admin1, /* replace =*/ false);
646
647 assertTrue(dpm.isAdminActive(admin1));
648 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
649
650 // Broadcast from saveSettingsLocked().
651 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
652 MockUtils.checkIntentAction(
653 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
654 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
655
656 // Remove. No permissions, but same user, so it'll work.
657 mContext.callerPermissions.clear();
658 dpm.removeActiveAdmin(admin1);
659
Makoto Onukif76b06a2015-09-22 15:03:44 -0700660 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
661 MockUtils.checkIntentAction(
662 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
663 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
664 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700665 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700666 eq(dpms.mHandler),
667 eq(Activity.RESULT_OK),
668 isNull(String.class),
669 isNull(Bundle.class));
670
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700671 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800672 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
673 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700674
675 // Again broadcast from saveSettingsLocked().
676 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
677 MockUtils.checkIntentAction(
678 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
679 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
680
681 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700682 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700683
Sudheer Shanka101c3532018-01-08 16:28:42 -0800684 public void testRemoveActiveAdmin_multipleAdminsInUser() {
685 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
686 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
687
688 // Add admin1.
689 dpm.setActiveAdmin(admin1, /* replace =*/ false);
690
691 assertTrue(dpm.isAdminActive(admin1));
692 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
693
694 // Add admin2.
695 dpm.setActiveAdmin(admin2, /* replace =*/ false);
696
697 assertTrue(dpm.isAdminActive(admin2));
698 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
699
700 // Broadcast from saveSettingsLocked().
701 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
702 MockUtils.checkIntentAction(
703 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
704 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
705
706 // Remove. No permissions, but same user, so it'll work.
707 mContext.callerPermissions.clear();
708 dpm.removeActiveAdmin(admin1);
709
710 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
711 MockUtils.checkIntentAction(
712 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
713 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
714 isNull(String.class),
715 any(BroadcastReceiver.class),
716 eq(dpms.mHandler),
717 eq(Activity.RESULT_OK),
718 isNull(String.class),
719 isNull(Bundle.class));
720
721 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
722 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800723 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800724 eq(DpmMockContext.CALLER_USER_HANDLE));
725
726 // Again broadcast from saveSettingsLocked().
727 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
728 MockUtils.checkIntentAction(
729 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
730 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
731 }
732
733 /**
734 * Test for:
735 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
736 */
737 public void testForceRemoveActiveAdmin() throws Exception {
738 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
739
740 // Add admin.
741 setupPackageInPackageManager(admin1.getPackageName(),
742 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
743 /* appId= */ 10138,
744 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
745 dpm.setActiveAdmin(admin1, /* replace =*/ false);
746 assertTrue(dpm.isAdminActive(admin1));
747
748 // Calling from a non-shell uid should fail with a SecurityException
749 mContext.binder.callingUid = 123456;
750 assertExpectException(SecurityException.class,
751 /* messageRegex =*/ "Non-shell user attempted to call",
752 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
753
754 mContext.binder.callingUid = Process.SHELL_UID;
755 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
756
757 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
758 // Verify
759 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
760 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
761 null, DpmMockContext.CALLER_USER_HANDLE);
762 }
763
Makoto Onukib643fb02015-09-22 15:03:44 -0700764 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000765 * Test for: @{link DevicePolicyManager#setActivePasswordState}
766 *
767 * Validates that when the password for a user changes, the notification broadcast intent
768 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
769 * addition to ones in the original user.
770 */
771 public void testSetActivePasswordState_sendToProfiles() throws Exception {
772 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
773
774 final int MANAGED_PROFILE_USER_ID = 78;
775 final int MANAGED_PROFILE_ADMIN_UID =
776 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
777
778 // Setup device owner.
779 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
780 mContext.packageName = admin1.getPackageName();
781 setupDeviceOwner();
782
783 // Add a managed profile belonging to the system user.
784 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
785
786 // Change the parent user's password.
787 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
788
789 // Both the device owner and the managed profile owner should receive this broadcast.
790 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
791 intent.setComponent(admin1);
792 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
793
794 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
795 MockUtils.checkIntent(intent),
796 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
797 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
798 MockUtils.checkIntent(intent),
799 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
800 }
801
802 /**
803 * Test for: @{link DevicePolicyManager#setActivePasswordState}
804 *
805 * Validates that when the password for a managed profile changes, the notification broadcast
806 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
807 * its parent.
808 */
809 public void testSetActivePasswordState_notSentToParent() throws Exception {
810 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
811
812 final int MANAGED_PROFILE_USER_ID = 78;
813 final int MANAGED_PROFILE_ADMIN_UID =
814 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
815
816 // Setup device owner.
817 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
818 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100819 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000820 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
821 setupDeviceOwner();
822
823 // Add a managed profile belonging to the system user.
824 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
825
826 // Change the profile's password.
827 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
828
829 // Both the device owner and the managed profile owner should receive this broadcast.
830 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
831 intent.setComponent(admin1);
832 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
833
834 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
835 MockUtils.checkIntent(intent),
836 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
837 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
838 MockUtils.checkIntent(intent),
839 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
840 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100841
Robin Leed2a73ed2016-12-19 09:07:16 +0000842 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000843 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700844 */
845 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000846 setDeviceOwner();
847
848 // Try to set a profile owner on the same user, which should fail.
849 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
850 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100851 assertExpectException(IllegalStateException.class,
852 /* messageRegex= */ "already has a device owner",
853 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000854
855 // DO admin can't be deactivated.
856 dpm.removeActiveAdmin(admin1);
857 assertTrue(dpm.isAdminActive(admin1));
858
859 // TODO Test getDeviceOwnerName() too. To do so, we need to change
860 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
861 }
862
863 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700864 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800865 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700866 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
867 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
868
Makoto Onukid932f762015-09-29 16:53:38 -0700869 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700870 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
871
Makoto Onukid932f762015-09-29 16:53:38 -0700872 // Make sure admin1 is installed on system user.
873 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700874
Makoto Onukic8a5a552015-11-19 14:29:12 -0800875 // Check various get APIs.
876 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
877
Makoto Onukib643fb02015-09-22 15:03:44 -0700878 // DO needs to be an DA.
879 dpm.setActiveAdmin(admin1, /* replace =*/ false);
880
881 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700882 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700883
Makoto Onukic8a5a552015-11-19 14:29:12 -0800884 // getDeviceOwnerComponent should return the admin1 component.
885 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
886 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
887
888 // Check various get APIs.
889 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
890
891 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
892 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
893 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
894 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
895
896 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
897
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000898 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100899 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000900 eq(admin1.getPackageName()));
901
Makoto Onukib643fb02015-09-22 15:03:44 -0700902 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100903 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700904 eq(UserHandle.USER_SYSTEM), eq(false));
905
906 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
907 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
908 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
909
Makoto Onukic8a5a552015-11-19 14:29:12 -0800910 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700911 }
912
Makoto Onukic8a5a552015-11-19 14:29:12 -0800913 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
914 final int origCallingUser = mContext.binder.callingUid;
915 final List origPermissions = new ArrayList(mContext.callerPermissions);
916 mContext.callerPermissions.clear();
917
918 mContext.callerPermissions.add(permission.MANAGE_USERS);
919
920 mContext.binder.callingUid = Process.SYSTEM_UID;
921
922 // TODO Test getDeviceOwnerName() too. To do so, we need to change
923 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
924 if (hasDeviceOwner) {
925 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
926 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
927 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
928
929 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
930 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
931 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
932 } else {
933 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
934 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
935 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
936
937 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
938 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
939 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
940 }
941
942 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
943 if (hasDeviceOwner) {
944 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
945 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
946 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
947
948 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
949 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
950 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
951 } else {
952 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
953 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
954 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
955
956 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
957 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
958 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
959 }
960
961 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
962 // Still with MANAGE_USERS.
963 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
964 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
965 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
966
967 if (hasDeviceOwner) {
968 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
969 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
970 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
971 } else {
972 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
973 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
974 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
975 }
976
977 mContext.binder.callingUid = Process.SYSTEM_UID;
978 mContext.callerPermissions.remove(permission.MANAGE_USERS);
979 // System can still call "OnAnyUser" without MANAGE_USERS.
980 if (hasDeviceOwner) {
981 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
982 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
983 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
984
985 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
986 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
987 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
988 } else {
989 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
990 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
991 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
992
993 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
994 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
995 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
996 }
997
998 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
999 // Still no MANAGE_USERS.
1000 if (hasDeviceOwner) {
1001 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1002 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1003 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1004 } else {
1005 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1006 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1007 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1008 }
1009
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001010 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1011 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1012 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1013 dpm::getDeviceOwnerComponentOnAnyUser);
1014 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1015 dpm::getDeviceOwnerUserId);
1016 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1017 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001018
1019 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1020 // Still no MANAGE_USERS.
1021 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1022 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1023 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1024
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001025 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1026 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1027 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1028 dpm::getDeviceOwnerComponentOnAnyUser);
1029 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1030 dpm::getDeviceOwnerUserId);
1031 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1032 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001033
1034 // Restore.
1035 mContext.binder.callingUid = origCallingUser;
1036 mContext.callerPermissions.addAll(origPermissions);
1037 }
1038
1039
Makoto Onukib643fb02015-09-22 15:03:44 -07001040 /**
1041 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1042 */
1043 public void testSetDeviceOwner_noSuchPackage() {
1044 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001045 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001046 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1047 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1048
1049 // Call from a process on the system user.
1050 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1051
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001052 assertExpectException(IllegalArgumentException.class,
1053 /* messageRegex= */ "Invalid component",
1054 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001055 }
1056
1057 public void testSetDeviceOwner_failures() throws Exception {
1058 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1059 }
1060
Makoto Onukia52562c2015-10-01 16:12:31 -07001061 public void testClearDeviceOwner() throws Exception {
1062 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001063 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001064 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1065 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1066
1067 // Set admin1 as a DA to the secondary user.
1068 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1069
1070 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1071
1072 // Set admin 1 as the DO to the system user.
1073
1074 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1075 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1076 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1077 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1078
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001079 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001080 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001081 eq(admin1.getPackageName()));
1082
Makoto Onukic8a5a552015-11-19 14:29:12 -08001083 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001084
Makoto Onuki90b89652016-01-28 14:44:18 -08001085 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001086 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001087 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001088
1089 assertTrue(dpm.isAdminActive(admin1));
1090 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1091
Makoto Onukia52562c2015-10-01 16:12:31 -07001092 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001093 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001094
1095 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001096 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1097 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001098
1099 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001100 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001101 assertExpectException(IllegalStateException.class,
1102 /* messageRegex= */ "User must be running and unlocked",
1103 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001104
Pavel Grafov75c0a892017-05-18 17:28:27 +01001105 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1106 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001107 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1108
1109 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001110 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001111
Pavel Grafov75c0a892017-05-18 17:28:27 +01001112 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001113 eq(false),
1114 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1115
Pavel Grafov75c0a892017-05-18 17:28:27 +01001116 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001117 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001118 eq(null),
1119 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001120
Sudheer Shanka101c3532018-01-08 16:28:42 -08001121 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1122 null, UserHandle.USER_SYSTEM);
1123
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001124 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001125
1126 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1127 // and once for clearing it.
1128 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1129 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1130 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001131 // TODO Check other calls.
1132 }
1133
1134 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1135 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001136 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001137 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1138 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1139
1140 // Set admin1 as a DA to the secondary user.
1141 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1142
1143 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1144
1145 // Set admin 1 as the DO to the system user.
1146
1147 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1148 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1149 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1150 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1151
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001152 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001153 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001154 eq(admin1.getPackageName()));
1155
Makoto Onukic8a5a552015-11-19 14:29:12 -08001156 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001157
1158 // Now call clear from the secondary user, which should throw.
1159 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1160
1161 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001162 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001163 eq(admin1.getPackageName()),
1164 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001165 assertExpectException(SecurityException.class,
1166 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1167 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001168
Makoto Onukic8a5a552015-11-19 14:29:12 -08001169 // DO shouldn't be removed.
1170 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001171 }
1172
Makoto Onukib643fb02015-09-22 15:03:44 -07001173 public void testSetProfileOwner() throws Exception {
1174 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001175
Makoto Onuki90b89652016-01-28 14:44:18 -08001176 // PO admin can't be deactivated.
1177 dpm.removeActiveAdmin(admin1);
1178 assertTrue(dpm.isAdminActive(admin1));
1179
Makoto Onuki803d6752015-10-30 12:58:39 -07001180 // Try setting DO on the same user, which should fail.
1181 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001182 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1183 runAsCaller(mServiceContext, dpms, dpm -> {
1184 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001185 assertExpectException(IllegalStateException.class,
1186 /* messageRegex= */ "already has a profile owner",
1187 () -> dpm.setDeviceOwner(admin2, "owner-name",
1188 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001189 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001190 }
1191
Makoto Onuki90b89652016-01-28 14:44:18 -08001192 public void testClearProfileOwner() throws Exception {
1193 setAsProfileOwner(admin1);
1194
1195 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1196
1197 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1198 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1199
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001200 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001201 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001202 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001203 assertExpectException(IllegalStateException.class,
1204 /* messageRegex= */ "User must be running and unlocked",
1205 () -> dpm.clearProfileOwner(admin1));
1206
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001207 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001208 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001209 dpm.clearProfileOwner(admin1);
1210
1211 // Check
1212 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001213 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001214 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1215 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001216 }
1217
Makoto Onukib643fb02015-09-22 15:03:44 -07001218 public void testSetProfileOwner_failures() throws Exception {
1219 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1220 }
1221
Makoto Onukia52562c2015-10-01 16:12:31 -07001222 public void testGetDeviceOwnerAdminLocked() throws Exception {
1223 checkDeviceOwnerWithMultipleDeviceAdmins();
1224 }
1225
1226 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1227 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1228 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1229 // make sure it gets the right component from the right user.
1230
1231 final int ANOTHER_USER_ID = 100;
1232 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1233
Pavel Grafov75c0a892017-05-18 17:28:27 +01001234 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001235
1236 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001237 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001238 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1239 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1240
1241 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1242
Pavel Grafov75c0a892017-05-18 17:28:27 +01001243 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001244
Makoto Onukia52562c2015-10-01 16:12:31 -07001245 // Make sure the admin packge is installed to each user.
1246 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1247 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1248
1249 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1250 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1251
1252 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1253
1254
1255 // Set active admins to the users.
1256 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1257 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1258
1259 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1260 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1261
1262 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1263
1264 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001265 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001266 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1267
Makoto Onukic8a5a552015-11-19 14:29:12 -08001268 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001269
1270 // Then check getDeviceOwnerAdminLocked().
1271 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1272 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1273 }
1274
1275 /**
1276 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001277 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1278 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001279 *
1280 * We didn't use to persist the DO component class name, but now we do, and the above method
1281 * finds the right component from a package name upon migration.
1282 */
1283 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001284 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001285 checkDeviceOwnerWithMultipleDeviceAdmins();
1286
1287 // Overwrite the device owner setting and clears the clas name.
1288 dpms.mOwners.setDeviceOwner(
1289 new ComponentName(admin2.getPackageName(), ""),
1290 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1291 dpms.mOwners.writeDeviceOwner();
1292
1293 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001294 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001295
1296 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001297 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001298 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001299 initializeDpms();
1300
1301 // Now the DO component name is a full name.
1302 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1303 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001304 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001305 }
1306
Makoto Onukib643fb02015-09-22 15:03:44 -07001307 public void testSetGetApplicationRestriction() {
1308 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001309 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001310
1311 {
1312 Bundle rest = new Bundle();
1313 rest.putString("KEY_STRING", "Foo1");
1314 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1315 }
1316
1317 {
1318 Bundle rest = new Bundle();
1319 rest.putString("KEY_STRING", "Foo2");
1320 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1321 }
1322
1323 {
1324 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1325 assertNotNull(returned);
1326 assertEquals(returned.size(), 1);
1327 assertEquals(returned.get("KEY_STRING"), "Foo1");
1328 }
1329
1330 {
1331 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1332 assertNotNull(returned);
1333 assertEquals(returned.size(), 1);
1334 assertEquals(returned.get("KEY_STRING"), "Foo2");
1335 }
1336
1337 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1338 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1339 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001340
Edman Anjosf9946772016-11-28 16:35:15 +01001341 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001342 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1343 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001344 *
1345 * @param packageName the name of the package to be setup
1346 * @param appId the application ID to be given to the package
1347 * @return the UID of the package as known by the mock package manager
1348 */
1349 private int setupPackageInPackageManager(final String packageName, final int appId)
1350 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001351 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001352 ApplicationInfo.FLAG_HAS_CODE);
1353 }
1354
1355 /**
1356 * Setup a package in the package manager mock. Useful for faking installed applications.
1357 *
1358 * @param packageName the name of the package to be setup
1359 * @param userId the user id where the package will be "installed"
1360 * @param appId the application ID to be given to the package
1361 * @param flags flags to set in the ApplicationInfo for this package
1362 * @return the UID of the package as known by the mock package manager
1363 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001364 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1365 int flags) throws Exception {
1366 final int uid = UserHandle.getUid(userId, appId);
1367 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001368 final PackageInfo pi = new PackageInfo();
1369 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001370 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001371 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001372 eq(packageName),
1373 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001374 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001375 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001376 eq(packageName),
1377 anyInt(),
1378 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001379 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001380 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001381 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001382 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001383 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001384 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001385 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001386 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001387 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001388 return uid;
1389 }
1390
Robin Lee7f5c91c2017-02-08 21:27:02 +00001391 public void testCertificateDisclosure() throws Exception {
1392 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1393 final UserHandle user = UserHandle.of(userId);
1394
1395 mContext.applicationInfo = new ApplicationInfo();
1396 mContext.callerPermissions.add(permission.MANAGE_USERS);
1397 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001398 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001399 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1400
Robin Leeabaa0692017-02-20 20:54:22 +00001401 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1402 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001403
1404 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1405 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1406
1407 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001408 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001409 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001410 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001411 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001412 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001413 .cancelAsUser(anyString(), anyInt(), eq(user));
1414
1415 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001416 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001417 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001418 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1419 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001420 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001421 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001422 .notifyAsUser(anyString(), anyInt(), argThat(
1423 new BaseMatcher<Notification>() {
1424 @Override
1425 public boolean matches(Object item) {
1426 final Notification noti = (Notification) item;
1427 return TEST_STRING.equals(
1428 noti.extras.getString(Notification.EXTRA_TITLE));
1429 }
1430 @Override
1431 public void describeTo(Description description) {
1432 description.appendText(
1433 "Notification{title=\"" + TEST_STRING + "\"}");
1434 }
1435 }), eq(user));
1436 }
1437
Edman Anjosf9946772016-11-28 16:35:15 +01001438 /**
1439 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1440 * privileges can acually be exercised by a delegate are not covered here.
1441 */
1442 public void testDelegation() throws Exception {
1443 setAsProfileOwner(admin1);
1444
1445 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1446
1447 // Given two packages
1448 final String CERT_DELEGATE = "com.delegate.certs";
1449 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1450 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1451 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1452 20989);
1453
1454 // On delegation
1455 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1456 mContext.packageName = admin1.getPackageName();
1457 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1458 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1459
1460 // DPMS correctly stores and retrieves the delegates
1461 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1462 assertEquals(2, policy.mDelegationMap.size());
1463 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1464 DELEGATION_CERT_INSTALL);
1465 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1466 DELEGATION_CERT_INSTALL);
1467 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1468 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1469 DELEGATION_APP_RESTRICTIONS);
1470 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1471 DELEGATION_APP_RESTRICTIONS);
1472 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1473
1474 // On calling install certificate APIs from an unauthorized process
1475 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1476 mContext.packageName = RESTRICTIONS_DELEGATE;
1477
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001478 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1479 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001480
1481 // On calling install certificate APIs from an authorized process
1482 mContext.binder.callingUid = CERT_DELEGATE_UID;
1483 mContext.packageName = CERT_DELEGATE;
1484
1485 // DPMS executes without a SecurityException
1486 try {
1487 dpm.installCaCert(null, null);
1488 } catch (SecurityException unexpected) {
1489 fail("Threw SecurityException on authorized access");
1490 } catch (NullPointerException expected) {
1491 }
1492
1493 // On removing a delegate
1494 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1495 mContext.packageName = admin1.getPackageName();
1496 dpm.setCertInstallerPackage(admin1, null);
1497
1498 // DPMS does not allow access to ex-delegate
1499 mContext.binder.callingUid = CERT_DELEGATE_UID;
1500 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001501 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1502 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001503
1504 // But still allows access to other existing delegates
1505 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1506 mContext.packageName = RESTRICTIONS_DELEGATE;
1507 try {
1508 dpm.getApplicationRestrictions(null, "pkg");
1509 } catch (SecurityException expected) {
1510 fail("Threw SecurityException on authorized access");
1511 }
1512 }
1513
Esteban Talaverabf60f722015-12-10 16:26:44 +00001514 public void testApplicationRestrictionsManagingApp() throws Exception {
1515 setAsProfileOwner(admin1);
1516
Rubin Xued1928a2016-02-11 17:23:06 +00001517 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001518 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001519 final String nonDelegateExceptionMessageRegex =
1520 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001521 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001522 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1523 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001524
Esteban Talaverabf60f722015-12-10 16:26:44 +00001525 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1526 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001527 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1528 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001529 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001530 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001531 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001532 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1533 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001534
1535 // Check via the profile owner that no restrictions were set.
1536 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001537 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001538 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1539
Rubin Xued1928a2016-02-11 17:23:06 +00001540 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001541 assertExpectException(PackageManager.NameNotFoundException.class,
1542 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1543 () -> dpm.setApplicationRestrictionsManagingPackage(
1544 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001545
Esteban Talaverabf60f722015-12-10 16:26:44 +00001546 // Let appRestrictionsManagerPackage manage app restrictions
1547 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1548 assertEquals(appRestrictionsManagerPackage,
1549 dpm.getApplicationRestrictionsManagingPackage(admin1));
1550
1551 // Now that package should be able to set and retrieve app restrictions.
1552 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001553 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001554 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1555 dpm.setApplicationRestrictions(null, "pkg1", rest);
1556 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1557 assertEquals(1, returned.size(), 1);
1558 assertEquals("Foo1", returned.get("KEY_STRING"));
1559
1560 // The same app running on a separate user shouldn't be able to manage app restrictions.
1561 mContext.binder.callingUid = UserHandle.getUid(
1562 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1563 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001564 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1565 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001566
1567 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1568 // too.
1569 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001570 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001571 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1572 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1573 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1574
1575 // Removing the ability for the package to manage app restrictions.
1576 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1577 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1578 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001579 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001580 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001581 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1582 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001583 }
1584
Makoto Onukia4f11972015-10-01 13:19:58 -07001585 public void testSetUserRestriction_asDo() throws Exception {
1586 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001587 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001588 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1589 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1590
1591 // First, set DO.
1592
1593 // Call from a process on the system user.
1594 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1595
1596 // Make sure admin1 is installed on system user.
1597 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001598
1599 // Call.
1600 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001601 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001602 UserHandle.USER_SYSTEM));
1603
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001604 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001605 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001606 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001607 DpmTestUtils.assertRestrictions(
1608 DpmTestUtils.newRestrictions(defaultRestrictions),
1609 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1610 );
1611 DpmTestUtils.assertRestrictions(
1612 DpmTestUtils.newRestrictions(defaultRestrictions),
1613 dpm.getUserRestrictions(admin1)
1614 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001615 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001616 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001617 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001618 eq(true) /* isDeviceOwner */,
1619 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001620 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001621 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001622
1623 for (String restriction : defaultRestrictions) {
1624 dpm.clearUserRestriction(admin1, restriction);
1625 }
1626
Esteban Talavera548a04b2016-12-20 15:22:30 +00001627 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001628 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001629
1630 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001631 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001632 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001633 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1634 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001635 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001636
Makoto Onukia4f11972015-10-01 13:19:58 -07001637 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001638 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001639 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001640 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1641 UserManager.DISALLOW_ADD_USER),
1642 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001643 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001644
Makoto Onuki068c54a2015-10-13 14:34:03 -07001645 DpmTestUtils.assertRestrictions(
1646 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001647 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001648 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1649 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001650 DpmTestUtils.assertRestrictions(
1651 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001652 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001653 dpm.getUserRestrictions(admin1)
1654 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001655
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001656 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001657 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001658 eq(UserHandle.USER_SYSTEM),
1659 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001660 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001661 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001662
Makoto Onuki068c54a2015-10-13 14:34:03 -07001663 DpmTestUtils.assertRestrictions(
1664 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1665 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1666 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001667 DpmTestUtils.assertRestrictions(
1668 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1669 dpm.getUserRestrictions(admin1)
1670 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001671
1672 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001673 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 eq(UserHandle.USER_SYSTEM),
1675 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001676 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001677 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001678
Esteban Talavera548a04b2016-12-20 15:22:30 +00001679 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001680
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1682 // DO sets them, the scope is global.
1683 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001684 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001685 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001686 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001688 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001689 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1690 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001691 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001692
1693 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1694 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001695 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001696
1697 // More tests.
1698 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001699 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001701 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1702 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001703 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001704
1705 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001706 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001707 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001708 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001709 UserManager.DISALLOW_ADD_USER),
1710 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001711 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001712
1713 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001714 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715 eq(UserHandle.USER_SYSTEM),
1716 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001717 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001718 UserManager.DISALLOW_ADD_USER),
1719 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001720 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001721 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722
Eric Sandnessca5969d2018-08-10 13:28:46 +01001723 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1724 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1725 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001726
Eric Sandnessca5969d2018-08-10 13:28:46 +01001727 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1728 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001729
Eric Sandnessca5969d2018-08-10 13:28:46 +01001730 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1731 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1732 () -> dpm.setCameraDisabled(admin1, true));
1733 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1734
1735 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1736 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1737 () -> dpm.setKeyguardDisabledFeatures(admin1,
1738 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1739 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1740
1741 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1742 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1743 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1744 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1745
1746 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1747 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1748 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1749 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001750 }
1751
1752 public void testSetUserRestriction_asPo() {
1753 setAsProfileOwner(admin1);
1754
Makoto Onuki068c54a2015-10-13 14:34:03 -07001755 DpmTestUtils.assertRestrictions(
1756 DpmTestUtils.newRestrictions(),
1757 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1758 .ensureUserRestrictions()
1759 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001760
1761 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001762 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001763 eq(DpmMockContext.CALLER_USER_HANDLE),
1764 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001765 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001766 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001767
Makoto Onukia4f11972015-10-01 13:19:58 -07001768 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001769 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001770 eq(DpmMockContext.CALLER_USER_HANDLE),
1771 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1772 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001773 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001774 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001775
Makoto Onuki068c54a2015-10-13 14:34:03 -07001776 DpmTestUtils.assertRestrictions(
1777 DpmTestUtils.newRestrictions(
1778 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1779 UserManager.DISALLOW_OUTGOING_CALLS
1780 ),
1781 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1782 .ensureUserRestrictions()
1783 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001784 DpmTestUtils.assertRestrictions(
1785 DpmTestUtils.newRestrictions(
1786 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1787 UserManager.DISALLOW_OUTGOING_CALLS
1788 ),
1789 dpm.getUserRestrictions(admin1)
1790 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001791
1792 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001793 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001794 eq(DpmMockContext.CALLER_USER_HANDLE),
1795 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001796 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001797 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001798
1799 DpmTestUtils.assertRestrictions(
1800 DpmTestUtils.newRestrictions(
1801 UserManager.DISALLOW_OUTGOING_CALLS
1802 ),
1803 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1804 .ensureUserRestrictions()
1805 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001806 DpmTestUtils.assertRestrictions(
1807 DpmTestUtils.newRestrictions(
1808 UserManager.DISALLOW_OUTGOING_CALLS
1809 ),
1810 dpm.getUserRestrictions(admin1)
1811 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001812
1813 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001814 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001815 eq(DpmMockContext.CALLER_USER_HANDLE),
1816 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001817 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001818 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001819
Makoto Onuki068c54a2015-10-13 14:34:03 -07001820 DpmTestUtils.assertRestrictions(
1821 DpmTestUtils.newRestrictions(),
1822 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1823 .ensureUserRestrictions()
1824 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001825 DpmTestUtils.assertRestrictions(
1826 DpmTestUtils.newRestrictions(),
1827 dpm.getUserRestrictions(admin1)
1828 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001829
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001830 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1831 // though when DO sets them they'll be applied globally.
1832 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001833 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001834 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001835 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001836 eq(DpmMockContext.CALLER_USER_HANDLE),
1837 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1838 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001839 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001840 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001841
1842 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001843 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001844 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001845 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001846 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001847 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001848 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001849
Makoto Onukia4f11972015-10-01 13:19:58 -07001850 // TODO Make sure restrictions are written to the file.
1851 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001852
Esteban Talavera548a04b2016-12-20 15:22:30 +00001853
1854 public void testDefaultEnabledUserRestrictions() throws Exception {
1855 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1856 mContext.callerPermissions.add(permission.MANAGE_USERS);
1857 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1858 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1859
1860 // First, set DO.
1861
1862 // Call from a process on the system user.
1863 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1864
1865 // Make sure admin1 is installed on system user.
1866 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1867
1868 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1869 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1870 UserHandle.USER_SYSTEM));
1871
1872 // Check that the user restrictions that are enabled by default are set. Then unset them.
1873 String[] defaultRestrictions = UserRestrictionsUtils
1874 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1875 assertTrue(defaultRestrictions.length > 0);
1876 DpmTestUtils.assertRestrictions(
1877 DpmTestUtils.newRestrictions(defaultRestrictions),
1878 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1879 );
1880 DpmTestUtils.assertRestrictions(
1881 DpmTestUtils.newRestrictions(defaultRestrictions),
1882 dpm.getUserRestrictions(admin1)
1883 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001884 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001885 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001886 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001887 eq(true) /* isDeviceOwner */,
1888 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001889 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001890 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001891
1892 for (String restriction : defaultRestrictions) {
1893 dpm.clearUserRestriction(admin1, restriction);
1894 }
1895
1896 assertNoDeviceOwnerRestrictions();
1897
1898 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001899 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001900 initializeDpms();
1901 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1902 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1903
1904 assertNoDeviceOwnerRestrictions();
1905
1906 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1907 // is set as it wasn't enabled during setDeviceOwner.
1908 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1909 assertFalse(UserRestrictionsUtils
1910 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1911 UserRestrictionsUtils
1912 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1913 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001914 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001915 initializeDpms();
1916 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1917 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1918
1919 DpmTestUtils.assertRestrictions(
1920 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1921 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1922 );
1923 DpmTestUtils.assertRestrictions(
1924 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1925 dpm.getUserRestrictions(admin1)
1926 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001927 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001928 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001929 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001930 eq(true) /* isDeviceOwner */,
1931 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001932 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001933 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001934
1935 // Remove the restriction.
1936 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1937
1938 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1939 initializeDpms();
1940 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1941 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1942 assertNoDeviceOwnerRestrictions();
1943 } finally {
1944 UserRestrictionsUtils
1945 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1946 }
1947 }
1948
1949 private void assertNoDeviceOwnerRestrictions() {
1950 DpmTestUtils.assertRestrictions(
1951 DpmTestUtils.newRestrictions(),
1952 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1953 );
1954 DpmTestUtils.assertRestrictions(
1955 DpmTestUtils.newRestrictions(),
1956 dpm.getUserRestrictions(admin1)
1957 );
1958 }
1959
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001960 public void testGetMacAddress() throws Exception {
1961 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1962 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1963 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1964
1965 // In this test, change the caller user to "system".
1966 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1967
1968 // Make sure admin1 is installed on system user.
1969 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1970
1971 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001972 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1973 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001974
1975 // DO needs to be an DA.
1976 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1977 assertTrue(dpm.isAdminActive(admin1));
1978
1979 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001980 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1981 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001982
1983 // Test 3. Caller has PO, but not DO.
1984 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001985 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1986 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001987
1988 // Remove PO.
1989 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001990 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001991 // Test 4, Caller is DO now.
1992 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1993
xshu425b9a62018-12-13 14:18:18 -08001994 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001995 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001996
xshu425b9a62018-12-13 14:18:18 -08001997 // 4-2. When WifiManager returns an empty array, dpm should also output null.
1998 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001999 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002000
2001 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002002 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2003 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002004 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002005 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002006
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002007 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002008 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2009 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2010
2011 // In this test, change the caller user to "system".
2012 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2013
2014 // Make sure admin1 is installed on system user.
2015 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2016
2017 // Set admin1 as DA.
2018 dpm.setActiveAdmin(admin1, false);
2019 assertTrue(dpm.isAdminActive(admin1));
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 // Set admin1 as PO.
2024 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002025 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2026 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002027
2028 // Remove PO and add DO.
2029 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002030 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002031 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2032
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002033 // admin1 is DO.
2034 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002035 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002036 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002037 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2038 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002039
2040 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002041 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002042 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002043 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2044 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002045
2046 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002047 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002048 dpm.reboot(admin1);
2049 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002050
2051 public void testSetGetSupportText() {
2052 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2053 dpm.setActiveAdmin(admin1, true);
2054 dpm.setActiveAdmin(admin2, true);
2055 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2056
2057 // Null default support messages.
2058 {
2059 assertNull(dpm.getLongSupportMessage(admin1));
2060 assertNull(dpm.getShortSupportMessage(admin1));
2061 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2062 assertNull(dpm.getShortSupportMessageForUser(admin1,
2063 DpmMockContext.CALLER_USER_HANDLE));
2064 assertNull(dpm.getLongSupportMessageForUser(admin1,
2065 DpmMockContext.CALLER_USER_HANDLE));
2066 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2067 }
2068
2069 // Only system can call the per user versions.
2070 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002071 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2072 () -> dpm.getShortSupportMessageForUser(admin1,
2073 DpmMockContext.CALLER_USER_HANDLE));
2074 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2075 () -> dpm.getLongSupportMessageForUser(admin1,
2076 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002077 }
2078
2079 // Can't set message for admin in another uid.
2080 {
2081 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002082 assertExpectException(SecurityException.class,
2083 /* messageRegex= */ "is not owned by uid",
2084 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002085 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2086 }
2087
2088 // Set/Get short returns what it sets and other admins text isn't changed.
2089 {
2090 final String supportText = "Some text to test with.";
2091 dpm.setShortSupportMessage(admin1, supportText);
2092 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2093 assertNull(dpm.getLongSupportMessage(admin1));
2094 assertNull(dpm.getShortSupportMessage(admin2));
2095
2096 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2097 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2098 DpmMockContext.CALLER_USER_HANDLE));
2099 assertNull(dpm.getShortSupportMessageForUser(admin2,
2100 DpmMockContext.CALLER_USER_HANDLE));
2101 assertNull(dpm.getLongSupportMessageForUser(admin1,
2102 DpmMockContext.CALLER_USER_HANDLE));
2103 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2104
2105 dpm.setShortSupportMessage(admin1, null);
2106 assertNull(dpm.getShortSupportMessage(admin1));
2107 }
2108
2109 // Set/Get long returns what it sets and other admins text isn't changed.
2110 {
2111 final String supportText = "Some text to test with.\nWith more text.";
2112 dpm.setLongSupportMessage(admin1, supportText);
2113 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2114 assertNull(dpm.getShortSupportMessage(admin1));
2115 assertNull(dpm.getLongSupportMessage(admin2));
2116
2117 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2118 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2119 DpmMockContext.CALLER_USER_HANDLE));
2120 assertNull(dpm.getLongSupportMessageForUser(admin2,
2121 DpmMockContext.CALLER_USER_HANDLE));
2122 assertNull(dpm.getShortSupportMessageForUser(admin1,
2123 DpmMockContext.CALLER_USER_HANDLE));
2124 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2125
2126 dpm.setLongSupportMessage(admin1, null);
2127 assertNull(dpm.getLongSupportMessage(admin1));
2128 }
2129 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002130
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002131 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002132 setAsProfileOwner(admin1);
2133
2134 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002135 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002136
2137 // Setup
2138 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2139 final String package1 = "com.example.one";
2140 final String package2 = "com.example.two";
2141 pkgsToRestrict.add(package1);
2142 pkgsToRestrict.add(package2);
2143 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2144 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002145 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002146
2147 // Verify
2148 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002149 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002150 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2151 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2152 eq(DpmMockContext.CALLER_USER_HANDLE));
2153
2154 // Setup
2155 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002156 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002157
2158 // Verify
2159 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002160 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002161 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2162 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2163 eq(DpmMockContext.CALLER_USER_HANDLE));
2164 }
2165
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002166 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002167 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2168 dpm.setActiveAdmin(admin1, true);
2169 assertTrue(dpm.isAdminActive(admin1));
2170 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2171
2172 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002173 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002174 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002175 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002176 }
2177
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002178 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002179 setAsProfileOwner(admin1);
2180
2181 // Setup
2182 final ArrayList<String> emptyList = new ArrayList<>();
2183 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2184 final String package1 = "com.example.one";
2185 final String package2 = "com.example.two";
2186 final String package3 = "com.example.three";
2187 pkgsToRestrict.add(package1);
2188 pkgsToRestrict.add(package2);
2189 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2190 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002191 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002192
2193 // Verify
2194 assertEquals(emptyList, excludedPkgs);
2195 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2196 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002197 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002198 DpmMockContext.CALLER_USER_HANDLE));
2199 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002200 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002201 DpmMockContext.CALLER_USER_HANDLE));
2202 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002203 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002204 DpmMockContext.CALLER_USER_HANDLE));
2205 }
2206
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002207 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002208 setAsProfileOwner(admin1);
2209 assertExpectException(SecurityException.class,
2210 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002211 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002212 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2213 dpm.clearProfileOwner(admin1);
2214
2215 setDeviceOwner();
2216 assertExpectException(SecurityException.class,
2217 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002218 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002219 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2220 clearDeviceOwner();
2221 }
2222
phweiss73145f42017-01-17 19:06:38 +01002223 public void testCreateAdminSupportIntent() throws Exception {
2224 // Setup device owner.
2225 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2226 setupDeviceOwner();
2227
2228 // Nonexisting permission returns null
2229 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2230 assertNull(intent);
2231
2232 // Existing permission that is not set returns null
2233 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2234 assertNull(intent);
2235
2236 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002237 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002238 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2239 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2240 .thenReturn(true);
2241 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2242 assertNull(intent);
2243
2244 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002245 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002246 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2247 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2248 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2249 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2250 assertNotNull(intent);
2251 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2252 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2253 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002254 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002255 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2256 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2257
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002258 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2259 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002260
2261 // Camera is not disabled
2262 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2263 assertNull(intent);
2264
2265 // Camera is disabled
2266 dpm.setCameraDisabled(admin1, true);
2267 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2268 assertNotNull(intent);
2269 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2270 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2271
2272 // Screen capture is not disabled
2273 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2274 assertNull(intent);
2275
2276 // Screen capture is disabled
2277 dpm.setScreenCaptureDisabled(admin1, true);
2278 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2279 assertNotNull(intent);
2280 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2281 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2282
2283 // Same checks for different user
2284 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2285 // Camera should be disabled by device owner
2286 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2287 assertNotNull(intent);
2288 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2289 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2290 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2291 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2292 // ScreenCapture should not be disabled by device owner
2293 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2294 assertNull(intent);
2295 }
2296
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002297 /**
2298 * Test for:
2299 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002300 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002301 * {@link DevicePolicyManager#isAffiliatedUser}
2302 */
2303 public void testUserAffiliation() throws Exception {
2304 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2305 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2306 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2307
2308 // Check that the system user is unaffiliated.
2309 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2310 assertFalse(dpm.isAffiliatedUser());
2311
2312 // Set a device owner on the system user. Check that the system user becomes affiliated.
2313 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2314 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2315 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2316 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002317 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002318
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002319 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002320 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2321 setAsProfileOwner(admin2);
2322 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002323 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002324
2325 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2326 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002327 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002328 userAffiliationIds.add("red");
2329 userAffiliationIds.add("green");
2330 userAffiliationIds.add("blue");
2331 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002332 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002333 assertFalse(dpm.isAffiliatedUser());
2334
2335 // Have the device owner specify a set of affiliation ids that do not intersect with those
2336 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002337 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002338 deviceAffiliationIds.add("cyan");
2339 deviceAffiliationIds.add("yellow");
2340 deviceAffiliationIds.add("magenta");
2341 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2342 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002343 MoreAsserts.assertContentsInAnyOrder(
2344 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002345 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2346 assertFalse(dpm.isAffiliatedUser());
2347
2348 // Have the profile owner specify a set of affiliation ids that intersect with those
2349 // specified by the device owner. Check that the test user becomes affiliated.
2350 userAffiliationIds.add("yellow");
2351 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002352 MoreAsserts.assertContentsInAnyOrder(
2353 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002354 assertTrue(dpm.isAffiliatedUser());
2355
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002356 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002357 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002358 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002359 assertFalse(dpm.isAffiliatedUser());
2360
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002361 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2362 dpm.setAffiliationIds(admin2, userAffiliationIds);
2363 assertTrue(dpm.isAffiliatedUser());
2364 dpm.clearProfileOwner(admin2);
2365 assertFalse(dpm.isAffiliatedUser());
2366
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002367 // Check that the system user remains affiliated.
2368 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2369 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002370
2371 // Clear the device owner - the user becomes unaffiliated.
2372 clearDeviceOwner();
2373 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002374 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002375
2376 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002377 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002378 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2379 }
2380
2381 public void testSetUserProvisioningState_permission() throws Exception {
2382 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002383
2384 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2385 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2386 }
2387
2388 public void testSetUserProvisioningState_unprivileged() throws Exception {
2389 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002390 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2391 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2392 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002393 }
2394
2395 public void testSetUserProvisioningState_noManagement() {
2396 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002397 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002398 assertExpectException(IllegalStateException.class,
2399 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2400 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2401 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002402 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2403 }
2404
2405 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2406 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2407 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002408
2409 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2410 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2411 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2412 }
2413
2414 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2415 throws Exception {
2416 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2417 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002418
2419 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2420 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2421 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2422 }
2423
2424 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2425 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2426 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002427
2428 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2429 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2430 }
2431
2432 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2433 throws Exception {
2434 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002435
2436 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2437 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2438 DevicePolicyManager.STATE_USER_UNMANAGED);
2439 }
2440
2441 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2442 throws Exception {
2443 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002444
2445 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2446 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2447 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2448 }
2449
2450 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2451 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002452
2453 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2454 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2455 }
2456
2457 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2458 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002459
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002460 assertExpectException(IllegalStateException.class,
2461 /* messageRegex= */ "Cannot move to user provisioning state",
2462 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2463 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2464 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002465 }
2466
2467 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2468 throws Exception {
2469 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002470
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002471 assertExpectException(IllegalStateException.class,
2472 /* messageRegex= */ "Cannot move to user provisioning state",
2473 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2474 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2475 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002476 }
2477
2478 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002479 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2480 mContext.callerPermissions.add(permission.MANAGE_USERS);
2481
Alan Treadwayafad8782016-01-19 15:15:08 +00002482 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2483 for (int state : states) {
2484 dpm.setUserProvisioningState(state, userId);
2485 assertEquals(state, dpm.getUserProvisioningState());
2486 }
2487 }
2488
2489 private void setupProfileOwner() throws Exception {
2490 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2491
2492 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2493 dpm.setActiveAdmin(admin1, false);
2494 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2495
2496 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2497 }
2498
2499 private void setupDeviceOwner() throws Exception {
2500 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2501
2502 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2503 dpm.setActiveAdmin(admin1, false);
2504 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2505
2506 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2507 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002508
2509 public void testSetMaximumTimeToLock() {
2510 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2511
2512 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2513 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2514
Pavel Grafov75c0a892017-05-18 17:28:27 +01002515 reset(getServices().powerManagerInternal);
2516 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002517
2518 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002519 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2520 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002521 reset(getServices().powerManagerInternal);
2522 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002523
2524 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002525 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2526 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002527 reset(getServices().powerManagerInternal);
2528 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002529
2530 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002531 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2532 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002533 reset(getServices().powerManagerInternal);
2534 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002535
2536 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002537 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2538 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002539 reset(getServices().powerManagerInternal);
2540 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002541
2542 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002543 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2544 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002545 reset(getServices().powerManagerInternal);
2546 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002547
2548 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002549 reset(getServices().powerManagerInternal);
2550 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002551
Pavel Grafov28939982017-10-03 15:11:52 +01002552 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2553 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2554 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002555 reset(getServices().powerManagerInternal);
2556 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002557
2558 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002559 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2560 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002561 reset(getServices().powerManagerInternal);
2562 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002563
Pavel Grafov28939982017-10-03 15:11:52 +01002564 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002565 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002566 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2567 verifyStayOnWhilePluggedCleared(false);
2568 }
2569
2570 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2571 // uses separate challenge.
2572 public void testSetMaximumTimeToLockProfile() throws Exception {
2573 final int PROFILE_USER = 15;
2574 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2575 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2576 mContext.binder.callingUid = PROFILE_ADMIN;
2577 final DevicePolicyManagerInternal dpmi =
2578 LocalServices.getService(DevicePolicyManagerInternal.class);
2579
2580 dpm.setMaximumTimeToLock(admin1, 0);
2581
2582 reset(getServices().powerManagerInternal);
2583 reset(getServices().settings);
2584
2585 // First add timeout for the profile.
2586 dpm.setMaximumTimeToLock(admin1, 10);
2587 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2588
2589 reset(getServices().powerManagerInternal);
2590 reset(getServices().settings);
2591
2592 // Add separate challenge
2593 when(getServices().lockPatternUtils
2594 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2595 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2596
2597 verifyScreenTimeoutCall(10L, PROFILE_USER);
2598 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2599
2600 reset(getServices().powerManagerInternal);
2601 reset(getServices().settings);
2602
2603 // Remove the timeout.
2604 dpm.setMaximumTimeToLock(admin1, 0);
2605 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2606 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2607
2608 reset(getServices().powerManagerInternal);
2609 reset(getServices().settings);
2610
2611 // Add it back.
2612 dpm.setMaximumTimeToLock(admin1, 10);
2613 verifyScreenTimeoutCall(10L, PROFILE_USER);
2614 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2615
2616 reset(getServices().powerManagerInternal);
2617 reset(getServices().settings);
2618
2619 // Remove separate challenge.
2620 reset(getServices().lockPatternUtils);
2621 when(getServices().lockPatternUtils
2622 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2623 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002624 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002625
2626 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2627 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2628
2629 reset(getServices().powerManagerInternal);
2630 reset(getServices().settings);
2631
2632 // Remove the timeout.
2633 dpm.setMaximumTimeToLock(admin1, 0);
2634 verifyScreenTimeoutCall(null, PROFILE_USER);
2635 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002636 }
2637
Michal Karpinski943aabd2016-10-06 11:09:25 +01002638 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2639 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2640 setupDeviceOwner();
2641 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2642
Michal Karpinskid084ca52017-01-18 15:54:18 +00002643 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2644 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2645 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2646 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2647 - ONE_MINUTE;
2648
2649 // verify that the minimum timeout cannot be modified on user builds (system property is
2650 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002651 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002652
2653 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2654 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2655 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2656
Pavel Grafov75c0a892017-05-18 17:28:27 +01002657 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002658
2659 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002660 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002661
Michal Karpinskid084ca52017-01-18 15:54:18 +00002662 // reset to default (0 means the admin is not participating, so default should be returned)
2663 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002664
2665 // aggregation should be the default if unset by any admin
2666 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2667 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2668
2669 // admin not participating by default
2670 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2671
2672 //clamping from the top
2673 dpm.setRequiredStrongAuthTimeout(admin1,
2674 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2675 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2676 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2677 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2678 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2679
Michal Karpinskid084ca52017-01-18 15:54:18 +00002680 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002681 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2682 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2683 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2684 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2685
2686 // clamping from the bottom
2687 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2688 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2689 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2690
Michal Karpinskid084ca52017-01-18 15:54:18 +00002691 // values within range
2692 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2693 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2694 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2695
2696 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2697 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2698 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002699
2700 // reset to default
2701 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2702 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2703 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2704 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2705
2706 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002707 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2708 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002709 }
2710
Pavel Grafov28939982017-10-03 15:11:52 +01002711 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002712 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002713 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002714 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002715 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002716 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002717 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002718 }
Pavel Grafov28939982017-10-03 15:11:52 +01002719 }
2720
2721 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002722 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2723 // UnfinishedVerificationException.
2724 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002725
Esteban Talavera01576862016-12-15 11:16:44 +00002726 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002727 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002728 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002729 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002730 .thenReturn(false);
2731 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002732 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2733 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002734 .thenReturn(true);
2735 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2736
2737 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002738 }
Victor Chang3e794af2016-03-04 13:48:17 +00002739
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002740 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2741 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002742 mContext.packageName = admin1.getPackageName();
2743 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002744 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2745 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2746 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2747 false);
2748 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2749 }
2750
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002751 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2752 setup_DeviceAdminFeatureOff();
2753 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2754 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2755 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2756 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2757 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2758 assertCheckProvisioningPreCondition(
2759 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2760 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2761 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2762 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2763 }
2764
Esteban Talavera01576862016-12-15 11:16:44 +00002765 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002766 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002767 .thenReturn(false);
2768 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002769 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2770 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002771 .thenReturn(true);
2772 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2773
2774 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002775 }
Victor Chang3e794af2016-03-04 13:48:17 +00002776
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002777 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2778 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002779 mContext.packageName = admin1.getPackageName();
2780 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002781 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2782 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2784 false);
2785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2786
2787 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002788 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002789 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2790 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2791 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2792 true);
2793 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2794 }
2795
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002796 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2797 setup_ManagedProfileFeatureOff();
2798 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2799 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2800 DevicePolicyManager.CODE_OK);
2801 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2802 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2803 assertCheckProvisioningPreCondition(
2804 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2805 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2806 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2807 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2808
2809 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002810 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002811 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2812 DevicePolicyManager.CODE_OK);
2813 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2814 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2815 assertCheckProvisioningPreCondition(
2816 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2817 DevicePolicyManager.CODE_OK);
2818 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2819 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2820 }
2821
Esteban Talavera01576862016-12-15 11:16:44 +00002822 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002823 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002824 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002825 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2826 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002827 .thenReturn(true);
2828 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2829
2830 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002831 }
Victor Chang3e794af2016-03-04 13:48:17 +00002832
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002833 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2834 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002835 mContext.packageName = admin1.getPackageName();
2836 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002837 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2838 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2839 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2840 false /* because of non-split user */);
2841 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2842 false /* because of non-split user */);
2843 }
2844
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002845 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002846 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002847 setup_nonSplitUser_firstBoot_primaryUser();
2848 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2849 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2850 DevicePolicyManager.CODE_OK);
2851 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2852 DevicePolicyManager.CODE_OK);
2853 assertCheckProvisioningPreCondition(
2854 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2855 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2856 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2857 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2858 }
2859
Esteban Talavera01576862016-12-15 11:16:44 +00002860 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002861 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002862 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002863 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2864 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002865 .thenReturn(true);
2866 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2867
2868 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002869 }
Victor Chang3e794af2016-03-04 13:48:17 +00002870
Nicolas Prevot45d29072017-01-18 16:11:19 +00002871 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2872 setDeviceOwner();
2873 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2874 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2875 }
2876
2877 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2878 setup_nonSplitUser_withDo_primaryUser();
2879 final int MANAGED_PROFILE_USER_ID = 18;
2880 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2881 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002882 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002883 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002884 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002885 true)).thenReturn(true);
2886 }
2887
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002888 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2889 throws Exception {
2890 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002891 mContext.packageName = admin1.getPackageName();
2892 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002893 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2894 false/* because of completed device setup */);
2895 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2896 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2897 false/* because of non-split user */);
2898 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2899 false/* because of non-split user */);
2900 }
2901
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002902 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2903 throws Exception {
2904 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2905 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2906 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2907 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2908 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2909 DevicePolicyManager.CODE_OK);
2910 assertCheckProvisioningPreCondition(
2911 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2912 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2913 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2914 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2915 }
2916
Nicolas Prevot45d29072017-01-18 16:11:19 +00002917 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2918 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002919 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002920 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2921
2922 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2923 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002924 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002925
2926 // COMP mode is allowed.
2927 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2928 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002929 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002930
Nicolas Prevot45d29072017-01-18 16:11:19 +00002931 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002932 assertCheckProvisioningPreCondition(
2933 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002934 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002935 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002936 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2937 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2938 }
Esteban Talavera01576862016-12-15 11:16:44 +00002939
Nicolas Prevot45d29072017-01-18 16:11:19 +00002940 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2941 setup_nonSplitUser_withDo_primaryUser();
2942 mContext.packageName = admin1.getPackageName();
2943 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2944 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2945 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002946 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002947 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2948 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2949 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002950 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002951 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2952 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2953 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2954 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2955 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002956 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002957 assertCheckProvisioningPreCondition(
2958 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002959 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002960 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002961 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2962 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2963 }
Esteban Talavera01576862016-12-15 11:16:44 +00002964
Nicolas Prevot45d29072017-01-18 16:11:19 +00002965 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2966 throws Exception {
2967 setup_nonSplitUser_withDo_primaryUser();
2968 mContext.packageName = admin1.getPackageName();
2969 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002970 // The DO should not be allowed to initiate provisioning if the restriction is set by
2971 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002972 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002973 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2974 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2975 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002976 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002977 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2978 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2979 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2980 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2981 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002982 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2983
2984 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002985 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002986 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002987 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002988 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2989 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2990 }
2991
2992 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2993 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2994 mContext.packageName = admin1.getPackageName();
2995 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2996
2997 // We can delete the managed profile to create a new one, so provisioning is allowed.
2998 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2999 DevicePolicyManager.CODE_OK);
3000 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3001 assertCheckProvisioningPreCondition(
3002 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3003 DpmMockContext.ANOTHER_PACKAGE_NAME,
3004 DevicePolicyManager.CODE_OK);
3005 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3006 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3007 }
3008
3009 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3010 throws Exception {
3011 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3012 mContext.packageName = admin1.getPackageName();
3013 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003014 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003015 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3016 eq(UserHandle.SYSTEM)))
3017 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003018 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003019 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3020 eq(UserHandle.SYSTEM)))
3021 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003022
3023 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003024 assertCheckProvisioningPreCondition(
3025 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3026 DpmMockContext.ANOTHER_PACKAGE_NAME,
3027 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3028 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3029 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003030
3031 // But the device owner can still do it because it has set the restriction itself.
3032 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3033 DevicePolicyManager.CODE_OK);
3034 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003035 }
3036
3037 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003038 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003039 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003040 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3041 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003042 .thenReturn(false);
3043 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3044
3045 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003046 }
Victor Chang3e794af2016-03-04 13:48:17 +00003047
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003048 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3049 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003050 mContext.packageName = admin1.getPackageName();
3051 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003052 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3053 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3054 false /* because canAddMoreManagedProfiles returns false */);
3055 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3056 true);
3057 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3058 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003059 }
3060
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003061 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3062 throws Exception {
3063 setup_splitUser_firstBoot_systemUser();
3064 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3065 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3066 DevicePolicyManager.CODE_OK);
3067 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003068 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003069 assertCheckProvisioningPreCondition(
3070 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3071 DevicePolicyManager.CODE_OK);
3072 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3073 DevicePolicyManager.CODE_SYSTEM_USER);
3074 }
3075
Esteban Talavera01576862016-12-15 11:16:44 +00003076 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003077 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003078 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003079 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3080 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003081 .thenReturn(false);
3082 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3083
3084 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003085 }
Victor Chang3e794af2016-03-04 13:48:17 +00003086
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003087 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3088 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003089 mContext.packageName = admin1.getPackageName();
3090 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003091 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3092 true/* it's undefined behavior. Can be changed into false in the future */);
3093 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3094 false /* because canAddMoreManagedProfiles returns false */);
3095 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3096 true/* it's undefined behavior. Can be changed into false in the future */);
3097 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3098 false/* because calling uid is system user */);
3099 }
3100
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003101 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3102 throws Exception {
3103 setup_splitUser_afterDeviceSetup_systemUser();
3104 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3105 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3106 DevicePolicyManager.CODE_OK);
3107 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003108 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003109 assertCheckProvisioningPreCondition(
3110 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3111 DevicePolicyManager.CODE_OK);
3112 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3113 DevicePolicyManager.CODE_SYSTEM_USER);
3114 }
3115
Esteban Talavera01576862016-12-15 11:16:44 +00003116 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003117 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003118 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003119 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3120 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003121 true)).thenReturn(true);
3122 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3123
3124 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003125 }
Victor Chang3e794af2016-03-04 13:48:17 +00003126
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003127 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3128 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003129 mContext.packageName = admin1.getPackageName();
3130 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003131 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3132 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3133 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3134 true);
3135 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003136 }
3137
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003138 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003139 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003140 setup_splitUser_firstBoot_primaryUser();
3141 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3142 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3143 DevicePolicyManager.CODE_OK);
3144 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3145 DevicePolicyManager.CODE_OK);
3146 assertCheckProvisioningPreCondition(
3147 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3148 DevicePolicyManager.CODE_OK);
3149 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3150 DevicePolicyManager.CODE_OK);
3151 }
3152
Esteban Talavera01576862016-12-15 11:16:44 +00003153 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003154 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003155 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003156 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3157 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003158 true)).thenReturn(true);
3159 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3160
3161 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003162 }
Victor Chang3e794af2016-03-04 13:48:17 +00003163
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003164 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3165 throws Exception {
3166 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003167 mContext.packageName = admin1.getPackageName();
3168 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003169 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3170 true/* it's undefined behavior. Can be changed into false in the future */);
3171 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3172 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3173 true/* it's undefined behavior. Can be changed into false in the future */);
3174 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3175 false/* because user setup completed */);
3176 }
3177
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003178 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003179 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003180 setup_splitUser_afterDeviceSetup_primaryUser();
3181 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3182 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3183 DevicePolicyManager.CODE_OK);
3184 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3185 DevicePolicyManager.CODE_OK);
3186 assertCheckProvisioningPreCondition(
3187 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3188 DevicePolicyManager.CODE_OK);
3189 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3190 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3191 }
3192
Esteban Talavera01576862016-12-15 11:16:44 +00003193 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003194 setDeviceOwner();
3195
Pavel Grafov75c0a892017-05-18 17:28:27 +01003196 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003197 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003198 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3199 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003200 .thenReturn(false);
3201 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3202
3203 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003204 }
Victor Chang3e794af2016-03-04 13:48:17 +00003205
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003206 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3207 throws Exception {
3208 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003209 mContext.packageName = admin1.getPackageName();
3210 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003211 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3212 false /* can't provision managed profile on system user */);
3213 }
3214
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003215 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003216 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003217 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3218 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3219 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3220 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3221 }
3222
3223 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003224 setDeviceOwner();
3225
Pavel Grafov75c0a892017-05-18 17:28:27 +01003226 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003227 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003228 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3229 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003230 true)).thenReturn(true);
3231 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3232
3233 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003234 }
Victor Chang3e794af2016-03-04 13:48:17 +00003235
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003236 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3237 throws Exception {
3238 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003239 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3240 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003241 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3242 }
3243
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003244 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003245 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003246 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3247 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003248
3249 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003250 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3251 DevicePolicyManager.CODE_OK);
3252 }
3253
3254 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003255 setDeviceOwner();
3256
Pavel Grafov75c0a892017-05-18 17:28:27 +01003257 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003258 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003259 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3260 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003261 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3262 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003263 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003264 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003265 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003266 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003267 true)).thenReturn(true);
3268 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3269
3270 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003271 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003272
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003273 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3274 throws Exception {
3275 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003276 mContext.packageName = admin1.getPackageName();
3277 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003278 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3279 }
3280
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003281 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3282 throws Exception {
3283 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3284 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3285 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3286 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3287 }
3288
3289 public void testCheckProvisioningPreCondition_permission() {
3290 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003291 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3292 () -> dpm.checkProvisioningPreCondition(
3293 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003294 }
3295
Victor Chang3577ed22016-08-25 18:49:26 +01003296 public void testForceUpdateUserSetupComplete_permission() {
3297 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003298 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3299 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003300 }
3301
3302 public void testForceUpdateUserSetupComplete_systemUser() {
3303 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3304 // GIVEN calling from user 20
3305 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003306 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3307 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003308 }
3309
3310 public void testForceUpdateUserSetupComplete_userbuild() {
3311 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3312 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3313
3314 final int userId = UserHandle.USER_SYSTEM;
3315 // GIVEN userComplete is false in SettingsProvider
3316 setUserSetupCompleteForUser(false, userId);
3317
3318 // GIVEN userComplete is true in DPM
3319 DevicePolicyManagerService.DevicePolicyData userData =
3320 new DevicePolicyManagerService.DevicePolicyData(userId);
3321 userData.mUserSetupComplete = true;
3322 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3323
3324 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003325 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003326
3327 assertTrue(dpms.hasUserSetupCompleted());
3328
3329 dpm.forceUpdateUserSetupComplete();
3330
3331 // THEN the state in dpms is not changed
3332 assertTrue(dpms.hasUserSetupCompleted());
3333 }
3334
3335 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3336 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3337 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3338
3339 final int userId = UserHandle.USER_SYSTEM;
3340 // GIVEN userComplete is false in SettingsProvider
3341 setUserSetupCompleteForUser(false, userId);
3342
3343 // GIVEN userComplete is true in DPM
3344 DevicePolicyManagerService.DevicePolicyData userData =
3345 new DevicePolicyManagerService.DevicePolicyData(userId);
3346 userData.mUserSetupComplete = true;
3347 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3348
3349 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003350 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003351
3352 assertTrue(dpms.hasUserSetupCompleted());
3353
3354 dpm.forceUpdateUserSetupComplete();
3355
3356 // THEN the state in dpms is not changed
3357 assertFalse(dpms.hasUserSetupCompleted());
3358 }
3359
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003360 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003361 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003362 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003363
3364 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3365 runAsCaller(mAdmin1Context, dpms, dpm -> {
3366 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3367 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003368 }
3369
3370 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3371 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3372 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003373
3374 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3375 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003376 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003377 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3378 .thenReturn(true);
3379
3380 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003381 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003382
3383 // Enabling logging should not change the timestamp.
3384 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003385 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003386 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003387 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003388 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003389 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003390
3391 // Retrieving the logs should update the timestamp.
3392 final long beforeRetrieval = System.currentTimeMillis();
3393 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003394 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003395 final long afterRetrieval = System.currentTimeMillis();
3396 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3397 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3398
3399 // Retrieving the pre-boot logs should update the timestamp.
3400 Thread.sleep(2);
3401 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003402 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003403 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3404
3405 // Checking the timestamp again should not change it.
3406 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003407 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003408
3409 // Retrieving the logs again should update the timestamp.
3410 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003411 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003412 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3413
3414 // Disabling logging should not change the timestamp.
3415 Thread.sleep(2);
3416 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003417 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003418
3419 // Restarting the DPMS should not lose the timestamp.
3420 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003421 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003422
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003423 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3424 mContext.binder.callingUid = 1234567;
3425 mContext.callerPermissions.add(permission.MANAGE_USERS);
3426 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3427 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3428
3429 // System can retrieve the timestamp.
3430 mContext.binder.clearCallingIdentity();
3431 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3432
3433 // Removing the device owner should clear the timestamp.
3434 clearDeviceOwner();
3435 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003436 }
3437
yuemingw0de748d2017-11-15 19:22:27 +00003438 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3439 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3440 setupDeviceOwner();
3441 assertExpectException(SecurityException.class, null, () ->
3442 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3443 }
3444
yuemingwc0281f12018-03-28 15:58:49 +01003445 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003446 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3447 setupDeviceOwner();
3448 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003449 verify(getServices().settings).settingsSystemPutStringForUser(
3450 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3451 }
3452
3453 public void testSetSystemSettingWithPO() throws Exception {
3454 setupProfileOwner();
3455 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3456 verify(getServices().settings).settingsSystemPutStringForUser(
3457 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003458 }
3459
yuemingwe43cdf72017-10-12 16:52:11 +01003460 public void testSetTime() throws Exception {
3461 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3462 setupDeviceOwner();
3463 dpm.setTime(admin1, 0);
3464 verify(getServices().alarmManager).setTime(0);
3465 }
3466
3467 public void testSetTimeFailWithPO() throws Exception {
3468 setupProfileOwner();
3469 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3470 }
3471
3472 public void testSetTimeWithAutoTimeOn() throws Exception {
3473 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3474 setupDeviceOwner();
3475 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3476 .thenReturn(1);
3477 assertFalse(dpm.setTime(admin1, 0));
3478 }
3479
3480 public void testSetTimeZone() throws Exception {
3481 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3482 setupDeviceOwner();
3483 dpm.setTimeZone(admin1, "Asia/Shanghai");
3484 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3485 }
3486
3487 public void testSetTimeZoneFailWithPO() throws Exception {
3488 setupProfileOwner();
3489 assertExpectException(SecurityException.class, null,
3490 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3491 }
3492
3493 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3494 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3495 setupDeviceOwner();
3496 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3497 .thenReturn(1);
3498 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3499 }
3500
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003501 public void testGetLastBugReportRequestTime() throws Exception {
3502 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3503 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003504
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003505 mContext.packageName = admin1.getPackageName();
3506 mContext.applicationInfo = new ApplicationInfo();
3507 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3508 .thenReturn(Color.WHITE);
3509 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3510 anyObject())).thenReturn(Color.WHITE);
3511
Esteban Talaverad36dd152016-12-15 08:51:45 +00003512 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3513 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003514 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003515
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003516 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003517 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003518
3519 // Requesting a bug report should update the timestamp.
3520 final long beforeRequest = System.currentTimeMillis();
3521 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003522 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003523 final long afterRequest = System.currentTimeMillis();
3524 assertTrue(bugReportRequestTime >= beforeRequest);
3525 assertTrue(bugReportRequestTime <= afterRequest);
3526
3527 // Checking the timestamp again should not change it.
3528 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003529 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003530
3531 // Restarting the DPMS should not lose the timestamp.
3532 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003533 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003534
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003535 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3536 mContext.binder.callingUid = 1234567;
3537 mContext.callerPermissions.add(permission.MANAGE_USERS);
3538 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3539 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3540
3541 // System can retrieve the timestamp.
3542 mContext.binder.clearCallingIdentity();
3543 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3544
3545 // Removing the device owner should clear the timestamp.
3546 clearDeviceOwner();
3547 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003548 }
3549
3550 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3551 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3552 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003553 mContext.packageName = admin1.getPackageName();
3554 mContext.applicationInfo = new ApplicationInfo();
3555 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3556 .thenReturn(Color.WHITE);
3557 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3558 anyObject())).thenReturn(Color.WHITE);
3559
3560 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3561 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003562 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003563 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003564 .thenReturn(true);
3565
3566 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003567 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003568
3569 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3570 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003571 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003572
3573 // Enabling logging should not change the timestamp.
3574 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003575 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003576
3577 // Retrieving the logs should update the timestamp.
3578 final long beforeRetrieval = System.currentTimeMillis();
3579 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003580 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003581 final long afterRetrieval = System.currentTimeMillis();
3582 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3583 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3584
3585 // Checking the timestamp again should not change it.
3586 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003587 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003588
3589 // Retrieving the logs again should update the timestamp.
3590 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003591 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003592 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3593
3594 // Disabling logging should not change the timestamp.
3595 Thread.sleep(2);
3596 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003597 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003598
3599 // Restarting the DPMS should not lose the timestamp.
3600 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003601 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3602
3603 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3604 mContext.binder.callingUid = 1234567;
3605 mContext.callerPermissions.add(permission.MANAGE_USERS);
3606 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3607 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3608
3609 // System can retrieve the timestamp.
3610 mContext.binder.clearCallingIdentity();
3611 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3612
3613 // Removing the device owner should clear the timestamp.
3614 clearDeviceOwner();
3615 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003616 }
3617
Tony Mak2f26b792016-11-28 17:54:51 +00003618 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3619 // Setup device owner.
3620 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3621 setupDeviceOwner();
3622
3623 // Only device owner is setup, the result list should be empty.
3624 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3625 MoreAsserts.assertEmpty(targetUsers);
3626
3627 // Setup a managed profile managed by the same admin.
3628 final int MANAGED_PROFILE_USER_ID = 15;
3629 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3630 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3631
3632 // Add a secondary user, it should never talk with.
3633 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003634 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003635
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003636 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3637 // other.
3638 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3639 MoreAsserts.assertEmpty(targetUsers);
3640
3641 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3642 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3643 MoreAsserts.assertEmpty(targetUsers);
3644
3645 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003646 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003647 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3648 dpm.setAffiliationIds(admin1, userAffiliationIds);
3649
3650 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3651 dpm.setAffiliationIds(admin1, userAffiliationIds);
3652
Tony Mak2f26b792016-11-28 17:54:51 +00003653 // Calling from device owner admin, the result list should just contain the managed
3654 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003655 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003656 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3657 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3658
3659 // Calling from managed profile admin, the result list should just contain the system
3660 // user id.
3661 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3662 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3663 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003664
3665 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003666 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003667
3668 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3669 // to each other.
3670 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3671 MoreAsserts.assertEmpty(targetUsers);
3672
3673 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3674 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3675 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003676 }
3677
3678 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3679 // Setup a device owner.
3680 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3681 setupDeviceOwner();
3682
3683 // Set up a managed profile managed by different package.
3684 final int MANAGED_PROFILE_USER_ID = 15;
3685 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3686 final ComponentName adminDifferentPackage =
3687 new ComponentName("another.package", "whatever.class");
3688 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3689
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003690 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003691 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003692 dpm.setAffiliationIds(admin1, userAffiliationIds);
3693
3694 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3695 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3696
Tony Mak2f26b792016-11-28 17:54:51 +00003697 // Calling from device owner admin, we should get zero bind device admin target users as
3698 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003699 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003700 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3701 MoreAsserts.assertEmpty(targetUsers);
3702
3703 // Calling from managed profile admin, we should still get zero target users for the same
3704 // reason.
3705 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3706 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3707 MoreAsserts.assertEmpty(targetUsers);
3708 }
3709
Jason Parks3c13b642017-11-28 15:39:43 -06003710 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003711 verifyLockTaskState(userId, new String[0],
3712 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003713 }
3714
3715 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3716 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003717 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003718 }
3719
3720 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3721 int flags) throws Exception {
3722 mContext.binder.callingUid = uid;
3723 dpm.setLockTaskPackages(who, packages);
3724 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3725 for (String p : packages) {
3726 assertTrue(dpm.isLockTaskPermitted(p));
3727 }
3728 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3729 // Test to see if set lock task features can be set
3730 dpm.setLockTaskFeatures(who, flags);
3731 verifyLockTaskState(userId, packages, flags);
3732 }
3733
3734 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3735 int flags) throws Exception {
3736 mContext.binder.callingUid = uid;
3737 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3738 () -> dpm.setLockTaskPackages(who, packages));
3739 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3740 () -> dpm.getLockTaskPackages(who));
3741 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3742 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3743 () -> dpm.setLockTaskFeatures(who, flags));
3744 }
3745
Charles Hee078db72017-10-19 18:03:20 +01003746 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003747 // Setup a device owner.
3748 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3749 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003750 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003751 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003752
3753 // Set up a managed profile managed by different package (package name shouldn't matter)
3754 final int MANAGED_PROFILE_USER_ID = 15;
3755 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3756 final ComponentName adminDifferentPackage =
3757 new ComponentName("another.package", "whatever.class");
3758 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003759 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3760
3761 // Setup a PO on the secondary user
3762 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3763 setAsProfileOwner(admin3);
3764 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003765
3766 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003767 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003768 final int flags = 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 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3772
3773 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3774 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003775 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3776 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003777 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003778
3779 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3780 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3781 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003782 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003783 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3784 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003785 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003786
3787 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003788 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003789 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3790 dpm.setAffiliationIds(admin1, userAffiliationIds);
3791
3792 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3793 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3794
3795 // Now the managed profile can set lock task packages.
3796 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3797 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3798 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3799 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003800 // And it can set lock task features.
3801 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003802 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003803
3804 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003805 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003806 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3807 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003808 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3809 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003810 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003811 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003812
Jason Parks3c13b642017-11-28 15:39:43 -06003813 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003814 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3815 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003816
3817 }
3818
3819 public void testLockTaskPolicyForProfileOwner() throws Exception {
3820 // Setup a PO
3821 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3822 setAsProfileOwner(admin1);
3823 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3824
3825 final String[] poPackages = {"poPackage1", "poPackage2"};
3826 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003827 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3828 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003829 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3830 poPackages, poFlags);
3831
3832 // Set up a managed profile managed by different package (package name shouldn't matter)
3833 final int MANAGED_PROFILE_USER_ID = 15;
3834 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3835 final ComponentName adminDifferentPackage =
3836 new ComponentName("another.package", "whatever.class");
3837 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3838 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3839
3840 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3841 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3842 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3843 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003844 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3845 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003846 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003847 }
3848
Benjamin Franzcaffa772018-02-05 16:36:10 +00003849 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3850 // Setup a device owner.
3851 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3852 setupDeviceOwner();
3853 // Lock task policy is updated when loading user data.
3854 verifyLockTaskState(UserHandle.USER_SYSTEM);
3855
3856 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3857 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3858 assertExpectException(IllegalArgumentException.class,
3859 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3860 () -> dpm.setLockTaskFeatures(admin1, flags));
3861 }
3862
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003863 public void testIsDeviceManaged() throws Exception {
3864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3865 setupDeviceOwner();
3866
3867 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3868 // find out that the device has a device owner.
3869 assertTrue(dpm.isDeviceManaged());
3870 mContext.binder.callingUid = 1234567;
3871 mContext.callerPermissions.add(permission.MANAGE_USERS);
3872 assertTrue(dpm.isDeviceManaged());
3873 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3874 mContext.binder.clearCallingIdentity();
3875 assertTrue(dpm.isDeviceManaged());
3876
3877 clearDeviceOwner();
3878
3879 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3880 // not have a device owner.
3881 mContext.binder.callingUid = 1234567;
3882 mContext.callerPermissions.add(permission.MANAGE_USERS);
3883 assertFalse(dpm.isDeviceManaged());
3884 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3885 mContext.binder.clearCallingIdentity();
3886 assertFalse(dpm.isDeviceManaged());
3887 }
3888
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003889 public void testDeviceOwnerOrganizationName() throws Exception {
3890 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3891 setupDeviceOwner();
3892
3893 dpm.setOrganizationName(admin1, "organization");
3894
3895 // Device owner can retrieve organization managing the device.
3896 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3897
3898 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3899 mContext.binder.callingUid = 1234567;
3900 mContext.callerPermissions.add(permission.MANAGE_USERS);
3901 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3902 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3903
3904 // System can retrieve organization managing the device.
3905 mContext.binder.clearCallingIdentity();
3906 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3907
3908 // Removing the device owner clears the organization managing the device.
3909 clearDeviceOwner();
3910 assertNull(dpm.getDeviceOwnerOrganizationName());
3911 }
3912
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003913 public void testWipeDataManagedProfile() throws Exception {
3914 final int MANAGED_PROFILE_USER_ID = 15;
3915 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3916 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3917 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3918
3919 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003920 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003921 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003922 // Get mock reason string since we throw an IAE with empty string input.
3923 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3924 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003925
3926 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003927 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003928 MANAGED_PROFILE_USER_ID);
3929 }
3930
3931 public void testWipeDataManagedProfileDisallowed() throws Exception {
3932 final int MANAGED_PROFILE_USER_ID = 15;
3933 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3934 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3935
3936 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003937 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003938 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3939
Pavel Grafov75c0a892017-05-18 17:28:27 +01003940 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003941 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3942 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3943 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003944 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3945 thenReturn("Just a test string.");
3946
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003947 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003948 // The PO is not allowed to remove the profile if the user restriction was set on the
3949 // profile by the system
3950 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3951 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003952 }
3953
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003954 public void testWipeDataDeviceOwner() throws Exception {
3955 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003956 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003957 UserManager.DISALLOW_FACTORY_RESET,
3958 UserHandle.SYSTEM))
3959 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003960 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3961 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003962
3963 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003964 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003965 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3966 /*wipeEuicc=*/ eq(false));
3967 }
3968
3969 public void testWipeEuiccDataEnabled() throws Exception {
3970 setDeviceOwner();
3971 when(getServices().userManager.getUserRestrictionSource(
3972 UserManager.DISALLOW_FACTORY_RESET,
3973 UserHandle.SYSTEM))
3974 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003975 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3976 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003977
3978 dpm.wipeData(WIPE_EUICC);
3979 verify(getServices().recoverySystem).rebootWipeUserData(
3980 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3981 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003982 }
3983
3984 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3985 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003986 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003987 UserManager.DISALLOW_FACTORY_RESET,
3988 UserHandle.SYSTEM))
3989 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003990 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3991 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003992 // The DO is not allowed to wipe the device if the user restriction was set
3993 // by the system
3994 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3995 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003996 }
3997
3998 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3999 final int MANAGED_PROFILE_USER_ID = 15;
4000 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4001 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4002
4003 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004004 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004005 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4006
Pavel Grafov75c0a892017-05-18 17:28:27 +01004007 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004008 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4009 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4010 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4011
4012 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4013 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4014
4015 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4016 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4017 // Failed password attempts on the parent user are taken into account, as there isn't a
4018 // separate work challenge.
4019 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4020 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4021 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4022
4023 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4024 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004025 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004026 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004027 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004028 }
4029
4030 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4031 throws Exception {
4032 final int MANAGED_PROFILE_USER_ID = 15;
4033 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4034 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4035
4036 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004037 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004038 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4039
Pavel Grafov75c0a892017-05-18 17:28:27 +01004040 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004041 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4042 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4043 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4044
4045 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4046 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4047
4048 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4049 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4050 // Failed password attempts on the parent user are taken into account, as there isn't a
4051 // separate work challenge.
4052 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4053 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4054 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4055
4056 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4057 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004058 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004059 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004060 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004061 }
4062
4063 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4064 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004065 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004066 UserManager.DISALLOW_FACTORY_RESET,
4067 UserHandle.SYSTEM))
4068 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4069
4070 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4071
4072 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4073 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4074 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4075 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4076 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4077
4078 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4079 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004080 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004081 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4082 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004083 }
4084
4085 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4086 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004087 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004088 UserManager.DISALLOW_FACTORY_RESET,
4089 UserHandle.SYSTEM))
4090 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4091
4092 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4093
4094 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4095 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4096 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4097 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4098 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4099
4100 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004101 verifyZeroInteractions(getServices().recoverySystem);
4102 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004103 .removeUserEvenWhenDisallowed(anyInt());
4104 }
4105
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004106 public void testGetPermissionGrantState() throws Exception {
4107 final String permission = "some.permission";
4108 final String app1 = "com.example.app1";
4109 final String app2 = "com.example.app2";
4110
Pavel Grafov75c0a892017-05-18 17:28:27 +01004111 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004112 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004113 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004114 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004115 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004116 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4117 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004118 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004119 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004120 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004121 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004122 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004123 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4124
4125 // System can retrieve permission grant state.
4126 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004127 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004128 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4129 dpm.getPermissionGrantState(null, app1, permission));
4130 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4131 dpm.getPermissionGrantState(null, app2, permission));
4132
4133 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004134 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4135 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004136 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4137 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004138
4139 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004140 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4141 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004142 setAsProfileOwner(admin1);
4143 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4144 dpm.getPermissionGrantState(admin1, app1, permission));
4145 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4146 dpm.getPermissionGrantState(admin1, app2, permission));
4147 }
4148
Rubin Xuaab7a412016-12-30 21:13:29 +00004149 public void testResetPasswordWithToken() throws Exception {
4150 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4151 setupDeviceOwner();
4152 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004153 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4154 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4155
Rubin Xuaab7a412016-12-30 21:13:29 +00004156 // test adding a token
4157 final byte[] token = new byte[32];
4158 final long handle = 123456;
4159 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01004160 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004161 .thenReturn(handle);
4162 assertTrue(dpm.setResetPasswordToken(admin1, token));
4163
4164 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004165 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004166 .thenReturn(true);
4167 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4168
4169 // test reset password with token
Rich Canningsf64ec632019-02-21 12:40:36 -08004170 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password.getBytes()),
Rubin Xu7cf45092017-08-28 11:47:35 +01004171 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
Adrian Roosebf84c22018-12-06 17:50:41 +01004172 eq(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004173 eq(UserHandle.USER_SYSTEM)))
4174 .thenReturn(true);
4175 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4176
4177 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004178 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004179 .thenReturn(true);
4180 assertTrue(dpm.clearResetPasswordToken(admin1));
4181 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004182
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004183 public void testIsActivePasswordSufficient() throws Exception {
4184 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4185 mContext.packageName = admin1.getPackageName();
4186 setupDeviceOwner();
4187
4188 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4189 dpm.setPasswordMinimumLength(admin1, 8);
4190 dpm.setPasswordMinimumLetters(admin1, 6);
4191 dpm.setPasswordMinimumLowerCase(admin1, 3);
4192 dpm.setPasswordMinimumUpperCase(admin1, 1);
4193 dpm.setPasswordMinimumNonLetter(admin1, 1);
4194 dpm.setPasswordMinimumNumeric(admin1, 1);
4195 dpm.setPasswordMinimumSymbols(admin1, 0);
4196
Rubin Xucc391c22018-01-02 20:37:35 +00004197 reset(mContext.spiedContext);
4198
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004199 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4200 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4201 8, 2,
4202 6, 1,
4203 0, 1);
4204
4205 setActivePasswordState(passwordMetricsNoSymbols);
4206 assertTrue(dpm.isActivePasswordSufficient());
4207
4208 initializeDpms();
4209 reset(mContext.spiedContext);
4210 assertTrue(dpm.isActivePasswordSufficient());
4211
4212 // This call simulates the user entering the password for the first time after a reboot.
4213 // This causes password metrics to be reloaded into memory. Until this happens,
4214 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4215 // even if the DPC changes password requirements so that the password no longer meets the
4216 // requirements. This is a known limitation of the current implementation of
4217 // isActivePasswordSufficient() - see b/34218769.
4218 setActivePasswordState(passwordMetricsNoSymbols);
4219 assertTrue(dpm.isActivePasswordSufficient());
4220
4221 dpm.setPasswordMinimumSymbols(admin1, 1);
4222 // This assertion would fail if we had not called setActivePasswordState() again after
4223 // initializeDpms() - see previous comment.
4224 assertFalse(dpm.isActivePasswordSufficient());
4225
4226 initializeDpms();
4227 reset(mContext.spiedContext);
4228 assertFalse(dpm.isActivePasswordSufficient());
4229
4230 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4231 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4232 7, 2,
4233 5, 1,
4234 1, 2);
4235
4236 setActivePasswordState(passwordMetricsWithSymbols);
4237 assertTrue(dpm.isActivePasswordSufficient());
4238 }
4239
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004240 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4241 // If there is no lock screen, the password is considered empty no matter what, because
4242 // it provides no security.
4243 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4244
4245 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4246 mContext.packageName = admin1.getPackageName();
4247 setupDeviceOwner();
4248
4249 // If no password requirements are set, isActivePasswordSufficient should succeed.
4250 assertTrue(dpm.isActivePasswordSufficient());
4251
4252 // Now set some password quality requirements.
4253 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4254
4255 reset(mContext.spiedContext);
4256 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4257 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4258 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4259 8, 2,
4260 6, 1,
4261 0, 1);
4262 // This should be ignored, as there is no lock screen.
4263 dpm.setActivePasswordState(passwordMetricsNoSymbols, userHandle);
4264 dpm.reportPasswordChanged(userHandle);
4265
4266 // No broadcast should be sent.
4267 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4268 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4269 MockUtils.checkUserHandle(userHandle));
4270
4271 // The active (nonexistent) password doesn't comply with the requirements.
4272 assertFalse(dpm.isActivePasswordSufficient());
4273 }
4274
Pavel Grafov75c0a892017-05-18 17:28:27 +01004275 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4276 throws Exception {
4277 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004278 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004279
Pavel Grafov75c0a892017-05-18 17:28:27 +01004280 dpm.setActivePasswordState(passwordMetrics, userHandle);
4281 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004282
Rubin Xucc391c22018-01-02 20:37:35 +00004283 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4284 // reportPasswordChanged()
Eran Messeri9ecde422018-04-30 16:16:39 +01004285 // This broadcast should be sent 4 times:
4286 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4287 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
4288 // * Twice from calls to DevicePolicyManagerService.saveSettingsLocked
4289 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4290 // the password change is relevant to and another with the credential owner of said
4291 // userId.
4292 verify(mContext.spiedContext, times(4)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004293 MockUtils.checkIntentAction(
4294 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4295 MockUtils.checkUserHandle(userHandle));
4296
Pavel Grafov75c0a892017-05-18 17:28:27 +01004297 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4298 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004299 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004300
4301 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4302 MockUtils.checkIntent(intent),
4303 MockUtils.checkUserHandle(userHandle));
4304
4305 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4306 // let it finish with system uid, otherwise it will throw and crash.
4307 flushTasks();
4308
4309 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004310 }
4311
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004312 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4313 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4314 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4315 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4316 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4317 DpmMockContext.SYSTEM_UID);
4318 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4319 DpmMockContext.SYSTEM_UID);
4320
4321 // Set up a device owner.
4322 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004323 setupDeviceOwner();
4324
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004325 // First and second user set IMEs manually.
4326 mContext.binder.callingUid = firstUserSystemUid;
4327 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4328 mContext.binder.callingUid = secondUserSystemUid;
4329 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004330
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004331 // Device owner changes IME for first user.
4332 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004333 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004334 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004335 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004336 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004337 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004338 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004339 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4340 mContext.binder.callingUid = firstUserSystemUid;
4341 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4342 mContext.binder.callingUid = secondUserSystemUid;
4343 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004344
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004345 // Second user changes IME manually.
4346 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4347 mContext.binder.callingUid = firstUserSystemUid;
4348 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4349 mContext.binder.callingUid = secondUserSystemUid;
4350 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004351
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004352 // First user changes IME manually.
4353 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4354 mContext.binder.callingUid = firstUserSystemUid;
4355 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4356 mContext.binder.callingUid = secondUserSystemUid;
4357 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004358
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004359 // Device owner changes IME for first user again.
4360 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004361 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004362 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004363 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004364 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004365 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004366 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4367 mContext.binder.callingUid = firstUserSystemUid;
4368 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4369 mContext.binder.callingUid = secondUserSystemUid;
4370 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004371
4372 // Restarting the DPMS should not lose information.
4373 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004374 mContext.binder.callingUid = firstUserSystemUid;
4375 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4376 mContext.binder.callingUid = secondUserSystemUid;
4377 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004378
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004379 // Device owner can find out whether it set the current IME itself.
4380 mContext.binder.callingUid = deviceOwnerUid;
4381 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004382
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004383 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004384 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004385 mContext.binder.callingUid = firstUserSystemUid;
4386 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4387 mContext.binder.callingUid = secondUserSystemUid;
4388 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004389 }
4390
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004391 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4392 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4393 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4394 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4395 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4396 DpmMockContext.SYSTEM_UID);
4397 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4398 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004399
4400 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004401 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004402 setupProfileOwner();
4403
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004404 // First and second user set IMEs manually.
4405 mContext.binder.callingUid = firstUserSystemUid;
4406 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4407 mContext.binder.callingUid = secondUserSystemUid;
4408 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004409
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004410 // Profile owner changes IME for second user.
4411 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004412 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004413 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004414 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004415 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004416 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004417 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004418 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4419 mContext.binder.callingUid = firstUserSystemUid;
4420 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4421 mContext.binder.callingUid = secondUserSystemUid;
4422 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004423
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004424 // First user changes IME manually.
4425 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4426 mContext.binder.callingUid = firstUserSystemUid;
4427 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4428 mContext.binder.callingUid = secondUserSystemUid;
4429 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004430
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004431 // Second user changes IME manually.
4432 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4433 mContext.binder.callingUid = firstUserSystemUid;
4434 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4435 mContext.binder.callingUid = secondUserSystemUid;
4436 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004437
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004438 // Profile owner changes IME for second user again.
4439 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004440 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004441 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004442 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004443 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004444 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004445 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4446 mContext.binder.callingUid = firstUserSystemUid;
4447 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4448 mContext.binder.callingUid = secondUserSystemUid;
4449 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004450
4451 // Restarting the DPMS should not lose information.
4452 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004453 mContext.binder.callingUid = firstUserSystemUid;
4454 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4455 mContext.binder.callingUid = secondUserSystemUid;
4456 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004457
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004458 // Profile owner can find out whether it set the current IME itself.
4459 mContext.binder.callingUid = profileOwnerUid;
4460 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004461
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004462 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004463 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004464 mContext.binder.callingUid = firstUserSystemUid;
4465 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4466 mContext.binder.callingUid = secondUserSystemUid;
4467 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004468 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004469
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004470 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4471 throws Exception {
4472 // Set up a device owner.
4473 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4474 setupDeviceOwner();
4475 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4476 }
4477
4478 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4479 throws Exception {
4480 // Set up a profile owner.
4481 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4482 setupProfileOwner();
4483 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4484 }
4485
4486 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4487 int adminUid) throws Exception {
4488 mContext.binder.callingUid = adminUid;
4489 final int userId = UserHandle.getUserId(adminUid);
4490
4491 final String packageName = "some.package";
4492 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4493 admin1, Collections.singletonList(packageName)));
4494 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4495
4496 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4497 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4498
4499 // Attempt to set to empty list (which means no listener is whitelisted)
4500 mContext.binder.callingUid = adminUid;
4501 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004502 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004503 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4504
4505 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4506 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4507 }
4508
4509 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4510 // Set up a managed profile
4511 final int MANAGED_PROFILE_USER_ID = 15;
4512 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4513 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4514 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4515
4516 final String permittedListener = "some.package";
4517 setupPackageInPackageManager(
4518 permittedListener,
4519 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4520 /*appId=*/ 12345, /*flags=*/ 0);
4521
4522 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4523 admin1, Collections.singletonList(permittedListener)));
4524
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004525 // isNotificationListenerServicePermitted should throw if not called from System.
4526 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4527 () -> dpms.isNotificationListenerServicePermitted(
4528 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004529
4530 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4531 assertTrue(dpms.isNotificationListenerServicePermitted(
4532 permittedListener, MANAGED_PROFILE_USER_ID));
4533 }
4534
4535 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4536 throws Exception {
4537 // Set up a managed profile
4538 final int MANAGED_PROFILE_USER_ID = 15;
4539 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4540 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4541 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4542
4543 final String permittedListener = "permitted.package";
4544 int appId = 12345;
4545 setupPackageInPackageManager(
4546 permittedListener,
4547 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4548 appId, /*flags=*/ 0);
4549
4550 final String notPermittedListener = "not.permitted.package";
4551 setupPackageInPackageManager(
4552 notPermittedListener,
4553 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4554 ++appId, /*flags=*/ 0);
4555
4556 final String systemListener = "system.package";
4557 setupPackageInPackageManager(
4558 systemListener,
4559 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4560 ++appId, ApplicationInfo.FLAG_SYSTEM);
4561
4562 // By default all packages are allowed
4563 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4564
4565 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4566 assertTrue(dpms.isNotificationListenerServicePermitted(
4567 permittedListener, MANAGED_PROFILE_USER_ID));
4568 assertTrue(dpms.isNotificationListenerServicePermitted(
4569 notPermittedListener, MANAGED_PROFILE_USER_ID));
4570 assertTrue(dpms.isNotificationListenerServicePermitted(
4571 systemListener, MANAGED_PROFILE_USER_ID));
4572
4573 // Setting only one package in the whitelist
4574 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4575 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4576 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004577 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004578 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4579 assertEquals(1, permittedListeners.size());
4580 assertEquals(permittedListener, permittedListeners.get(0));
4581
4582 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4583 assertTrue(dpms.isNotificationListenerServicePermitted(
4584 permittedListener, MANAGED_PROFILE_USER_ID));
4585 assertFalse(dpms.isNotificationListenerServicePermitted(
4586 notPermittedListener, MANAGED_PROFILE_USER_ID));
4587 // System packages are always allowed (even if not in the whitelist)
4588 assertTrue(dpms.isNotificationListenerServicePermitted(
4589 systemListener, MANAGED_PROFILE_USER_ID));
4590
4591 // Setting an empty whitelist - only system listeners allowed
4592 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4593 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004594 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004595 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4596
4597 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4598 assertFalse(dpms.isNotificationListenerServicePermitted(
4599 permittedListener, MANAGED_PROFILE_USER_ID));
4600 assertFalse(dpms.isNotificationListenerServicePermitted(
4601 notPermittedListener, MANAGED_PROFILE_USER_ID));
4602 // System packages are always allowed (even if not in the whitelist)
4603 assertTrue(dpms.isNotificationListenerServicePermitted(
4604 systemListener, MANAGED_PROFILE_USER_ID));
4605
4606 // Setting a null whitelist - all listeners allowed
4607 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4608 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4609 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4610
4611 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4612 assertTrue(dpms.isNotificationListenerServicePermitted(
4613 permittedListener, MANAGED_PROFILE_USER_ID));
4614 assertTrue(dpms.isNotificationListenerServicePermitted(
4615 notPermittedListener, MANAGED_PROFILE_USER_ID));
4616 assertTrue(dpms.isNotificationListenerServicePermitted(
4617 systemListener, MANAGED_PROFILE_USER_ID));
4618 }
4619
4620 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4621 throws Exception {
4622 // Set up a managed profile
4623 final int MANAGED_PROFILE_USER_ID = 15;
4624 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4625 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4626 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4627
4628 final String nonSystemPackage = "non.system.package";
4629 int appId = 12345;
4630 setupPackageInPackageManager(
4631 nonSystemPackage,
4632 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4633 appId, /*flags=*/ 0);
4634
4635 final String systemListener = "system.package";
4636 setupPackageInPackageManager(
4637 systemListener,
4638 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4639 ++appId, ApplicationInfo.FLAG_SYSTEM);
4640
4641 // By default all packages are allowed (for all profiles)
4642 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4643
4644 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4645 assertTrue(dpms.isNotificationListenerServicePermitted(
4646 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4647 assertTrue(dpms.isNotificationListenerServicePermitted(
4648 systemListener, MANAGED_PROFILE_USER_ID));
4649 assertTrue(dpms.isNotificationListenerServicePermitted(
4650 nonSystemPackage, UserHandle.USER_SYSTEM));
4651 assertTrue(dpms.isNotificationListenerServicePermitted(
4652 systemListener, UserHandle.USER_SYSTEM));
4653
4654 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4655 // all allowed in primary profile
4656 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4657 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004658 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004659 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4660
4661 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4662 assertFalse(dpms.isNotificationListenerServicePermitted(
4663 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4664 assertTrue(dpms.isNotificationListenerServicePermitted(
4665 systemListener, MANAGED_PROFILE_USER_ID));
4666 assertTrue(dpms.isNotificationListenerServicePermitted(
4667 nonSystemPackage, UserHandle.USER_SYSTEM));
4668 assertTrue(dpms.isNotificationListenerServicePermitted(
4669 systemListener, UserHandle.USER_SYSTEM));
4670 }
4671
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004672 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004673 mServiceContext.packageName = mRealTestContext.getPackageName();
4674 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4675 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004676 setDeviceOwner();
4677
Pavel Grafov75c0a892017-05-18 17:28:27 +01004678 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004679 }
4680
4681 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004682 mServiceContext.packageName = mRealTestContext.getPackageName();
4683 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4684 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004685 setAsProfileOwner(admin1);
4686
Pavel Grafov75c0a892017-05-18 17:28:27 +01004687 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4688 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004689 }
4690
4691 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004692 mServiceContext.packageName = mRealTestContext.getPackageName();
4693 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4694 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004695 setAsProfileOwner(admin1);
4696
Pavel Grafov75c0a892017-05-18 17:28:27 +01004697 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4698 caller.packageName = "com.example.delegate";
4699 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4700 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004701
Pavel Grafov75c0a892017-05-18 17:28:27 +01004702 // Make caller a delegated cert installer.
4703 runAsCaller(mAdmin1Context, dpms,
4704 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004705
4706 verifyCanGetOwnerInstalledCaCerts(null, caller);
4707 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004708 }
4709
Rubin Xucc391c22018-01-02 20:37:35 +00004710 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004711 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4712 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004713 Bundle restriction = new Bundle();
4714 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4715
4716 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4717 RestrictionsListener listener = new RestrictionsListener(mContext);
4718 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4719 new Bundle());
4720 verifyDataSharingChangedBroadcast();
4721 }
4722
4723 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004724 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4725 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004726 Bundle restriction = new Bundle();
4727 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4728
4729 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4730 RestrictionsListener listener = new RestrictionsListener(mContext);
4731 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4732 restriction);
4733 verifyDataSharingChangedBroadcast();
4734 }
4735
4736 public void testDisallowSharingIntoProfileUnchanged() {
4737 RestrictionsListener listener = new RestrictionsListener(mContext);
4738 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4739 new Bundle());
4740 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4741 }
4742
4743 private void verifyDataSharingChangedBroadcast() {
4744 Intent expectedIntent = new Intent(
4745 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4746 expectedIntent.setPackage("com.android.managedprovisioning");
4747 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4748 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4749 MockUtils.checkIntent(expectedIntent),
4750 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4751 }
4752
yuemingwe3d9c092018-01-11 12:11:44 +00004753 public void testOverrideApnAPIsFailWithPO() throws Exception {
4754 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004755 ApnSetting apn = (new ApnSetting.Builder())
4756 .setApnName("test")
4757 .setEntryName("test")
4758 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4759 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004760 assertExpectException(SecurityException.class, null, () ->
4761 dpm.addOverrideApn(admin1, apn));
4762 assertExpectException(SecurityException.class, null, () ->
4763 dpm.updateOverrideApn(admin1, 0, apn));
4764 assertExpectException(SecurityException.class, null, () ->
4765 dpm.removeOverrideApn(admin1, 0));
4766 assertExpectException(SecurityException.class, null, () ->
4767 dpm.getOverrideApns(admin1));
4768 assertExpectException(SecurityException.class, null, () ->
4769 dpm.setOverrideApnsEnabled(admin1, false));
4770 assertExpectException(SecurityException.class, null, () ->
4771 dpm.isOverrideApnEnabled(admin1));
4772 }
4773
Robin Lee2c68dad2017-03-17 12:50:24 +00004774 private void verifyCanGetOwnerInstalledCaCerts(
4775 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004776 final String alias = "cert";
4777 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004778
4779 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004780 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004781 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4782 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004783 }
4784 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4785
4786 // caller: device admin or delegated certificate installer
4787 callerContext.applicationInfo = new ApplicationInfo();
4788 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4789
4790 // system_server
4791 final DpmMockContext serviceContext = mContext;
4792 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004793 getServices().addPackageContext(callerUser, admin1Context);
4794 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004795
4796 // Install a CA cert.
4797 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004798 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004799 .thenReturn(alias);
4800 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004801 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004802 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004803 });
4804
Pavel Grafov75c0a892017-05-18 17:28:27 +01004805 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4806 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4807 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004808 flushTasks();
4809
Robin Lee2c68dad2017-03-17 12:50:24 +00004810 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4811
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004812 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004813 runAsCaller(admin1Context, dpms, (dpm) -> {
4814 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004815 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004816 ownerInstalledCaCerts.addAll(installedCaCerts);
4817 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004818
4819 // Restarting the DPMS should not lose information.
4820 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004821 runAsCaller(admin1Context, dpms, (dpm) ->
4822 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004823
4824 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004825 runAsCaller(serviceContext, dpms, (dpm) -> {
4826 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004827
Robin Lee2c68dad2017-03-17 12:50:24 +00004828 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004829 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004830 });
4831
Pavel Grafov75c0a892017-05-18 17:28:27 +01004832 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4833 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4834 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004835 flushTasks();
4836
4837 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4838 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004839 runAsCaller(admin1Context, dpms, (dpm) -> {
4840 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4841 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004842 }
4843
Robin Lee2c68dad2017-03-17 12:50:24 +00004844 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4845 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004846 final String alias = "cert";
4847 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004848
4849 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004850 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004851 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4852 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004853 }
4854 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4855
4856 // caller: device admin or delegated certificate installer
4857 callerContext.applicationInfo = new ApplicationInfo();
4858 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4859
4860 // system_server
4861 final DpmMockContext serviceContext = mContext;
4862 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004863 getServices().addPackageContext(callerUser, admin1Context);
4864 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004865
4866 // Install a CA cert as caller
4867 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004868 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004869 .thenReturn(alias);
4870 assertTrue(dpm.installCaCert(callerName, caCert));
4871 });
4872
4873 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004874 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004875 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004876 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4877 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4878 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004879 flushTasks();
4880
Robin Lee2c68dad2017-03-17 12:50:24 +00004881 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004882 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004883
4884 runAsCaller(serviceContext, dpms, (dpm) -> {
4885 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4886 assertNotNull(ownerInstalledCaCerts);
4887 assertTrue(ownerInstalledCaCerts.isEmpty());
4888 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004889 }
4890
Eran Messeri94d56762017-12-21 20:50:54 +00004891 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4892 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4893 Arrays.sort(gotFlags);
4894 Arrays.sort(expectedFlags);
4895 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4896 }
4897
4898 public void testTranslationOfIdAttestationFlag() {
4899 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4900 int[] correspondingAttUtilsTypes = new int[]{
4901 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4902 AttestationUtils.ID_TYPE_MEID};
4903
4904 // Test translation of zero flags
4905 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4906
4907 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4908 // non-null array
4909 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4910
4911 // Test translation of a single flag
4912 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4913 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4914 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4915
4916 // Test translation of two flags
4917 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4918 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4919 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4920 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4921
4922 // Test translation of all three flags
4923 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4924 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4925 AttestationUtils.ID_TYPE_MEID});
4926 // Test translation of all three flags
4927 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4928 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4929 AttestationUtils.ID_TYPE_MEID});
4930 }
4931
arangelov08d534b2018-01-22 15:20:53 +00004932 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4933 setDeviceOwner();
4934 initializeDpms();
4935 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4936 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4937 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4938 }
4939
4940 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4941 DpmTestUtils.writeInputStreamToFile(
4942 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4943 getDeviceOwnerPoliciesFile());
4944 DpmTestUtils.writeInputStreamToFile(
4945 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4946 getDeviceOwnerFile());
4947 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4948 }
4949
4950 public void testRevertDeviceOwnership_deviceNotMigrated()
4951 throws Exception {
4952 DpmTestUtils.writeInputStreamToFile(
4953 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4954 getDeviceOwnerPoliciesFile());
4955 DpmTestUtils.writeInputStreamToFile(
4956 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4957 getDeviceOwnerFile());
4958 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4959 }
4960
4961 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4962 throws Exception {
4963 DpmTestUtils.writeInputStreamToFile(
4964 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4965 getDeviceOwnerPoliciesFile());
4966 DpmTestUtils.writeInputStreamToFile(
4967 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4968 getDeviceOwnerFile());
4969 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4970 }
4971
4972 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4973 setupProfileOwner();
4974 initializeDpms();
4975 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4976 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4977 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4978 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4979 }
4980
4981 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4982 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4983 UserHandle.USER_SYSTEM);
4984 DpmTestUtils.writeInputStreamToFile(
4985 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4986 getProfileOwnerPoliciesFile());
4987 DpmTestUtils.writeInputStreamToFile(
4988 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
4989 getProfileOwnerFile());
4990 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4991 }
4992
4993 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
4994 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4995 UserHandle.USER_SYSTEM);
4996 DpmTestUtils.writeInputStreamToFile(
4997 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4998 getProfileOwnerPoliciesFile());
4999 DpmTestUtils.writeInputStreamToFile(
5000 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5001 getProfileOwnerFile());
5002 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5003 }
5004
5005 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5006 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5007 UserHandle.USER_SYSTEM);
5008 DpmTestUtils.writeInputStreamToFile(
5009 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5010 getProfileOwnerPoliciesFile());
5011 DpmTestUtils.writeInputStreamToFile(
5012 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5013 getProfileOwnerFile());
5014 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5015 }
5016
Eran Messeribb271892018-10-17 18:27:50 +01005017 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5018 setupProfileOwner();
5019 configureContextForAccess(mContext, false);
5020
5021 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5022 () -> dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin2,
5023 UserHandle.of(DpmMockContext.CALLER_UID)));
5024 }
5025
5026 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5027 setupProfileOwner();
5028 configureContextForAccess(mContext, false);
5029
5030 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5031 () -> dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin1,
5032 UserHandle.of(DpmMockContext.CALLER_UID)));
5033 }
5034
5035 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5036 setupProfileOwner();
5037
5038 // This method will throw if the system context could not call
5039 // setProfileOwnerCanAccessDeviceIds successfully.
5040 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5041 }
5042
5043 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5044 when(context.spiedContext.checkCallingPermission(
5045 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5046 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5047 : PackageManager.PERMISSION_DENIED);
5048 }
5049
5050 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5051 setupProfileOwner();
5052
5053 final long ident = mServiceContext.binder.clearCallingIdentity();
5054 configureContextForAccess(mServiceContext, true);
5055
5056 mServiceContext.binder.callingUid =
5057 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5058 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5059 try {
5060 runAsCaller(mServiceContext, dpms, dpm -> {
5061 dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin1,
5062 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE));
5063 });
5064 } finally {
5065 mServiceContext.binder.restoreCallingIdentity(ident);
5066 }
5067 }
5068
5069 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5070 throws Exception {
5071 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5072 setupDeviceOwner();
5073 configureContextForAccess(mContext, false);
5074
5075 // Device owner should be allowed to request Device ID attestation.
5076 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5077 DpmMockContext.CALLER_SYSTEM_USER_UID);
5078
5079 // Another package must not be allowed to request Device ID attestation.
5080 assertExpectException(SecurityException.class, null,
5081 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5082 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5083 // Another component that is not the admin must not be allowed to request Device ID
5084 // attestation.
5085 assertExpectException(SecurityException.class, null,
5086 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5087 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5088 }
5089
5090 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5091 throws Exception {
5092 configureContextForAccess(mContext, false);
5093
5094 // Make sure a security exception is thrown if the device has no profile owner.
5095 assertExpectException(SecurityException.class, null,
5096 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5097 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5098
5099 setupProfileOwner();
5100 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5101
5102 // The profile owner is allowed to request Device ID attestation.
5103 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5104 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5105 DpmMockContext.CALLER_UID);
5106 // But not another package.
5107 assertExpectException(SecurityException.class, null,
5108 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5109 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5110 // Or another component which is not the admin.
5111 assertExpectException(SecurityException.class, null,
5112 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5113 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5114 }
5115
5116 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5117 final long ident = mServiceContext.binder.clearCallingIdentity();
5118
5119 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5120 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5121 try {
5122 runAsCaller(mServiceContext, dpms, action);
5123 } finally {
5124 mServiceContext.binder.restoreCallingIdentity(ident);
5125 }
5126 }
5127
5128 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5129 setupProfileOwner();
5130 markDelegatedCertInstallerAsInstalled();
5131
5132 // Configure a delegated cert installer.
5133 runAsCaller(mServiceContext, dpms,
5134 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5135 Arrays.asList(DELEGATION_CERT_INSTALL)));
5136
5137 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5138
5139 // Make sure that the profile owner can still request Device ID attestation.
5140 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5141 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5142 DpmMockContext.CALLER_UID);
5143
5144 runAsDelegatedCertInstaller(dpm -> {
5145 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5146 DpmMockContext.DELEGATE_PACKAGE_NAME,
5147 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5148 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5149 });
5150 }
5151
5152 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5153 throws Exception {
5154 setupProfileOwner();
5155 markDelegatedCertInstallerAsInstalled();
5156
5157 // Configure a delegated cert installer.
5158 runAsCaller(mServiceContext, dpms,
5159 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5160 Arrays.asList(DELEGATION_CERT_INSTALL)));
5161
5162
5163 assertExpectException(SecurityException.class, null,
5164 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5165 admin1.getPackageName(),
5166 DpmMockContext.CALLER_UID));
5167
5168 runAsDelegatedCertInstaller(dpm -> {
5169 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5170 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5171 DpmMockContext.DELEGATE_PACKAGE_NAME,
5172 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5173 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5174 });
5175 }
5176
Bernard Chaue9586552018-11-29 10:59:31 +00005177 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5178 assertThrows(SecurityException.class,
5179 () -> new DevicePolicyManagerTestable(
5180 mServiceContext,
5181 dpms,
5182 /* parentInstance= */ true)
5183 .getPasswordComplexity());
5184 }
5185
5186 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5187 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5188 .thenReturn(false);
5189 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5190 }
5191
5192 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5193 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5194 .thenReturn(true);
5195 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5196 }
5197
5198
5199 public void testGetPasswordComplexity_currentUserNoPassword() {
5200 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5201 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005202 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005203 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5204 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5205
5206 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5207 }
5208
5209 public void testGetPasswordComplexity_currentUserHasPassword() {
5210 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5211 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005212 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005213 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5214 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5215 dpms.mUserPasswordMetrics.put(
5216 DpmMockContext.CALLER_USER_HANDLE,
Rich Canningsf64ec632019-02-21 12:40:36 -08005217 PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005218
5219 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5220 }
5221
5222 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5223 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5224 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005225 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005226
5227 UserInfo parentUser = new UserInfo();
5228 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5229 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5230 .thenReturn(parentUser.id);
5231
5232 dpms.mUserPasswordMetrics.put(
5233 DpmMockContext.CALLER_USER_HANDLE,
Rich Canningsf64ec632019-02-21 12:40:36 -08005234 PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005235 dpms.mUserPasswordMetrics.put(
5236 parentUser.id,
Rich Canningsf64ec632019-02-21 12:40:36 -08005237 PasswordMetrics.computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005238
5239 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5240 }
5241
yuemingwd2bfbc82019-01-02 11:42:25 +00005242 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5243 setAsProfileOwner(admin1);
5244 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5245 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5246 }
5247
5248 public void testCrossProfileCalendarPackages_reopenDpms() {
5249 setAsProfileOwner(admin1);
5250 dpm.setCrossProfileCalendarPackages(admin1, null);
5251 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5252 assertTrue(packages == null);
5253 initializeDpms();
5254 packages = dpm.getCrossProfileCalendarPackages(admin1);
5255 assertTrue(packages == null);
5256
5257 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5258 packages = dpm.getCrossProfileCalendarPackages(admin1);
5259 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5260 initializeDpms();
5261 packages = dpm.getCrossProfileCalendarPackages(admin1);
5262 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5263
5264 final String dummyPackageName = "test";
5265 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5266 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5267 packages = dpm.getCrossProfileCalendarPackages(admin1);
5268 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5269 initializeDpms();
5270 packages = dpm.getCrossProfileCalendarPackages(admin1);
5271 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5272 }
5273
5274 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5275 assertTrue(expected != null);
5276 assertTrue(actual != null);
5277 assertTrue(expected.containsAll(actual));
5278 assertTrue(actual.containsAll(expected));
5279 }
5280
yuemingwdded98f2019-01-30 17:08:12 +00005281 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5282 setAsProfileOwner(admin1);
5283 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5284 when(getServices().settings.settingsSecureGetIntForUser(
5285 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5286 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5287 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5288 }
5289
5290 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5291 final String testPackage = "TEST_PACKAGE";
5292 setAsProfileOwner(admin1);
5293 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5294 when(getServices().settings.settingsSecureGetIntForUser(
5295 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5296 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5297 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5298 }
5299
5300 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5301 final String testPackage = "TEST_PACKAGE";
5302 setAsProfileOwner(admin1);
5303 dpm.setCrossProfileCalendarPackages(admin1, null);
5304 when(getServices().settings.settingsSecureGetIntForUser(
5305 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5306 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5307 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5308 }
5309
Eran Messeribb271892018-10-17 18:27:50 +01005310 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5311 final long ident = mServiceContext.binder.clearCallingIdentity();
5312 mServiceContext.binder.callingUid =
5313 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5314 runAsCaller(mServiceContext, dpms, dpm -> {
5315 dpm.setProfileOwnerCanAccessDeviceIdsForUser(who, UserHandle.of(userId));
5316 });
5317 mServiceContext.binder.restoreCallingIdentity(ident);
5318 }
5319
arangelov08d534b2018-01-22 15:20:53 +00005320 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5321 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5322 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5323 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5324
5325 final long ident = mServiceContext.binder.clearCallingIdentity();
5326 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5327 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5328 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5329 // To simulate a reboot, we just reinitialize dpms and call systemReady
5330 initializeDpms();
5331
5332 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5333 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5334 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5335 assertTrue(dpm.isAdminActive(admin1));
5336 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5337 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5338
5339 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5340 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5341 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5342 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5343
5344 mServiceContext.binder.restoreCallingIdentity(ident);
5345 }
5346
5347 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5348 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5349 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5350 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5351
5352 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5353 DpmMockContext.CALLER_SYSTEM_USER_UID);
5354 setUpPackageManagerForAdmin(admin1, uid);
5355 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5356 // To simulate a reboot, we just reinitialize dpms and call systemReady
5357 initializeDpms();
5358
5359 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5360 assertTrue(dpm.isAdminActive(admin1));
5361 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5362 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5363 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5364 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5365 }
5366
5367 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5368 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5369 metadataManager.deleteMetadataFile();
5370
5371 final TransferOwnershipMetadataManager.Metadata metadata =
5372 new TransferOwnershipMetadataManager.Metadata(
5373 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5374 callerUserHandle,
5375 adminType);
5376 metadataManager.saveMetadataFile(metadata);
5377 }
5378
5379 private File getDeviceOwnerFile() {
5380 return dpms.mOwners.getDeviceOwnerFile();
5381 }
5382
5383 private File getProfileOwnerFile() {
5384 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5385 }
5386
5387 private File getProfileOwnerPoliciesFile() {
5388 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5389 DpmMockContext.CALLER_USER_HANDLE);
5390 return getPoliciesFile(parentDir);
5391 }
5392
5393 private File getDeviceOwnerPoliciesFile() {
5394 return getPoliciesFile(getServices().systemUserDataDir);
5395 }
5396
5397 private File getPoliciesFile(File parentDir) {
5398 return new File(parentDir, "device_policies.xml");
5399 }
5400
5401 private InputStream getRawStream(@RawRes int id) {
5402 return mRealTestContext.getResources().openRawResource(id);
5403 }
5404
Victor Chang3e794af2016-03-04 13:48:17 +00005405 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005406 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005407 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5408 dpms.notifyChangeToContentObserver(
5409 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5410 }
5411
5412 private void assertProvisioningAllowed(String action, boolean expected) {
5413 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5414 dpm.isProvisioningAllowed(action));
5415 }
Tony Mak2f26b792016-11-28 17:54:51 +00005416
Nicolas Prevot45d29072017-01-18 16:11:19 +00005417 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5418 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005419 final String previousPackageName = mContext.packageName;
5420 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005421
5422 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5423 mContext.packageName = packageName;
5424 mMockContext.binder.callingUid = uid;
5425 assertProvisioningAllowed(action, expected);
5426
5427 // Set the previous package name / calling uid to go back to the initial state.
5428 mContext.packageName = previousPackageName;
5429 mMockContext.binder.callingUid = previousUid;
5430 }
5431
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005432 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005433 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5434 }
5435
5436 private void assertCheckProvisioningPreCondition(
5437 String action, String packageName, int provisioningCondition) {
5438 assertEquals("checkProvisioningPreCondition("
5439 + action + ", " + packageName + ") returning unexpected result",
5440 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005441 }
5442
Tony Mak2f26b792016-11-28 17:54:51 +00005443 /**
5444 * Setup a managed profile with the specified admin and its uid.
5445 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5446 * @param adminUid uid of the admin package.
5447 * @param copyFromAdmin package information for {@code admin} will be built based on this
5448 * component's information.
5449 */
5450 private void addManagedProfile(
5451 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5452 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005453 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005454 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5455 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5456 dpm.setActiveAdmin(admin, false, userId);
5457 assertTrue(dpm.setProfileOwner(admin, null, userId));
5458 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5459 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005460
5461 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005462 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005463 */
Robin Leeabaa0692017-02-20 20:54:22 +00005464 private static StringParceledListSlice asSlice(String[] s) {
5465 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005466 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005467
5468 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005469 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5470 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005471
Robin Lee2c68dad2017-03-17 12:50:24 +00005472 // We can't let exceptions happen on the background thread. Throw them here if they happen
5473 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005474 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005475 }
Victor Chang3e794af2016-03-04 13:48:17 +00005476}