blob: 5b197000497158b66f41f2e040923ce76ee77eee [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
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080032import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Eugene Susla4f8680b2017-08-07 17:25:30 -070033import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010034
Pavel Grafov75c0a892017-05-18 17:28:27 +010035import static org.mockito.Matchers.any;
36import static org.mockito.Matchers.anyInt;
37import static org.mockito.Matchers.anyLong;
38import static org.mockito.Matchers.anyObject;
39import static org.mockito.Matchers.anyString;
40import static org.mockito.Matchers.eq;
41import static org.mockito.Matchers.isNull;
42import static org.mockito.Mockito.atLeast;
43import static org.mockito.Mockito.doAnswer;
44import static org.mockito.Mockito.doReturn;
45import static org.mockito.Mockito.never;
46import static org.mockito.Mockito.nullable;
47import static org.mockito.Mockito.reset;
48import static org.mockito.Mockito.timeout;
49import static org.mockito.Mockito.times;
50import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080051import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010052import static org.mockito.Mockito.verifyZeroInteractions;
53import static org.mockito.Mockito.when;
54import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000055import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010056
Makoto Onukif76b06a2015-09-22 15:03:44 -070057import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000058import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070059import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000060import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061import android.app.admin.DeviceAdminReceiver;
62import android.app.admin.DevicePolicyManager;
63import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010064import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070065import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070066import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000067import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000068import android.content.pm.ApplicationInfo;
69import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070070import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010071import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000072import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000073import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010074import android.graphics.Color;
75import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080076import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070077import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080078import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070079import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070080import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010081import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080082import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010083import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000084import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000085import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000086import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080087import android.test.MoreAsserts;
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
Pavel Grafov57f1b662019-03-27 14:55:38 +000091import androidx.test.filters.SmallTest;
92
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010093import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000094import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000095import com.android.server.LocalServices;
96import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000097import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000098import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000099
Robin Lee7f5c91c2017-02-08 21:27:02 +0000100import org.hamcrest.BaseMatcher;
101import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800102import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700103import org.mockito.invocation.InvocationOnMock;
104import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700105
arangelov08d534b2018-01-22 15:20:53 +0000106import java.io.File;
107import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800108import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000109import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000110import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700111import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700112import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700113import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100114import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000115import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700118 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000119 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700120 m FrameworksServicesTests &&
121 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000122 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700123 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700124 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700125
126 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000127 *
128 * , or:
129 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700130 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000131@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100132@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700133public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000134 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
135 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
136 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100137 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800138 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100139 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000140
Pavel Grafov75c0a892017-05-18 17:28:27 +0100141 // TODO replace all instances of this with explicit {@link #mServiceContext}.
142 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700143 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100144
145 private DpmMockContext mServiceContext;
146 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700147 public DevicePolicyManager dpm;
148 public DevicePolicyManagerServiceTestable dpms;
149
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100150 /*
151 * The CA cert below is the content of cacert.pem as generated by:
152 *
153 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
154 */
155 private static final String TEST_CA =
156 "-----BEGIN CERTIFICATE-----\n" +
157 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
158 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
159 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
160 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
161 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
162 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
163 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
164 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
165 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
166 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
167 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
168 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
169 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
170 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
171 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
172 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
173 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
174 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
175 "wQ==\n" +
176 "-----END CERTIFICATE-----\n";
177
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700178 @Override
179 protected void setUp() throws Exception {
180 super.setUp();
181
182 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100183 mServiceContext = mContext;
184 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
185 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700186 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100187 doReturn(Collections.singletonList(new ResolveInfo()))
188 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
189 any(Intent.class),
190 anyInt(),
191 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700192
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800193 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100194 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800195
Makoto Onukia52562c2015-10-01 16:12:31 -0700196 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700197
Sudheer Shanka101c3532018-01-08 16:28:42 -0800198 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800199 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700200 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
201 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
202 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800203 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700204
Pavel Grafov75c0a892017-05-18 17:28:27 +0100205 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
206 mAdmin1Context.packageName = admin1.getPackageName();
207 mAdmin1Context.applicationInfo = new ApplicationInfo();
208 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
209
Makoto Onukib643fb02015-09-22 15:03:44 -0700210 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100211
212 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700213 }
214
arangelov08d534b2018-01-22 15:20:53 +0000215 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
216 return dpms.mTransferOwnershipMetadataManager;
217 }
218
Robin Lee2c68dad2017-03-17 12:50:24 +0000219 @Override
220 protected void tearDown() throws Exception {
221 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000222 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000223 super.tearDown();
224 }
225
Makoto Onukia52562c2015-10-01 16:12:31 -0700226 private void initializeDpms() {
227 // Need clearCallingIdentity() to pass permission checks.
228 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100229 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700230
Pavel Grafov75c0a892017-05-18 17:28:27 +0100231 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
232 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
233 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700234
Pavel Grafov75c0a892017-05-18 17:28:27 +0100235 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700236
Pavel Grafov75c0a892017-05-18 17:28:27 +0100237 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700238 }
239
Makoto Onukib643fb02015-09-22 15:03:44 -0700240 private void setUpUserManager() {
241 // Emulate UserManager.set/getApplicationRestriction().
242 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
243
244 // UM.setApplicationRestrictions() will save to appRestrictions.
245 doAnswer(new Answer<Void>() {
246 @Override
247 public Void answer(InvocationOnMock invocation) throws Throwable {
248 String pkg = (String) invocation.getArguments()[0];
249 Bundle bundle = (Bundle) invocation.getArguments()[1];
250 UserHandle user = (UserHandle) invocation.getArguments()[2];
251
252 appRestrictions.put(Pair.create(pkg, user), bundle);
253
254 return null;
255 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100256 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100257 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700258
259 // UM.getApplicationRestrictions() will read from appRestrictions.
260 doAnswer(new Answer<Bundle>() {
261 @Override
262 public Bundle answer(InvocationOnMock invocation) throws Throwable {
263 String pkg = (String) invocation.getArguments()[0];
264 UserHandle user = (UserHandle) invocation.getArguments()[1];
265
266 return appRestrictions.get(Pair.create(pkg, user));
267 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100268 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700269 anyString(), any(UserHandle.class));
270
Makoto Onukid932f762015-09-29 16:53:38 -0700271 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100272 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700273 }
274
275 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100276 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700277
Pavel Grafov75c0a892017-05-18 17:28:27 +0100278 mServiceContext.binder.callingUid =
279 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
280 runAsCaller(mServiceContext, dpms, dpm -> {
281 // PO needs to be a DA.
282 dpm.setActiveAdmin(admin, /*replace=*/ false);
283 // Fire!
284 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
285 // Check
286 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
287 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700288
Pavel Grafov75c0a892017-05-18 17:28:27 +0100289 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700290 }
291
292 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100293 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700294 .thenReturn(false);
295
296 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100297 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700298
299 // If the device has no DPMS feature, it shouldn't register the local service.
300 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
301 }
302
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800303 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800304 // Device owner in SYSTEM_USER
305 setDeviceOwner();
306 // Profile owner in CALLER_USER_HANDLE
307 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
308 setAsProfileOwner(admin2);
309 // Active admin in CALLER_USER_HANDLE
310 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
311 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
312 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
313 DpmMockContext.CALLER_USER_HANDLE);
314 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
315 DpmMockContext.CALLER_USER_HANDLE));
316
317 initializeDpms();
318
319 // Verify
320 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800321 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800322 eq(UserHandle.USER_SYSTEM));
323 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800324 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800325 adminAnotherPackage.getPackageName()),
326 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800327 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
328 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
329 }
330
331 public void testLoadAdminData_noAdmins() throws Exception {
332 final int ANOTHER_USER_ID = 15;
333 getServices().addUser(ANOTHER_USER_ID, 0);
334
335 initializeDpms();
336
337 // Verify
338 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
339 null, DpmMockContext.CALLER_USER_HANDLE);
340 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
341 null, ANOTHER_USER_ID);
342 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
343 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800344 }
345
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700346 /**
347 * Caller doesn't have proper permissions.
348 */
349 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700350 // 1. Failure cases.
351
352 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100353 assertExpectException(SecurityException.class, /* messageRegex= */ null,
354 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700355
356 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
357 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100358
359 assertExpectException(SecurityException.class, /* messageRegex= */ null,
360 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700361 }
362
Makoto Onukif76b06a2015-09-22 15:03:44 -0700363 /**
364 * Test for:
365 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800366 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700367 * {@link DevicePolicyManager#isAdminActive}
368 * {@link DevicePolicyManager#isAdminActiveAsUser}
369 * {@link DevicePolicyManager#getActiveAdmins}
370 * {@link DevicePolicyManager#getActiveAdminsAsUser}
371 */
372 public void testSetActiveAdmin() throws Exception {
373 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700374 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
375
Makoto Onukif76b06a2015-09-22 15:03:44 -0700376 // 2. Call the API.
377 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700378
379 // 3. Verify internal calls.
380
381 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700382 verify(mContext.spiedContext).sendBroadcastAsUser(
383 MockUtils.checkIntentAction(
384 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
385 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
386 verify(mContext.spiedContext).sendBroadcastAsUser(
387 MockUtils.checkIntentAction(
388 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700389 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
390
Pavel Grafov75c0a892017-05-18 17:28:27 +0100391 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700392 eq(admin1.getPackageName()),
393 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
394 eq(PackageManager.DONT_KILL_APP),
395 eq(DpmMockContext.CALLER_USER_HANDLE),
396 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700397
Sudheer Shanka101c3532018-01-08 16:28:42 -0800398 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
399 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
400
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700401 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700402
403 // Make sure it's active admin1.
404 assertTrue(dpm.isAdminActive(admin1));
405 assertFalse(dpm.isAdminActive(admin2));
406 assertFalse(dpm.isAdminActive(admin3));
407
408 // But not admin1 for a different user.
409
410 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
411 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
412 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
413
414 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
415 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
416
417 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
418
419 // Next, add one more admin.
420 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700421 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700422 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700423
424 dpm.setActiveAdmin(admin2, /* replace =*/ false);
425
426 // Now we have two admins.
427 assertTrue(dpm.isAdminActive(admin1));
428 assertTrue(dpm.isAdminActive(admin2));
429 assertFalse(dpm.isAdminActive(admin3));
430
431 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
432 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100433 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700434 eq(admin1.getPackageName()),
435 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
436 eq(PackageManager.DONT_KILL_APP),
437 eq(DpmMockContext.CALLER_USER_HANDLE),
438 anyString());
439
Sudheer Shanka101c3532018-01-08 16:28:42 -0800440 // times(2) because it was previously called for admin1 which is in the same package
441 // as admin2.
442 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
443 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
444
Makoto Onukif76b06a2015-09-22 15:03:44 -0700445 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100446 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
447 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700448
449 // 5. Add the same admin1 again with replace, which should succeed.
450 dpm.setActiveAdmin(admin1, /* replace =*/ true);
451
452 // TODO make sure it's replaced.
453
454 // 6. Test getActiveAdmins()
455 List<ComponentName> admins = dpm.getActiveAdmins();
456 assertEquals(2, admins.size());
457 assertEquals(admin1, admins.get(0));
458 assertEquals(admin2, admins.get(1));
459
Sudheer Shanka101c3532018-01-08 16:28:42 -0800460 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
461 // replaced
462 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
463
Makoto Onukif76b06a2015-09-22 15:03:44 -0700464 // Another user has no admins.
465 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
466
467 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
468 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
469
470 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
471 }
472
Makoto Onukid932f762015-09-29 16:53:38 -0700473 public void testSetActiveAdmin_multiUsers() throws Exception {
474
475 final int ANOTHER_USER_ID = 100;
476 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
477
Pavel Grafov75c0a892017-05-18 17:28:27 +0100478 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700479
480 // Set up pacakge manager for the other user.
481 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700482
483 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
484
485 dpm.setActiveAdmin(admin1, /* replace =*/ false);
486
487 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
488 dpm.setActiveAdmin(admin2, /* replace =*/ false);
489
490
491 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
492 assertTrue(dpm.isAdminActive(admin1));
493 assertFalse(dpm.isAdminActive(admin2));
494
495 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
496 assertFalse(dpm.isAdminActive(admin1));
497 assertTrue(dpm.isAdminActive(admin2));
498 }
499
Makoto Onukif76b06a2015-09-22 15:03:44 -0700500 /**
501 * Test for:
502 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800503 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700504 */
505 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
506 // 1. Make sure the caller has proper permissions.
507 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
508
509 dpm.setActiveAdmin(admin1, /* replace =*/ false);
510 assertTrue(dpm.isAdminActive(admin1));
511
512 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100513 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
514 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700515 }
516
517 /**
518 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800519 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
520 * BIND_DEVICE_ADMIN.
521 */
522 public void testSetActiveAdmin_permissionCheck() throws Exception {
523 // 1. Make sure the caller has proper permissions.
524 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
525
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100526 assertExpectException(IllegalArgumentException.class,
527 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
528 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800529 assertFalse(dpm.isAdminActive(adminNoPerm));
530
531 // Change the target API level to MNC. Now it can be set as DA.
532 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
533 VERSION_CODES.M);
534 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
535 assertTrue(dpm.isAdminActive(adminNoPerm));
536
537 // TODO Test the "load from the file" case where DA will still be loaded even without
538 // BIND_DEVICE_ADMIN and target API is N.
539 }
540
541 /**
542 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700543 * {@link DevicePolicyManager#removeActiveAdmin}
544 */
545 public void testRemoveActiveAdmin_SecurityException() {
546 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
547
548 // Add admin.
549
550 dpm.setActiveAdmin(admin1, /* replace =*/ false);
551
552 assertTrue(dpm.isAdminActive(admin1));
553
554 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
555
556 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100557 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
558 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700559
560 // Try to remove active admin with a different caller userid should fail too, without
561 // having MANAGE_DEVICE_ADMINS.
562 mContext.callerPermissions.clear();
563
Makoto Onukid932f762015-09-29 16:53:38 -0700564 // Change the caller, and call into DPMS directly with a different user-id.
565
Makoto Onukif76b06a2015-09-22 15:03:44 -0700566 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100567 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
568 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700569 }
570
571 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800572 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
573 * (because we can't send the remove broadcast).
574 */
575 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
576 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
577
578 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
579
580 // Add admin.
581
582 dpm.setActiveAdmin(admin1, /* replace =*/ false);
583
584 assertTrue(dpm.isAdminActive(admin1));
585
586 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
587
588 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100589 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800590 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100591 assertExpectException(IllegalStateException.class,
592 /* messageRegex= */ "User must be running and unlocked",
593 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800594
595 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800596 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
597 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800598
599 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100600 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800601 .thenReturn(true);
602
603 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700604 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800605 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
606 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800607 }
608
609 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700610 * Test for:
611 * {@link DevicePolicyManager#removeActiveAdmin}
612 */
Makoto Onukid932f762015-09-29 16:53:38 -0700613 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700614 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
615
616 // Add admin1.
617
618 dpm.setActiveAdmin(admin1, /* replace =*/ false);
619
620 assertTrue(dpm.isAdminActive(admin1));
621 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
622
623 // Different user, but should work, because caller has proper permissions.
624 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700625
626 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700627 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700628
629 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700630 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800631 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
632 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700633
634 // TODO DO Still can't be removed in this case.
635 }
636
637 /**
638 * Test for:
639 * {@link DevicePolicyManager#removeActiveAdmin}
640 */
641 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
642 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
643 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
644
645 // Add admin1.
646
647 dpm.setActiveAdmin(admin1, /* replace =*/ false);
648
649 assertTrue(dpm.isAdminActive(admin1));
650 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
651
652 // Broadcast from saveSettingsLocked().
653 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
654 MockUtils.checkIntentAction(
655 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
656 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
657
658 // Remove. No permissions, but same user, so it'll work.
659 mContext.callerPermissions.clear();
660 dpm.removeActiveAdmin(admin1);
661
Makoto Onukif76b06a2015-09-22 15:03:44 -0700662 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
663 MockUtils.checkIntentAction(
664 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
665 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
666 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700667 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700668 eq(dpms.mHandler),
669 eq(Activity.RESULT_OK),
670 isNull(String.class),
671 isNull(Bundle.class));
672
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700673 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800674 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
675 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700676
677 // Again broadcast from saveSettingsLocked().
678 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
679 MockUtils.checkIntentAction(
680 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
681 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
682
683 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700684 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700685
Sudheer Shanka101c3532018-01-08 16:28:42 -0800686 public void testRemoveActiveAdmin_multipleAdminsInUser() {
687 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
688 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
689
690 // Add admin1.
691 dpm.setActiveAdmin(admin1, /* replace =*/ false);
692
693 assertTrue(dpm.isAdminActive(admin1));
694 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
695
696 // Add admin2.
697 dpm.setActiveAdmin(admin2, /* replace =*/ false);
698
699 assertTrue(dpm.isAdminActive(admin2));
700 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
701
702 // Broadcast from saveSettingsLocked().
703 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
704 MockUtils.checkIntentAction(
705 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
706 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
707
708 // Remove. No permissions, but same user, so it'll work.
709 mContext.callerPermissions.clear();
710 dpm.removeActiveAdmin(admin1);
711
712 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
713 MockUtils.checkIntentAction(
714 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
715 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
716 isNull(String.class),
717 any(BroadcastReceiver.class),
718 eq(dpms.mHandler),
719 eq(Activity.RESULT_OK),
720 isNull(String.class),
721 isNull(Bundle.class));
722
723 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
724 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800725 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800726 eq(DpmMockContext.CALLER_USER_HANDLE));
727
728 // Again broadcast from saveSettingsLocked().
729 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
730 MockUtils.checkIntentAction(
731 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
732 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
733 }
734
735 /**
736 * Test for:
737 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
738 */
739 public void testForceRemoveActiveAdmin() throws Exception {
740 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
741
742 // Add admin.
743 setupPackageInPackageManager(admin1.getPackageName(),
744 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
745 /* appId= */ 10138,
746 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
747 dpm.setActiveAdmin(admin1, /* replace =*/ false);
748 assertTrue(dpm.isAdminActive(admin1));
749
750 // Calling from a non-shell uid should fail with a SecurityException
751 mContext.binder.callingUid = 123456;
752 assertExpectException(SecurityException.class,
753 /* messageRegex =*/ "Non-shell user attempted to call",
754 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
755
756 mContext.binder.callingUid = Process.SHELL_UID;
757 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
758
759 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
760 // Verify
761 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
762 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
763 null, DpmMockContext.CALLER_USER_HANDLE);
764 }
765
Makoto Onukib643fb02015-09-22 15:03:44 -0700766 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000767 * Test for: @{link DevicePolicyManager#setActivePasswordState}
768 *
769 * Validates that when the password for a user changes, the notification broadcast intent
770 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
771 * addition to ones in the original user.
772 */
773 public void testSetActivePasswordState_sendToProfiles() throws Exception {
774 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
775
776 final int MANAGED_PROFILE_USER_ID = 78;
777 final int MANAGED_PROFILE_ADMIN_UID =
778 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
779
780 // Setup device owner.
781 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
782 mContext.packageName = admin1.getPackageName();
783 setupDeviceOwner();
784
785 // Add a managed profile belonging to the system user.
786 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
787
788 // Change the parent user's password.
789 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
790
791 // Both the device owner and the managed profile owner should receive this broadcast.
792 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
793 intent.setComponent(admin1);
794 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
795
796 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
797 MockUtils.checkIntent(intent),
798 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
799 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
800 MockUtils.checkIntent(intent),
801 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
802 }
803
804 /**
805 * Test for: @{link DevicePolicyManager#setActivePasswordState}
806 *
807 * Validates that when the password for a managed profile changes, the notification broadcast
808 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
809 * its parent.
810 */
811 public void testSetActivePasswordState_notSentToParent() throws Exception {
812 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
813
814 final int MANAGED_PROFILE_USER_ID = 78;
815 final int MANAGED_PROFILE_ADMIN_UID =
816 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
817
818 // Setup device owner.
819 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
820 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100821 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000822 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
823 setupDeviceOwner();
824
825 // Add a managed profile belonging to the system user.
826 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
827
828 // Change the profile's password.
829 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
830
831 // Both the device owner and the managed profile owner should receive this broadcast.
832 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
833 intent.setComponent(admin1);
834 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
835
836 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
837 MockUtils.checkIntent(intent),
838 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
839 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
840 MockUtils.checkIntent(intent),
841 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
842 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100843
Robin Leed2a73ed2016-12-19 09:07:16 +0000844 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000845 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700846 */
847 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000848 setDeviceOwner();
849
850 // Try to set a profile owner on the same user, which should fail.
851 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
852 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100853 assertExpectException(IllegalStateException.class,
854 /* messageRegex= */ "already has a device owner",
855 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000856
857 // DO admin can't be deactivated.
858 dpm.removeActiveAdmin(admin1);
859 assertTrue(dpm.isAdminActive(admin1));
860
861 // TODO Test getDeviceOwnerName() too. To do so, we need to change
862 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
863 }
864
865 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700866 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800867 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700868 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
869 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
870
Makoto Onukid932f762015-09-29 16:53:38 -0700871 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700872 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
873
Makoto Onukid932f762015-09-29 16:53:38 -0700874 // Make sure admin1 is installed on system user.
875 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700876
Makoto Onukic8a5a552015-11-19 14:29:12 -0800877 // Check various get APIs.
878 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
879
Makoto Onukib643fb02015-09-22 15:03:44 -0700880 // DO needs to be an DA.
881 dpm.setActiveAdmin(admin1, /* replace =*/ false);
882
883 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700884 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700885
Makoto Onukic8a5a552015-11-19 14:29:12 -0800886 // getDeviceOwnerComponent should return the admin1 component.
887 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
888 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
889
890 // Check various get APIs.
891 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
892
893 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
894 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
895 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
896 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
897
898 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
899
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000900 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100901 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000902 eq(admin1.getPackageName()));
903
Makoto Onukib643fb02015-09-22 15:03:44 -0700904 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100905 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700906 eq(UserHandle.USER_SYSTEM), eq(false));
907
908 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
909 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
910 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
911
Makoto Onukic8a5a552015-11-19 14:29:12 -0800912 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700913 }
914
Makoto Onukic8a5a552015-11-19 14:29:12 -0800915 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
916 final int origCallingUser = mContext.binder.callingUid;
917 final List origPermissions = new ArrayList(mContext.callerPermissions);
918 mContext.callerPermissions.clear();
919
920 mContext.callerPermissions.add(permission.MANAGE_USERS);
921
922 mContext.binder.callingUid = Process.SYSTEM_UID;
923
924 // TODO Test getDeviceOwnerName() too. To do so, we need to change
925 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
926 if (hasDeviceOwner) {
927 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
928 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
929 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
930
931 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
932 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
933 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
934 } else {
935 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
936 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
937 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
938
939 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
940 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
941 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
942 }
943
944 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
945 if (hasDeviceOwner) {
946 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
947 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
948 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
949
950 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
951 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
952 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
953 } else {
954 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
955 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
956 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
957
958 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
959 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
960 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
961 }
962
963 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
964 // Still with MANAGE_USERS.
965 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
966 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
967 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
968
969 if (hasDeviceOwner) {
970 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
971 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
972 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
973 } else {
974 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
975 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
976 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
977 }
978
979 mContext.binder.callingUid = Process.SYSTEM_UID;
980 mContext.callerPermissions.remove(permission.MANAGE_USERS);
981 // System can still call "OnAnyUser" without MANAGE_USERS.
982 if (hasDeviceOwner) {
983 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
984 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
985 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
986
987 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
988 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
989 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
990 } else {
991 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
992 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
993 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
994
995 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
996 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
997 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
998 }
999
1000 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1001 // Still no MANAGE_USERS.
1002 if (hasDeviceOwner) {
1003 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1004 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1005 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1006 } else {
1007 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1008 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1009 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1010 }
1011
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001012 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1013 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1014 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1015 dpm::getDeviceOwnerComponentOnAnyUser);
1016 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1017 dpm::getDeviceOwnerUserId);
1018 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1019 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001020
1021 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1022 // Still no MANAGE_USERS.
1023 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1024 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1025 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1026
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001027 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1028 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1029 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1030 dpm::getDeviceOwnerComponentOnAnyUser);
1031 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1032 dpm::getDeviceOwnerUserId);
1033 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1034 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001035
1036 // Restore.
1037 mContext.binder.callingUid = origCallingUser;
1038 mContext.callerPermissions.addAll(origPermissions);
1039 }
1040
1041
Makoto Onukib643fb02015-09-22 15:03:44 -07001042 /**
1043 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1044 */
1045 public void testSetDeviceOwner_noSuchPackage() {
1046 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001047 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001048 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1049 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1050
1051 // Call from a process on the system user.
1052 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1053
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001054 assertExpectException(IllegalArgumentException.class,
1055 /* messageRegex= */ "Invalid component",
1056 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001057 }
1058
1059 public void testSetDeviceOwner_failures() throws Exception {
1060 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1061 }
1062
Makoto Onukia52562c2015-10-01 16:12:31 -07001063 public void testClearDeviceOwner() throws Exception {
1064 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001065 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001066 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1067 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1068
1069 // Set admin1 as a DA to the secondary user.
1070 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1071
1072 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1073
1074 // Set admin 1 as the DO to the system user.
1075
1076 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1077 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1078 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1079 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1080
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001081 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001082 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001083 eq(admin1.getPackageName()));
1084
Makoto Onukic8a5a552015-11-19 14:29:12 -08001085 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001086
Makoto Onuki90b89652016-01-28 14:44:18 -08001087 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001088 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001089 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001090
1091 assertTrue(dpm.isAdminActive(admin1));
1092 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1093
Makoto Onukia52562c2015-10-01 16:12:31 -07001094 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001095 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001096
1097 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001098 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1099 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001100
1101 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001102 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001103 assertExpectException(IllegalStateException.class,
1104 /* messageRegex= */ "User must be running and unlocked",
1105 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001106
Pavel Grafov75c0a892017-05-18 17:28:27 +01001107 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1108 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001109 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1110
1111 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001112 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001113
Pavel Grafov75c0a892017-05-18 17:28:27 +01001114 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001115 eq(false),
1116 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1117
Pavel Grafov75c0a892017-05-18 17:28:27 +01001118 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001119 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001120 eq(null),
1121 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001122
Sudheer Shanka101c3532018-01-08 16:28:42 -08001123 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1124 null, UserHandle.USER_SYSTEM);
1125
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001126 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001127
1128 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1129 // and once for clearing it.
1130 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1131 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1132 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001133 // TODO Check other calls.
1134 }
1135
1136 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1137 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001138 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001139 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1140 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1141
1142 // Set admin1 as a DA to the secondary user.
1143 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1144
1145 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1146
1147 // Set admin 1 as the DO to the system user.
1148
1149 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1150 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1151 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1152 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1153
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001154 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001155 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001156 eq(admin1.getPackageName()));
1157
Makoto Onukic8a5a552015-11-19 14:29:12 -08001158 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001159
1160 // Now call clear from the secondary user, which should throw.
1161 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1162
1163 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001164 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001165 eq(admin1.getPackageName()),
1166 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001167 assertExpectException(SecurityException.class,
1168 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1169 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001170
Makoto Onukic8a5a552015-11-19 14:29:12 -08001171 // DO shouldn't be removed.
1172 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001173 }
1174
Makoto Onukib643fb02015-09-22 15:03:44 -07001175 public void testSetProfileOwner() throws Exception {
1176 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001177
Makoto Onuki90b89652016-01-28 14:44:18 -08001178 // PO admin can't be deactivated.
1179 dpm.removeActiveAdmin(admin1);
1180 assertTrue(dpm.isAdminActive(admin1));
1181
Makoto Onuki803d6752015-10-30 12:58:39 -07001182 // Try setting DO on the same user, which should fail.
1183 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001184 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1185 runAsCaller(mServiceContext, dpms, dpm -> {
1186 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001187 assertExpectException(IllegalStateException.class,
1188 /* messageRegex= */ "already has a profile owner",
1189 () -> dpm.setDeviceOwner(admin2, "owner-name",
1190 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001191 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001192 }
1193
Makoto Onuki90b89652016-01-28 14:44:18 -08001194 public void testClearProfileOwner() throws Exception {
1195 setAsProfileOwner(admin1);
1196
1197 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1198
1199 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1200 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1201
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001202 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001203 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001204 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001205 assertExpectException(IllegalStateException.class,
1206 /* messageRegex= */ "User must be running and unlocked",
1207 () -> dpm.clearProfileOwner(admin1));
1208
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001209 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001210 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001211 dpm.clearProfileOwner(admin1);
1212
1213 // Check
1214 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001215 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001216 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1217 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001218 }
1219
Makoto Onukib643fb02015-09-22 15:03:44 -07001220 public void testSetProfileOwner_failures() throws Exception {
1221 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1222 }
1223
Makoto Onukia52562c2015-10-01 16:12:31 -07001224 public void testGetDeviceOwnerAdminLocked() throws Exception {
1225 checkDeviceOwnerWithMultipleDeviceAdmins();
1226 }
1227
1228 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1229 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1230 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1231 // make sure it gets the right component from the right user.
1232
1233 final int ANOTHER_USER_ID = 100;
1234 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1235
Pavel Grafov75c0a892017-05-18 17:28:27 +01001236 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001237
1238 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001239 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001240 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1241 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1242
1243 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1244
Pavel Grafov75c0a892017-05-18 17:28:27 +01001245 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001246
Makoto Onukia52562c2015-10-01 16:12:31 -07001247 // Make sure the admin packge is installed to each user.
1248 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1249 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1250
1251 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1252 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1253
1254 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1255
1256
1257 // Set active admins to the users.
1258 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1259 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1260
1261 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1262 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1263
1264 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1265
1266 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001267 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001268 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1269
Makoto Onukic8a5a552015-11-19 14:29:12 -08001270 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001271
1272 // Then check getDeviceOwnerAdminLocked().
1273 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1274 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1275 }
1276
1277 /**
1278 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001279 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1280 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001281 *
1282 * We didn't use to persist the DO component class name, but now we do, and the above method
1283 * finds the right component from a package name upon migration.
1284 */
1285 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001286 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001287 checkDeviceOwnerWithMultipleDeviceAdmins();
1288
1289 // Overwrite the device owner setting and clears the clas name.
1290 dpms.mOwners.setDeviceOwner(
1291 new ComponentName(admin2.getPackageName(), ""),
1292 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1293 dpms.mOwners.writeDeviceOwner();
1294
1295 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001296 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001297
1298 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001299 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001300 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001301 initializeDpms();
1302
1303 // Now the DO component name is a full name.
1304 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1305 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001306 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001307 }
1308
Makoto Onukib643fb02015-09-22 15:03:44 -07001309 public void testSetGetApplicationRestriction() {
1310 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001311 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001312
1313 {
1314 Bundle rest = new Bundle();
1315 rest.putString("KEY_STRING", "Foo1");
1316 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1317 }
1318
1319 {
1320 Bundle rest = new Bundle();
1321 rest.putString("KEY_STRING", "Foo2");
1322 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1323 }
1324
1325 {
1326 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1327 assertNotNull(returned);
1328 assertEquals(returned.size(), 1);
1329 assertEquals(returned.get("KEY_STRING"), "Foo1");
1330 }
1331
1332 {
1333 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1334 assertNotNull(returned);
1335 assertEquals(returned.size(), 1);
1336 assertEquals(returned.get("KEY_STRING"), "Foo2");
1337 }
1338
1339 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1340 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1341 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001342
Edman Anjosf9946772016-11-28 16:35:15 +01001343 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001344 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1345 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001346 *
1347 * @param packageName the name of the package to be setup
1348 * @param appId the application ID to be given to the package
1349 * @return the UID of the package as known by the mock package manager
1350 */
1351 private int setupPackageInPackageManager(final String packageName, final int appId)
1352 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001353 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001354 ApplicationInfo.FLAG_HAS_CODE);
1355 }
1356
1357 /**
1358 * Setup a package in the package manager mock. Useful for faking installed applications.
1359 *
1360 * @param packageName the name of the package to be setup
1361 * @param userId the user id where the package will be "installed"
1362 * @param appId the application ID to be given to the package
1363 * @param flags flags to set in the ApplicationInfo for this package
1364 * @return the UID of the package as known by the mock package manager
1365 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001366 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1367 int flags) throws Exception {
1368 final int uid = UserHandle.getUid(userId, appId);
1369 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001370 final PackageInfo pi = new PackageInfo();
1371 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001372 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001373 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001374 eq(packageName),
1375 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001376 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001377 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001378 eq(packageName),
1379 anyInt(),
1380 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001381 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001382 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001383 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001384 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001385 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001386 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001387 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001388 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001389 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001390 return uid;
1391 }
1392
Robin Lee7f5c91c2017-02-08 21:27:02 +00001393 public void testCertificateDisclosure() throws Exception {
1394 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1395 final UserHandle user = UserHandle.of(userId);
1396
1397 mContext.applicationInfo = new ApplicationInfo();
1398 mContext.callerPermissions.add(permission.MANAGE_USERS);
1399 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001400 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001401 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1402
Robin Leeabaa0692017-02-20 20:54:22 +00001403 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1404 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001405
1406 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1407 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1408
1409 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001410 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001411 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001412 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001413 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001414 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001415 .cancelAsUser(anyString(), anyInt(), eq(user));
1416
1417 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001418 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001419 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001420 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1421 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001422 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001423 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001424 .notifyAsUser(anyString(), anyInt(), argThat(
1425 new BaseMatcher<Notification>() {
1426 @Override
1427 public boolean matches(Object item) {
1428 final Notification noti = (Notification) item;
1429 return TEST_STRING.equals(
1430 noti.extras.getString(Notification.EXTRA_TITLE));
1431 }
1432 @Override
1433 public void describeTo(Description description) {
1434 description.appendText(
1435 "Notification{title=\"" + TEST_STRING + "\"}");
1436 }
1437 }), eq(user));
1438 }
1439
Edman Anjosf9946772016-11-28 16:35:15 +01001440 /**
1441 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1442 * privileges can acually be exercised by a delegate are not covered here.
1443 */
1444 public void testDelegation() throws Exception {
1445 setAsProfileOwner(admin1);
1446
1447 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1448
1449 // Given two packages
1450 final String CERT_DELEGATE = "com.delegate.certs";
1451 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1452 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1453 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1454 20989);
1455
1456 // On delegation
1457 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1458 mContext.packageName = admin1.getPackageName();
1459 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1460 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1461
1462 // DPMS correctly stores and retrieves the delegates
1463 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1464 assertEquals(2, policy.mDelegationMap.size());
1465 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1466 DELEGATION_CERT_INSTALL);
1467 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1468 DELEGATION_CERT_INSTALL);
1469 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1470 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1471 DELEGATION_APP_RESTRICTIONS);
1472 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1473 DELEGATION_APP_RESTRICTIONS);
1474 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1475
1476 // On calling install certificate APIs from an unauthorized process
1477 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1478 mContext.packageName = RESTRICTIONS_DELEGATE;
1479
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001480 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1481 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001482
1483 // On calling install certificate APIs from an authorized process
1484 mContext.binder.callingUid = CERT_DELEGATE_UID;
1485 mContext.packageName = CERT_DELEGATE;
1486
1487 // DPMS executes without a SecurityException
1488 try {
1489 dpm.installCaCert(null, null);
1490 } catch (SecurityException unexpected) {
1491 fail("Threw SecurityException on authorized access");
1492 } catch (NullPointerException expected) {
1493 }
1494
1495 // On removing a delegate
1496 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1497 mContext.packageName = admin1.getPackageName();
1498 dpm.setCertInstallerPackage(admin1, null);
1499
1500 // DPMS does not allow access to ex-delegate
1501 mContext.binder.callingUid = CERT_DELEGATE_UID;
1502 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001503 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1504 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001505
1506 // But still allows access to other existing delegates
1507 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1508 mContext.packageName = RESTRICTIONS_DELEGATE;
1509 try {
1510 dpm.getApplicationRestrictions(null, "pkg");
1511 } catch (SecurityException expected) {
1512 fail("Threw SecurityException on authorized access");
1513 }
1514 }
1515
Esteban Talaverabf60f722015-12-10 16:26:44 +00001516 public void testApplicationRestrictionsManagingApp() throws Exception {
1517 setAsProfileOwner(admin1);
1518
Rubin Xued1928a2016-02-11 17:23:06 +00001519 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001520 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001521 final String nonDelegateExceptionMessageRegex =
1522 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001523 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001524 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1525 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001526
Esteban Talaverabf60f722015-12-10 16:26:44 +00001527 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1528 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001529 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1530 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001531 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001532 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001533 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001534 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1535 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001536
1537 // Check via the profile owner that no restrictions were set.
1538 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001539 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001540 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1541
Rubin Xued1928a2016-02-11 17:23:06 +00001542 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001543 assertExpectException(PackageManager.NameNotFoundException.class,
1544 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1545 () -> dpm.setApplicationRestrictionsManagingPackage(
1546 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001547
Esteban Talaverabf60f722015-12-10 16:26:44 +00001548 // Let appRestrictionsManagerPackage manage app restrictions
1549 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1550 assertEquals(appRestrictionsManagerPackage,
1551 dpm.getApplicationRestrictionsManagingPackage(admin1));
1552
1553 // Now that package should be able to set and retrieve app restrictions.
1554 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001555 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001556 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1557 dpm.setApplicationRestrictions(null, "pkg1", rest);
1558 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1559 assertEquals(1, returned.size(), 1);
1560 assertEquals("Foo1", returned.get("KEY_STRING"));
1561
1562 // The same app running on a separate user shouldn't be able to manage app restrictions.
1563 mContext.binder.callingUid = UserHandle.getUid(
1564 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1565 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001566 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1567 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001568
1569 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1570 // too.
1571 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001572 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001573 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1574 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1575 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1576
1577 // Removing the ability for the package to manage app restrictions.
1578 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1579 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1580 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001581 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001582 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001583 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1584 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001585 }
1586
Makoto Onukia4f11972015-10-01 13:19:58 -07001587 public void testSetUserRestriction_asDo() throws Exception {
1588 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001589 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001590 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1591 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1592
1593 // First, set DO.
1594
1595 // Call from a process on the system user.
1596 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1597
1598 // Make sure admin1 is installed on system user.
1599 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001600
1601 // Call.
1602 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001603 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001604 UserHandle.USER_SYSTEM));
1605
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001606 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001607 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001608 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001609 DpmTestUtils.assertRestrictions(
1610 DpmTestUtils.newRestrictions(defaultRestrictions),
1611 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1612 );
1613 DpmTestUtils.assertRestrictions(
1614 DpmTestUtils.newRestrictions(defaultRestrictions),
1615 dpm.getUserRestrictions(admin1)
1616 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001617 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001618 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001619 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001620 eq(true) /* isDeviceOwner */,
1621 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001622 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001623 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001624
1625 for (String restriction : defaultRestrictions) {
1626 dpm.clearUserRestriction(admin1, restriction);
1627 }
1628
Esteban Talavera548a04b2016-12-20 15:22:30 +00001629 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001630 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001631
1632 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001633 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001634 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001635 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1636 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001637 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001638
Makoto Onukia4f11972015-10-01 13:19:58 -07001639 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001640 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001641 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001642 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1643 UserManager.DISALLOW_ADD_USER),
1644 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001645 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001646
Makoto Onuki068c54a2015-10-13 14:34:03 -07001647 DpmTestUtils.assertRestrictions(
1648 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001650 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1651 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001652 DpmTestUtils.assertRestrictions(
1653 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001654 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001655 dpm.getUserRestrictions(admin1)
1656 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001657
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001658 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001659 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001660 eq(UserHandle.USER_SYSTEM),
1661 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001662 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001663 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001664
Makoto Onuki068c54a2015-10-13 14:34:03 -07001665 DpmTestUtils.assertRestrictions(
1666 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1667 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1668 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001669 DpmTestUtils.assertRestrictions(
1670 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1671 dpm.getUserRestrictions(admin1)
1672 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001673
1674 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001675 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001676 eq(UserHandle.USER_SYSTEM),
1677 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001678 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001679 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001680
Esteban Talavera548a04b2016-12-20 15:22:30 +00001681 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001682
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1684 // DO sets them, the scope is global.
1685 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001686 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001688 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001690 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001691 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1692 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001693 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001694
1695 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1696 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001697 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698
1699 // More tests.
1700 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001701 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001702 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001703 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1704 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001705 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706
1707 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001708 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001709 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001711 UserManager.DISALLOW_ADD_USER),
1712 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001713 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001714
1715 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001716 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001717 eq(UserHandle.USER_SYSTEM),
1718 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001719 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001720 UserManager.DISALLOW_ADD_USER),
1721 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001722 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001723 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001724
Eric Sandnessca5969d2018-08-10 13:28:46 +01001725 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1726 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1727 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001728
Eric Sandnessca5969d2018-08-10 13:28:46 +01001729 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1730 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001731
Eric Sandnessca5969d2018-08-10 13:28:46 +01001732 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1733 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1734 () -> dpm.setCameraDisabled(admin1, true));
1735 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1736
1737 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1738 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1739 () -> dpm.setKeyguardDisabledFeatures(admin1,
1740 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1741 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1742
1743 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1744 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1745 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1746 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1747
1748 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1749 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1750 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1751 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001752 }
1753
1754 public void testSetUserRestriction_asPo() {
1755 setAsProfileOwner(admin1);
1756
Makoto Onuki068c54a2015-10-13 14:34:03 -07001757 DpmTestUtils.assertRestrictions(
1758 DpmTestUtils.newRestrictions(),
1759 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1760 .ensureUserRestrictions()
1761 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001762
1763 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001764 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001765 eq(DpmMockContext.CALLER_USER_HANDLE),
1766 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001767 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001768 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001769
Makoto Onukia4f11972015-10-01 13:19:58 -07001770 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001771 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001772 eq(DpmMockContext.CALLER_USER_HANDLE),
1773 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1774 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001775 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001776 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001777
Makoto Onuki068c54a2015-10-13 14:34:03 -07001778 DpmTestUtils.assertRestrictions(
1779 DpmTestUtils.newRestrictions(
1780 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1781 UserManager.DISALLOW_OUTGOING_CALLS
1782 ),
1783 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1784 .ensureUserRestrictions()
1785 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001786 DpmTestUtils.assertRestrictions(
1787 DpmTestUtils.newRestrictions(
1788 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1789 UserManager.DISALLOW_OUTGOING_CALLS
1790 ),
1791 dpm.getUserRestrictions(admin1)
1792 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001793
1794 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001795 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001796 eq(DpmMockContext.CALLER_USER_HANDLE),
1797 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001798 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001799 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001800
1801 DpmTestUtils.assertRestrictions(
1802 DpmTestUtils.newRestrictions(
1803 UserManager.DISALLOW_OUTGOING_CALLS
1804 ),
1805 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1806 .ensureUserRestrictions()
1807 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001808 DpmTestUtils.assertRestrictions(
1809 DpmTestUtils.newRestrictions(
1810 UserManager.DISALLOW_OUTGOING_CALLS
1811 ),
1812 dpm.getUserRestrictions(admin1)
1813 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001814
1815 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001816 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001817 eq(DpmMockContext.CALLER_USER_HANDLE),
1818 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001819 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001820 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001821
Makoto Onuki068c54a2015-10-13 14:34:03 -07001822 DpmTestUtils.assertRestrictions(
1823 DpmTestUtils.newRestrictions(),
1824 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1825 .ensureUserRestrictions()
1826 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001827 DpmTestUtils.assertRestrictions(
1828 DpmTestUtils.newRestrictions(),
1829 dpm.getUserRestrictions(admin1)
1830 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001831
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001832 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1833 // though when DO sets them they'll be applied globally.
1834 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001835 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001836 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001837 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001838 eq(DpmMockContext.CALLER_USER_HANDLE),
1839 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1840 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001841 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001842 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001843
1844 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001845 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001846 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001847 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001848 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001849 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001850 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001851
Makoto Onukia4f11972015-10-01 13:19:58 -07001852 // TODO Make sure restrictions are written to the file.
1853 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001854
Esteban Talavera548a04b2016-12-20 15:22:30 +00001855
1856 public void testDefaultEnabledUserRestrictions() throws Exception {
1857 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1858 mContext.callerPermissions.add(permission.MANAGE_USERS);
1859 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1860 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1861
1862 // First, set DO.
1863
1864 // Call from a process on the system user.
1865 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1866
1867 // Make sure admin1 is installed on system user.
1868 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1869
1870 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1871 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1872 UserHandle.USER_SYSTEM));
1873
1874 // Check that the user restrictions that are enabled by default are set. Then unset them.
1875 String[] defaultRestrictions = UserRestrictionsUtils
1876 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1877 assertTrue(defaultRestrictions.length > 0);
1878 DpmTestUtils.assertRestrictions(
1879 DpmTestUtils.newRestrictions(defaultRestrictions),
1880 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1881 );
1882 DpmTestUtils.assertRestrictions(
1883 DpmTestUtils.newRestrictions(defaultRestrictions),
1884 dpm.getUserRestrictions(admin1)
1885 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001886 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001887 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001888 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001889 eq(true) /* isDeviceOwner */,
1890 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001891 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001892 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001893
1894 for (String restriction : defaultRestrictions) {
1895 dpm.clearUserRestriction(admin1, restriction);
1896 }
1897
1898 assertNoDeviceOwnerRestrictions();
1899
1900 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001901 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001902 initializeDpms();
1903 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1904 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1905
1906 assertNoDeviceOwnerRestrictions();
1907
1908 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1909 // is set as it wasn't enabled during setDeviceOwner.
1910 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1911 assertFalse(UserRestrictionsUtils
1912 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1913 UserRestrictionsUtils
1914 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1915 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001916 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001917 initializeDpms();
1918 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1919 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1920
1921 DpmTestUtils.assertRestrictions(
1922 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1923 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1924 );
1925 DpmTestUtils.assertRestrictions(
1926 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1927 dpm.getUserRestrictions(admin1)
1928 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001929 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001930 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001931 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001932 eq(true) /* isDeviceOwner */,
1933 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001934 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001935 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001936
1937 // Remove the restriction.
1938 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1939
1940 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1941 initializeDpms();
1942 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1943 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1944 assertNoDeviceOwnerRestrictions();
1945 } finally {
1946 UserRestrictionsUtils
1947 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1948 }
1949 }
1950
1951 private void assertNoDeviceOwnerRestrictions() {
1952 DpmTestUtils.assertRestrictions(
1953 DpmTestUtils.newRestrictions(),
1954 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1955 );
1956 DpmTestUtils.assertRestrictions(
1957 DpmTestUtils.newRestrictions(),
1958 dpm.getUserRestrictions(admin1)
1959 );
1960 }
1961
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001962 public void testGetMacAddress() throws Exception {
1963 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1964 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1965 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1966
1967 // In this test, change the caller user to "system".
1968 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1969
1970 // Make sure admin1 is installed on system user.
1971 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1972
1973 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001974 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1975 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001976
1977 // DO needs to be an DA.
1978 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1979 assertTrue(dpm.isAdminActive(admin1));
1980
1981 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001982 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1983 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001984
1985 // Test 3. Caller has PO, but not DO.
1986 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001987 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1988 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001989
1990 // Remove PO.
1991 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001992 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001993 // Test 4, Caller is DO now.
1994 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1995
xshu425b9a62018-12-13 14:18:18 -08001996 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001997 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001998
xshu425b9a62018-12-13 14:18:18 -08001999 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2000 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002001 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002002
2003 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002004 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2005 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002006 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002007 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002008
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002009 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002010 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2011 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2012
2013 // In this test, change the caller user to "system".
2014 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2015
2016 // Make sure admin1 is installed on system user.
2017 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2018
2019 // Set admin1 as DA.
2020 dpm.setActiveAdmin(admin1, false);
2021 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002022 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2023 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002024
2025 // Set admin1 as PO.
2026 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002027 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2028 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002029
2030 // Remove PO and add DO.
2031 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002032 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002033 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2034
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002035 // admin1 is DO.
2036 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002037 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002038 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002039 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2040 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002041
2042 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002043 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002044 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002045 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2046 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002047
2048 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002049 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002050 dpm.reboot(admin1);
2051 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002052
2053 public void testSetGetSupportText() {
2054 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2055 dpm.setActiveAdmin(admin1, true);
2056 dpm.setActiveAdmin(admin2, true);
2057 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2058
2059 // Null default support messages.
2060 {
2061 assertNull(dpm.getLongSupportMessage(admin1));
2062 assertNull(dpm.getShortSupportMessage(admin1));
2063 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2064 assertNull(dpm.getShortSupportMessageForUser(admin1,
2065 DpmMockContext.CALLER_USER_HANDLE));
2066 assertNull(dpm.getLongSupportMessageForUser(admin1,
2067 DpmMockContext.CALLER_USER_HANDLE));
2068 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2069 }
2070
2071 // Only system can call the per user versions.
2072 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002073 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2074 () -> dpm.getShortSupportMessageForUser(admin1,
2075 DpmMockContext.CALLER_USER_HANDLE));
2076 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2077 () -> dpm.getLongSupportMessageForUser(admin1,
2078 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002079 }
2080
2081 // Can't set message for admin in another uid.
2082 {
2083 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002084 assertExpectException(SecurityException.class,
2085 /* messageRegex= */ "is not owned by uid",
2086 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002087 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2088 }
2089
2090 // Set/Get short returns what it sets and other admins text isn't changed.
2091 {
2092 final String supportText = "Some text to test with.";
2093 dpm.setShortSupportMessage(admin1, supportText);
2094 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2095 assertNull(dpm.getLongSupportMessage(admin1));
2096 assertNull(dpm.getShortSupportMessage(admin2));
2097
2098 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2099 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2100 DpmMockContext.CALLER_USER_HANDLE));
2101 assertNull(dpm.getShortSupportMessageForUser(admin2,
2102 DpmMockContext.CALLER_USER_HANDLE));
2103 assertNull(dpm.getLongSupportMessageForUser(admin1,
2104 DpmMockContext.CALLER_USER_HANDLE));
2105 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2106
2107 dpm.setShortSupportMessage(admin1, null);
2108 assertNull(dpm.getShortSupportMessage(admin1));
2109 }
2110
2111 // Set/Get long returns what it sets and other admins text isn't changed.
2112 {
2113 final String supportText = "Some text to test with.\nWith more text.";
2114 dpm.setLongSupportMessage(admin1, supportText);
2115 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2116 assertNull(dpm.getShortSupportMessage(admin1));
2117 assertNull(dpm.getLongSupportMessage(admin2));
2118
2119 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2120 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2121 DpmMockContext.CALLER_USER_HANDLE));
2122 assertNull(dpm.getLongSupportMessageForUser(admin2,
2123 DpmMockContext.CALLER_USER_HANDLE));
2124 assertNull(dpm.getShortSupportMessageForUser(admin1,
2125 DpmMockContext.CALLER_USER_HANDLE));
2126 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2127
2128 dpm.setLongSupportMessage(admin1, null);
2129 assertNull(dpm.getLongSupportMessage(admin1));
2130 }
2131 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002132
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002133 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002134 setAsProfileOwner(admin1);
2135
2136 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002137 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002138
2139 // Setup
2140 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2141 final String package1 = "com.example.one";
2142 final String package2 = "com.example.two";
2143 pkgsToRestrict.add(package1);
2144 pkgsToRestrict.add(package2);
2145 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2146 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002147 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002148
2149 // Verify
2150 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002151 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002152 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2153 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2154 eq(DpmMockContext.CALLER_USER_HANDLE));
2155
2156 // Setup
2157 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002158 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002159
2160 // Verify
2161 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002162 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002163 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2164 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2165 eq(DpmMockContext.CALLER_USER_HANDLE));
2166 }
2167
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002168 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002169 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2170 dpm.setActiveAdmin(admin1, true);
2171 assertTrue(dpm.isAdminActive(admin1));
2172 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2173
2174 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002175 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002176 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002177 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002178 }
2179
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002180 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002181 setAsProfileOwner(admin1);
2182
2183 // Setup
2184 final ArrayList<String> emptyList = new ArrayList<>();
2185 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2186 final String package1 = "com.example.one";
2187 final String package2 = "com.example.two";
2188 final String package3 = "com.example.three";
2189 pkgsToRestrict.add(package1);
2190 pkgsToRestrict.add(package2);
2191 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2192 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002193 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002194
2195 // Verify
2196 assertEquals(emptyList, excludedPkgs);
2197 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2198 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002199 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002200 DpmMockContext.CALLER_USER_HANDLE));
2201 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002202 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002203 DpmMockContext.CALLER_USER_HANDLE));
2204 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002205 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002206 DpmMockContext.CALLER_USER_HANDLE));
2207 }
2208
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002209 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002210 setAsProfileOwner(admin1);
2211 assertExpectException(SecurityException.class,
2212 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002213 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002214 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2215 dpm.clearProfileOwner(admin1);
2216
2217 setDeviceOwner();
2218 assertExpectException(SecurityException.class,
2219 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002220 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002221 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2222 clearDeviceOwner();
2223 }
2224
phweiss73145f42017-01-17 19:06:38 +01002225 public void testCreateAdminSupportIntent() throws Exception {
2226 // Setup device owner.
2227 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2228 setupDeviceOwner();
2229
2230 // Nonexisting permission returns null
2231 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2232 assertNull(intent);
2233
2234 // Existing permission that is not set returns null
2235 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2236 assertNull(intent);
2237
2238 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002239 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002240 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2241 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2242 .thenReturn(true);
2243 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2244 assertNull(intent);
2245
2246 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002247 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002248 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2249 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2250 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2251 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2252 assertNotNull(intent);
2253 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2254 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2255 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002256 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002257 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2258 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2259
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002260 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2261 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002262
2263 // Camera is not disabled
2264 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2265 assertNull(intent);
2266
2267 // Camera is disabled
2268 dpm.setCameraDisabled(admin1, true);
2269 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2270 assertNotNull(intent);
2271 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2272 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2273
2274 // Screen capture is not disabled
2275 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2276 assertNull(intent);
2277
2278 // Screen capture is disabled
2279 dpm.setScreenCaptureDisabled(admin1, true);
2280 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2281 assertNotNull(intent);
2282 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2283 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2284
2285 // Same checks for different user
2286 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2287 // Camera should be disabled by device owner
2288 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2289 assertNotNull(intent);
2290 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2291 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2292 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2293 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2294 // ScreenCapture should not be disabled by device owner
2295 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2296 assertNull(intent);
2297 }
2298
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002299 /**
2300 * Test for:
2301 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002302 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002303 * {@link DevicePolicyManager#isAffiliatedUser}
2304 */
2305 public void testUserAffiliation() throws Exception {
2306 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2307 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2308 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2309
2310 // Check that the system user is unaffiliated.
2311 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2312 assertFalse(dpm.isAffiliatedUser());
2313
2314 // Set a device owner on the system user. Check that the system user becomes affiliated.
2315 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2316 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2317 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2318 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002319 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002320
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002321 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002322 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2323 setAsProfileOwner(admin2);
2324 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002325 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002326
2327 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2328 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002329 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002330 userAffiliationIds.add("red");
2331 userAffiliationIds.add("green");
2332 userAffiliationIds.add("blue");
2333 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002334 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002335 assertFalse(dpm.isAffiliatedUser());
2336
2337 // Have the device owner specify a set of affiliation ids that do not intersect with those
2338 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002339 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002340 deviceAffiliationIds.add("cyan");
2341 deviceAffiliationIds.add("yellow");
2342 deviceAffiliationIds.add("magenta");
2343 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2344 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002345 MoreAsserts.assertContentsInAnyOrder(
2346 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002347 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2348 assertFalse(dpm.isAffiliatedUser());
2349
2350 // Have the profile owner specify a set of affiliation ids that intersect with those
2351 // specified by the device owner. Check that the test user becomes affiliated.
2352 userAffiliationIds.add("yellow");
2353 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002354 MoreAsserts.assertContentsInAnyOrder(
2355 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002356 assertTrue(dpm.isAffiliatedUser());
2357
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002358 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002359 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002360 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002361 assertFalse(dpm.isAffiliatedUser());
2362
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002363 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2364 dpm.setAffiliationIds(admin2, userAffiliationIds);
2365 assertTrue(dpm.isAffiliatedUser());
2366 dpm.clearProfileOwner(admin2);
2367 assertFalse(dpm.isAffiliatedUser());
2368
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002369 // Check that the system user remains affiliated.
2370 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2371 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002372
2373 // Clear the device owner - the user becomes unaffiliated.
2374 clearDeviceOwner();
2375 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002376 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002377
2378 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002379 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002380 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2381 }
2382
2383 public void testSetUserProvisioningState_permission() throws Exception {
2384 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002385
2386 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2387 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2388 }
2389
2390 public void testSetUserProvisioningState_unprivileged() throws Exception {
2391 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002392 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2393 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2394 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002395 }
2396
2397 public void testSetUserProvisioningState_noManagement() {
2398 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002399 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002400 assertExpectException(IllegalStateException.class,
2401 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2402 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2403 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002404 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2405 }
2406
2407 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2408 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2409 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002410
2411 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2412 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2413 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2414 }
2415
2416 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2417 throws Exception {
2418 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2419 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002420
2421 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2422 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2423 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2424 }
2425
2426 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2427 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2428 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002429
2430 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2431 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2432 }
2433
2434 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2435 throws Exception {
2436 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002437
2438 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2439 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2440 DevicePolicyManager.STATE_USER_UNMANAGED);
2441 }
2442
2443 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2444 throws Exception {
2445 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002446
2447 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2448 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2449 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2450 }
2451
2452 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2453 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002454
2455 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2456 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2457 }
2458
2459 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2460 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002461
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002462 assertExpectException(IllegalStateException.class,
2463 /* messageRegex= */ "Cannot move to user provisioning state",
2464 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2465 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2466 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002467 }
2468
2469 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2470 throws Exception {
2471 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002472
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002473 assertExpectException(IllegalStateException.class,
2474 /* messageRegex= */ "Cannot move to user provisioning state",
2475 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2476 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2477 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002478 }
2479
2480 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002481 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2482 mContext.callerPermissions.add(permission.MANAGE_USERS);
2483
Alan Treadwayafad8782016-01-19 15:15:08 +00002484 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2485 for (int state : states) {
2486 dpm.setUserProvisioningState(state, userId);
2487 assertEquals(state, dpm.getUserProvisioningState());
2488 }
2489 }
2490
2491 private void setupProfileOwner() throws Exception {
2492 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2493
2494 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2495 dpm.setActiveAdmin(admin1, false);
2496 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2497
2498 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2499 }
2500
2501 private void setupDeviceOwner() throws Exception {
2502 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2503
2504 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2505 dpm.setActiveAdmin(admin1, false);
2506 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2507
2508 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2509 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002510
2511 public void testSetMaximumTimeToLock() {
2512 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2513
2514 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2515 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2516
Pavel Grafov75c0a892017-05-18 17:28:27 +01002517 reset(getServices().powerManagerInternal);
2518 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002519
2520 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002521 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2522 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002523 reset(getServices().powerManagerInternal);
2524 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002525
2526 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002527 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2528 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002529 reset(getServices().powerManagerInternal);
2530 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002531
2532 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002533 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2534 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002535 reset(getServices().powerManagerInternal);
2536 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002537
2538 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002539 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2540 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002541 reset(getServices().powerManagerInternal);
2542 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002543
2544 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002545 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2546 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002547 reset(getServices().powerManagerInternal);
2548 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002549
2550 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002551 reset(getServices().powerManagerInternal);
2552 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002553
Pavel Grafov28939982017-10-03 15:11:52 +01002554 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2555 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2556 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002557 reset(getServices().powerManagerInternal);
2558 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002559
2560 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002561 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2562 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002563 reset(getServices().powerManagerInternal);
2564 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002565
Pavel Grafov28939982017-10-03 15:11:52 +01002566 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002567 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002568 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2569 verifyStayOnWhilePluggedCleared(false);
2570 }
2571
2572 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2573 // uses separate challenge.
2574 public void testSetMaximumTimeToLockProfile() throws Exception {
2575 final int PROFILE_USER = 15;
2576 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2577 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2578 mContext.binder.callingUid = PROFILE_ADMIN;
2579 final DevicePolicyManagerInternal dpmi =
2580 LocalServices.getService(DevicePolicyManagerInternal.class);
2581
2582 dpm.setMaximumTimeToLock(admin1, 0);
2583
2584 reset(getServices().powerManagerInternal);
2585 reset(getServices().settings);
2586
2587 // First add timeout for the profile.
2588 dpm.setMaximumTimeToLock(admin1, 10);
2589 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2590
2591 reset(getServices().powerManagerInternal);
2592 reset(getServices().settings);
2593
2594 // Add separate challenge
2595 when(getServices().lockPatternUtils
2596 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2597 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2598
2599 verifyScreenTimeoutCall(10L, PROFILE_USER);
2600 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2601
2602 reset(getServices().powerManagerInternal);
2603 reset(getServices().settings);
2604
2605 // Remove the timeout.
2606 dpm.setMaximumTimeToLock(admin1, 0);
2607 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2608 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2609
2610 reset(getServices().powerManagerInternal);
2611 reset(getServices().settings);
2612
2613 // Add it back.
2614 dpm.setMaximumTimeToLock(admin1, 10);
2615 verifyScreenTimeoutCall(10L, PROFILE_USER);
2616 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2617
2618 reset(getServices().powerManagerInternal);
2619 reset(getServices().settings);
2620
2621 // Remove separate challenge.
2622 reset(getServices().lockPatternUtils);
2623 when(getServices().lockPatternUtils
2624 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2625 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002626 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002627
2628 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2629 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2630
2631 reset(getServices().powerManagerInternal);
2632 reset(getServices().settings);
2633
2634 // Remove the timeout.
2635 dpm.setMaximumTimeToLock(admin1, 0);
2636 verifyScreenTimeoutCall(null, PROFILE_USER);
2637 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002638 }
2639
Michal Karpinski943aabd2016-10-06 11:09:25 +01002640 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2641 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2642 setupDeviceOwner();
2643 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2644
Michal Karpinskid084ca52017-01-18 15:54:18 +00002645 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2646 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2647 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2648 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2649 - ONE_MINUTE;
2650
2651 // verify that the minimum timeout cannot be modified on user builds (system property is
2652 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002653 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002654
2655 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2656 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2657 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2658
Pavel Grafov75c0a892017-05-18 17:28:27 +01002659 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002660
2661 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002662 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002663
Michal Karpinskid084ca52017-01-18 15:54:18 +00002664 // reset to default (0 means the admin is not participating, so default should be returned)
2665 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002666
2667 // aggregation should be the default if unset by any admin
2668 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2669 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2670
2671 // admin not participating by default
2672 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2673
2674 //clamping from the top
2675 dpm.setRequiredStrongAuthTimeout(admin1,
2676 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2677 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2678 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2679 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2680 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2681
Michal Karpinskid084ca52017-01-18 15:54:18 +00002682 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002683 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2684 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2685 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2686 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2687
2688 // clamping from the bottom
2689 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2690 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2691 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2692
Michal Karpinskid084ca52017-01-18 15:54:18 +00002693 // values within range
2694 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2695 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2696 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2697
2698 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2699 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2700 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002701
2702 // reset to default
2703 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2704 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2705 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2706 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2707
2708 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002709 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2710 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002711 }
2712
Pavel Grafov28939982017-10-03 15:11:52 +01002713 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002714 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002715 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002716 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002717 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002718 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002719 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002720 }
Pavel Grafov28939982017-10-03 15:11:52 +01002721 }
2722
2723 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002724 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2725 // UnfinishedVerificationException.
2726 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002727
Esteban Talavera01576862016-12-15 11:16:44 +00002728 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002729 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002730 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002731 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002732 .thenReturn(false);
2733 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002734 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2735 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002736 .thenReturn(true);
2737 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2738
2739 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002740 }
Victor Chang3e794af2016-03-04 13:48:17 +00002741
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002742 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2743 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002744 mContext.packageName = admin1.getPackageName();
2745 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002746 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2747 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2748 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2749 false);
2750 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2751 }
2752
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002753 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2754 setup_DeviceAdminFeatureOff();
2755 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2756 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2757 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2758 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2759 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2760 assertCheckProvisioningPreCondition(
2761 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2762 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2763 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2764 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2765 }
2766
Esteban Talavera01576862016-12-15 11:16:44 +00002767 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002768 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002769 .thenReturn(false);
2770 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002771 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2772 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002773 .thenReturn(true);
2774 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2775
2776 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002777 }
Victor Chang3e794af2016-03-04 13:48:17 +00002778
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002779 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2780 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002781 mContext.packageName = admin1.getPackageName();
2782 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2784 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2786 false);
2787 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2788
2789 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002790 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002791 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2792 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2793 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2794 true);
2795 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2796 }
2797
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002798 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2799 setup_ManagedProfileFeatureOff();
2800 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2801 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2802 DevicePolicyManager.CODE_OK);
2803 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2804 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2805 assertCheckProvisioningPreCondition(
2806 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2807 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2808 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2809 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2810
2811 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002812 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002813 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2814 DevicePolicyManager.CODE_OK);
2815 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2816 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2817 assertCheckProvisioningPreCondition(
2818 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2819 DevicePolicyManager.CODE_OK);
2820 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2821 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2822 }
2823
Esteban Talavera01576862016-12-15 11:16:44 +00002824 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002825 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002826 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002827 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2828 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002829 .thenReturn(true);
2830 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2831
2832 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002833 }
Victor Chang3e794af2016-03-04 13:48:17 +00002834
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002835 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2836 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002837 mContext.packageName = admin1.getPackageName();
2838 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002839 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2840 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2841 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2842 false /* because of non-split user */);
2843 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2844 false /* because of non-split user */);
2845 }
2846
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002847 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002848 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002849 setup_nonSplitUser_firstBoot_primaryUser();
2850 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2851 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2852 DevicePolicyManager.CODE_OK);
2853 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2854 DevicePolicyManager.CODE_OK);
2855 assertCheckProvisioningPreCondition(
2856 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2857 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2858 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2859 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2860 }
2861
Esteban Talavera01576862016-12-15 11:16:44 +00002862 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002863 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002864 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002865 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2866 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002867 .thenReturn(true);
2868 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2869
2870 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002871 }
Victor Chang3e794af2016-03-04 13:48:17 +00002872
Nicolas Prevot45d29072017-01-18 16:11:19 +00002873 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2874 setDeviceOwner();
2875 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2876 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2877 }
2878
2879 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2880 setup_nonSplitUser_withDo_primaryUser();
2881 final int MANAGED_PROFILE_USER_ID = 18;
2882 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2883 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002884 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002885 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002886 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002887 true)).thenReturn(true);
2888 }
2889
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002890 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2891 throws Exception {
2892 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002893 mContext.packageName = admin1.getPackageName();
2894 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002895 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2896 false/* because of completed device setup */);
2897 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2898 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2899 false/* because of non-split user */);
2900 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2901 false/* because of non-split user */);
2902 }
2903
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002904 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2905 throws Exception {
2906 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2907 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2908 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2909 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2910 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2911 DevicePolicyManager.CODE_OK);
2912 assertCheckProvisioningPreCondition(
2913 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2914 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2915 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2916 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2917 }
2918
Nicolas Prevot45d29072017-01-18 16:11:19 +00002919 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2920 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002921 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002922 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2923
2924 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2925 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002926 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002927
2928 // COMP mode is allowed.
2929 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2930 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002931 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002932
Nicolas Prevot45d29072017-01-18 16:11:19 +00002933 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002934 assertCheckProvisioningPreCondition(
2935 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002936 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002937 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002938 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2939 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2940 }
Esteban Talavera01576862016-12-15 11:16:44 +00002941
Nicolas Prevot45d29072017-01-18 16:11:19 +00002942 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2943 setup_nonSplitUser_withDo_primaryUser();
2944 mContext.packageName = admin1.getPackageName();
2945 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2946 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2947 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002948 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002949 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2950 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2951 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002952 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002953 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2954 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2955 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2956 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2957 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002958 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002959 assertCheckProvisioningPreCondition(
2960 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002961 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002962 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002963 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2964 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2965 }
Esteban Talavera01576862016-12-15 11:16:44 +00002966
Nicolas Prevot45d29072017-01-18 16:11:19 +00002967 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2968 throws Exception {
2969 setup_nonSplitUser_withDo_primaryUser();
2970 mContext.packageName = admin1.getPackageName();
2971 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002972 // The DO should not be allowed to initiate provisioning if the restriction is set by
2973 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002974 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002975 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2976 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2977 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002978 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002979 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2980 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2981 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2982 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2983 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002984 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2985
2986 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002987 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002988 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002989 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002990 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2991 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2992 }
2993
2994 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2995 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2996 mContext.packageName = admin1.getPackageName();
2997 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2998
2999 // We can delete the managed profile to create a new one, so provisioning is allowed.
3000 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3001 DevicePolicyManager.CODE_OK);
3002 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3003 assertCheckProvisioningPreCondition(
3004 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3005 DpmMockContext.ANOTHER_PACKAGE_NAME,
3006 DevicePolicyManager.CODE_OK);
3007 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3008 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3009 }
3010
3011 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3012 throws Exception {
3013 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3014 mContext.packageName = admin1.getPackageName();
3015 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003016 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003017 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3018 eq(UserHandle.SYSTEM)))
3019 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003020 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003021 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3022 eq(UserHandle.SYSTEM)))
3023 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003024
3025 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003026 assertCheckProvisioningPreCondition(
3027 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3028 DpmMockContext.ANOTHER_PACKAGE_NAME,
3029 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3030 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3031 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003032
3033 // But the device owner can still do it because it has set the restriction itself.
3034 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3035 DevicePolicyManager.CODE_OK);
3036 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003037 }
3038
3039 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003040 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003041 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003042 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3043 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003044 .thenReturn(false);
3045 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3046
3047 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003048 }
Victor Chang3e794af2016-03-04 13:48:17 +00003049
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003050 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3051 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003052 mContext.packageName = admin1.getPackageName();
3053 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003054 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3055 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3056 false /* because canAddMoreManagedProfiles returns false */);
3057 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3058 true);
3059 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3060 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003061 }
3062
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003063 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3064 throws Exception {
3065 setup_splitUser_firstBoot_systemUser();
3066 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3067 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3068 DevicePolicyManager.CODE_OK);
3069 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003070 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003071 assertCheckProvisioningPreCondition(
3072 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3073 DevicePolicyManager.CODE_OK);
3074 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3075 DevicePolicyManager.CODE_SYSTEM_USER);
3076 }
3077
Esteban Talavera01576862016-12-15 11:16:44 +00003078 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003079 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003080 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003081 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3082 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003083 .thenReturn(false);
3084 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3085
3086 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003087 }
Victor Chang3e794af2016-03-04 13:48:17 +00003088
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003089 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3090 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003091 mContext.packageName = admin1.getPackageName();
3092 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003093 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3094 true/* it's undefined behavior. Can be changed into false in the future */);
3095 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3096 false /* because canAddMoreManagedProfiles returns false */);
3097 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3098 true/* it's undefined behavior. Can be changed into false in the future */);
3099 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3100 false/* because calling uid is system user */);
3101 }
3102
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003103 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3104 throws Exception {
3105 setup_splitUser_afterDeviceSetup_systemUser();
3106 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3107 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3108 DevicePolicyManager.CODE_OK);
3109 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003110 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003111 assertCheckProvisioningPreCondition(
3112 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3113 DevicePolicyManager.CODE_OK);
3114 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3115 DevicePolicyManager.CODE_SYSTEM_USER);
3116 }
3117
Esteban Talavera01576862016-12-15 11:16:44 +00003118 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003119 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003120 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003121 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3122 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003123 true)).thenReturn(true);
3124 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3125
3126 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003127 }
Victor Chang3e794af2016-03-04 13:48:17 +00003128
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003129 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3130 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003131 mContext.packageName = admin1.getPackageName();
3132 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003133 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3134 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3135 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3136 true);
3137 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003138 }
3139
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003140 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003141 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003142 setup_splitUser_firstBoot_primaryUser();
3143 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3144 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3145 DevicePolicyManager.CODE_OK);
3146 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3147 DevicePolicyManager.CODE_OK);
3148 assertCheckProvisioningPreCondition(
3149 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3150 DevicePolicyManager.CODE_OK);
3151 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3152 DevicePolicyManager.CODE_OK);
3153 }
3154
Esteban Talavera01576862016-12-15 11:16:44 +00003155 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003156 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003157 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003158 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3159 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003160 true)).thenReturn(true);
3161 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3162
3163 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003164 }
Victor Chang3e794af2016-03-04 13:48:17 +00003165
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003166 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3167 throws Exception {
3168 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003169 mContext.packageName = admin1.getPackageName();
3170 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003171 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3172 true/* it's undefined behavior. Can be changed into false in the future */);
3173 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3174 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3175 true/* it's undefined behavior. Can be changed into false in the future */);
3176 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3177 false/* because user setup completed */);
3178 }
3179
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003180 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003181 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003182 setup_splitUser_afterDeviceSetup_primaryUser();
3183 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3184 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3185 DevicePolicyManager.CODE_OK);
3186 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3187 DevicePolicyManager.CODE_OK);
3188 assertCheckProvisioningPreCondition(
3189 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3190 DevicePolicyManager.CODE_OK);
3191 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3192 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3193 }
3194
Esteban Talavera01576862016-12-15 11:16:44 +00003195 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003196 setDeviceOwner();
3197
Pavel Grafov75c0a892017-05-18 17:28:27 +01003198 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003199 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003200 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3201 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003202 .thenReturn(false);
3203 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3204
3205 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003206 }
Victor Chang3e794af2016-03-04 13:48:17 +00003207
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003208 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3209 throws Exception {
3210 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003211 mContext.packageName = admin1.getPackageName();
3212 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003213 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3214 false /* can't provision managed profile on system user */);
3215 }
3216
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003217 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003218 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003219 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3220 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3221 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3222 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3223 }
3224
3225 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003226 setDeviceOwner();
3227
Pavel Grafov75c0a892017-05-18 17:28:27 +01003228 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003229 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003230 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3231 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003232 true)).thenReturn(true);
3233 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3234
3235 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003236 }
Victor Chang3e794af2016-03-04 13:48:17 +00003237
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003238 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3239 throws Exception {
3240 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003241 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3242 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003243 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3244 }
3245
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003246 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003247 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003248 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3249 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003250
3251 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003252 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3253 DevicePolicyManager.CODE_OK);
3254 }
3255
3256 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003257 setDeviceOwner();
3258
Pavel Grafov75c0a892017-05-18 17:28:27 +01003259 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003260 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003261 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3262 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003263 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3264 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003265 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003266 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003267 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003268 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003269 true)).thenReturn(true);
3270 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3271
3272 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003273 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003274
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003275 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3276 throws Exception {
3277 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003278 mContext.packageName = admin1.getPackageName();
3279 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003280 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3281 }
3282
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003283 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3284 throws Exception {
3285 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3286 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3287 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3288 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3289 }
3290
3291 public void testCheckProvisioningPreCondition_permission() {
3292 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003293 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3294 () -> dpm.checkProvisioningPreCondition(
3295 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003296 }
3297
Victor Chang3577ed22016-08-25 18:49:26 +01003298 public void testForceUpdateUserSetupComplete_permission() {
3299 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003300 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3301 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003302 }
3303
3304 public void testForceUpdateUserSetupComplete_systemUser() {
3305 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3306 // GIVEN calling from user 20
3307 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003308 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3309 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003310 }
3311
3312 public void testForceUpdateUserSetupComplete_userbuild() {
3313 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3314 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3315
3316 final int userId = UserHandle.USER_SYSTEM;
3317 // GIVEN userComplete is false in SettingsProvider
3318 setUserSetupCompleteForUser(false, userId);
3319
3320 // GIVEN userComplete is true in DPM
3321 DevicePolicyManagerService.DevicePolicyData userData =
3322 new DevicePolicyManagerService.DevicePolicyData(userId);
3323 userData.mUserSetupComplete = true;
3324 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3325
3326 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003327 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003328
3329 assertTrue(dpms.hasUserSetupCompleted());
3330
3331 dpm.forceUpdateUserSetupComplete();
3332
3333 // THEN the state in dpms is not changed
3334 assertTrue(dpms.hasUserSetupCompleted());
3335 }
3336
3337 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3338 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3339 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3340
3341 final int userId = UserHandle.USER_SYSTEM;
3342 // GIVEN userComplete is false in SettingsProvider
3343 setUserSetupCompleteForUser(false, userId);
3344
3345 // GIVEN userComplete is true in DPM
3346 DevicePolicyManagerService.DevicePolicyData userData =
3347 new DevicePolicyManagerService.DevicePolicyData(userId);
3348 userData.mUserSetupComplete = true;
3349 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3350
3351 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003352 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003353
3354 assertTrue(dpms.hasUserSetupCompleted());
3355
3356 dpm.forceUpdateUserSetupComplete();
3357
3358 // THEN the state in dpms is not changed
3359 assertFalse(dpms.hasUserSetupCompleted());
3360 }
3361
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003362 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003363 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003364 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003365
3366 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3367 runAsCaller(mAdmin1Context, dpms, dpm -> {
3368 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3369 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003370 }
3371
3372 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3373 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3374 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003375
3376 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3377 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003378 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003379 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3380 .thenReturn(true);
3381
3382 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003383 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003384
3385 // Enabling logging should not change the timestamp.
3386 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003387 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003388 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003389 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003390 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003391 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003392
3393 // Retrieving the logs should update the timestamp.
3394 final long beforeRetrieval = System.currentTimeMillis();
3395 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003396 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003397 final long afterRetrieval = System.currentTimeMillis();
3398 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3399 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3400
3401 // Retrieving the pre-boot logs should update the timestamp.
3402 Thread.sleep(2);
3403 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003404 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003405 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3406
3407 // Checking the timestamp again should not change it.
3408 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003409 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003410
3411 // Retrieving the logs again should update the timestamp.
3412 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003413 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003414 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3415
3416 // Disabling logging should not change the timestamp.
3417 Thread.sleep(2);
3418 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003419 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003420
3421 // Restarting the DPMS should not lose the timestamp.
3422 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003423 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003424
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003425 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3426 mContext.binder.callingUid = 1234567;
3427 mContext.callerPermissions.add(permission.MANAGE_USERS);
3428 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3429 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3430
3431 // System can retrieve the timestamp.
3432 mContext.binder.clearCallingIdentity();
3433 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3434
3435 // Removing the device owner should clear the timestamp.
3436 clearDeviceOwner();
3437 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003438 }
3439
yuemingw0de748d2017-11-15 19:22:27 +00003440 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3441 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3442 setupDeviceOwner();
3443 assertExpectException(SecurityException.class, null, () ->
3444 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3445 }
3446
yuemingwc0281f12018-03-28 15:58:49 +01003447 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003448 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3449 setupDeviceOwner();
3450 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003451 verify(getServices().settings).settingsSystemPutStringForUser(
3452 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3453 }
3454
3455 public void testSetSystemSettingWithPO() throws Exception {
3456 setupProfileOwner();
3457 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3458 verify(getServices().settings).settingsSystemPutStringForUser(
3459 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003460 }
3461
yuemingwe43cdf72017-10-12 16:52:11 +01003462 public void testSetTime() throws Exception {
3463 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3464 setupDeviceOwner();
3465 dpm.setTime(admin1, 0);
3466 verify(getServices().alarmManager).setTime(0);
3467 }
3468
3469 public void testSetTimeFailWithPO() throws Exception {
3470 setupProfileOwner();
3471 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3472 }
3473
3474 public void testSetTimeWithAutoTimeOn() throws Exception {
3475 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3476 setupDeviceOwner();
3477 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3478 .thenReturn(1);
3479 assertFalse(dpm.setTime(admin1, 0));
3480 }
3481
3482 public void testSetTimeZone() throws Exception {
3483 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3484 setupDeviceOwner();
3485 dpm.setTimeZone(admin1, "Asia/Shanghai");
3486 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3487 }
3488
3489 public void testSetTimeZoneFailWithPO() throws Exception {
3490 setupProfileOwner();
3491 assertExpectException(SecurityException.class, null,
3492 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3493 }
3494
3495 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3496 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3497 setupDeviceOwner();
3498 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3499 .thenReturn(1);
3500 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3501 }
3502
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003503 public void testGetLastBugReportRequestTime() throws Exception {
3504 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3505 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003506
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003507 mContext.packageName = admin1.getPackageName();
3508 mContext.applicationInfo = new ApplicationInfo();
3509 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3510 .thenReturn(Color.WHITE);
3511 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3512 anyObject())).thenReturn(Color.WHITE);
3513
Esteban Talaverad36dd152016-12-15 08:51:45 +00003514 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3515 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003516 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003517
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003518 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003519 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003520
3521 // Requesting a bug report should update the timestamp.
3522 final long beforeRequest = System.currentTimeMillis();
3523 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003524 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003525 final long afterRequest = System.currentTimeMillis();
3526 assertTrue(bugReportRequestTime >= beforeRequest);
3527 assertTrue(bugReportRequestTime <= afterRequest);
3528
3529 // Checking the timestamp again should not change it.
3530 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003531 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003532
3533 // Restarting the DPMS should not lose the timestamp.
3534 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003535 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003536
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003537 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3538 mContext.binder.callingUid = 1234567;
3539 mContext.callerPermissions.add(permission.MANAGE_USERS);
3540 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3541 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3542
3543 // System can retrieve the timestamp.
3544 mContext.binder.clearCallingIdentity();
3545 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3546
3547 // Removing the device owner should clear the timestamp.
3548 clearDeviceOwner();
3549 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003550 }
3551
3552 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3553 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3554 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003555 mContext.packageName = admin1.getPackageName();
3556 mContext.applicationInfo = new ApplicationInfo();
3557 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3558 .thenReturn(Color.WHITE);
3559 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3560 anyObject())).thenReturn(Color.WHITE);
3561
3562 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3563 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003564 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003565 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003566 .thenReturn(true);
3567
3568 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003569 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003570
3571 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3572 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003573 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003574
3575 // Enabling logging should not change the timestamp.
3576 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003577 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003578
3579 // Retrieving the logs should update the timestamp.
3580 final long beforeRetrieval = System.currentTimeMillis();
3581 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003582 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003583 final long afterRetrieval = System.currentTimeMillis();
3584 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3585 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3586
3587 // Checking the timestamp again should not change it.
3588 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003589 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003590
3591 // Retrieving the logs again should update the timestamp.
3592 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003593 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003594 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3595
3596 // Disabling logging should not change the timestamp.
3597 Thread.sleep(2);
3598 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003599 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003600
3601 // Restarting the DPMS should not lose the timestamp.
3602 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003603 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3604
3605 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3606 mContext.binder.callingUid = 1234567;
3607 mContext.callerPermissions.add(permission.MANAGE_USERS);
3608 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3609 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3610
3611 // System can retrieve the timestamp.
3612 mContext.binder.clearCallingIdentity();
3613 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3614
3615 // Removing the device owner should clear the timestamp.
3616 clearDeviceOwner();
3617 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003618 }
3619
Tony Mak2f26b792016-11-28 17:54:51 +00003620 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3621 // Setup device owner.
3622 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3623 setupDeviceOwner();
3624
3625 // Only device owner is setup, the result list should be empty.
3626 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3627 MoreAsserts.assertEmpty(targetUsers);
3628
3629 // Setup a managed profile managed by the same admin.
3630 final int MANAGED_PROFILE_USER_ID = 15;
3631 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3632 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3633
3634 // Add a secondary user, it should never talk with.
3635 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003636 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003637
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003638 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3639 // other.
3640 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3641 MoreAsserts.assertEmpty(targetUsers);
3642
3643 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3644 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3645 MoreAsserts.assertEmpty(targetUsers);
3646
3647 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003648 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003649 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3650 dpm.setAffiliationIds(admin1, userAffiliationIds);
3651
3652 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3653 dpm.setAffiliationIds(admin1, userAffiliationIds);
3654
Tony Mak2f26b792016-11-28 17:54:51 +00003655 // Calling from device owner admin, the result list should just contain the managed
3656 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003657 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003658 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3659 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3660
3661 // Calling from managed profile admin, the result list should just contain the system
3662 // user id.
3663 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3664 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3665 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003666
3667 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003668 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003669
3670 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3671 // to each other.
3672 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3673 MoreAsserts.assertEmpty(targetUsers);
3674
3675 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3676 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3677 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003678 }
3679
3680 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3681 // Setup a device owner.
3682 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3683 setupDeviceOwner();
3684
3685 // Set up a managed profile managed by different package.
3686 final int MANAGED_PROFILE_USER_ID = 15;
3687 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3688 final ComponentName adminDifferentPackage =
3689 new ComponentName("another.package", "whatever.class");
3690 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3691
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003692 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003693 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003694 dpm.setAffiliationIds(admin1, userAffiliationIds);
3695
3696 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3697 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3698
Tony Mak2f26b792016-11-28 17:54:51 +00003699 // Calling from device owner admin, we should get zero bind device admin target users as
3700 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003701 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003702 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3703 MoreAsserts.assertEmpty(targetUsers);
3704
3705 // Calling from managed profile admin, we should still get zero target users for the same
3706 // reason.
3707 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3708 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3709 MoreAsserts.assertEmpty(targetUsers);
3710 }
3711
Jason Parks3c13b642017-11-28 15:39:43 -06003712 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003713 verifyLockTaskState(userId, new String[0],
3714 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003715 }
3716
3717 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3718 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003719 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003720 }
3721
3722 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3723 int flags) throws Exception {
3724 mContext.binder.callingUid = uid;
3725 dpm.setLockTaskPackages(who, packages);
3726 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3727 for (String p : packages) {
3728 assertTrue(dpm.isLockTaskPermitted(p));
3729 }
3730 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3731 // Test to see if set lock task features can be set
3732 dpm.setLockTaskFeatures(who, flags);
3733 verifyLockTaskState(userId, packages, flags);
3734 }
3735
3736 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3737 int flags) throws Exception {
3738 mContext.binder.callingUid = uid;
3739 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3740 () -> dpm.setLockTaskPackages(who, packages));
3741 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3742 () -> dpm.getLockTaskPackages(who));
3743 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3744 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3745 () -> dpm.setLockTaskFeatures(who, flags));
3746 }
3747
Charles Hee078db72017-10-19 18:03:20 +01003748 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003749 // Setup a device owner.
3750 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3751 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003752 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003753 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003754
3755 // Set up a managed profile managed by different package (package name shouldn't matter)
3756 final int MANAGED_PROFILE_USER_ID = 15;
3757 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3758 final ComponentName adminDifferentPackage =
3759 new ComponentName("another.package", "whatever.class");
3760 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003761 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3762
3763 // Setup a PO on the secondary user
3764 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3765 setAsProfileOwner(admin3);
3766 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003767
3768 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003769 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003770 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003771 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3772 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003773 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3774
3775 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3776 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003777 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3778 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003779 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003780
3781 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3782 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3783 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003784 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003785 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3786 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003787 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003788
3789 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003790 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003791 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3792 dpm.setAffiliationIds(admin1, userAffiliationIds);
3793
3794 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3795 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3796
3797 // Now the managed profile can set lock task packages.
3798 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3799 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3800 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3801 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003802 // And it can set lock task features.
3803 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003804 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003805
3806 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003807 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003808 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3809 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003810 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3811 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003812 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003813 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003814
Jason Parks3c13b642017-11-28 15:39:43 -06003815 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003816 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3817 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003818
3819 }
3820
3821 public void testLockTaskPolicyForProfileOwner() throws Exception {
3822 // Setup a PO
3823 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3824 setAsProfileOwner(admin1);
3825 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3826
3827 final String[] poPackages = {"poPackage1", "poPackage2"};
3828 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003829 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3830 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003831 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3832 poPackages, poFlags);
3833
3834 // Set up a managed profile managed by different package (package name shouldn't matter)
3835 final int MANAGED_PROFILE_USER_ID = 15;
3836 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3837 final ComponentName adminDifferentPackage =
3838 new ComponentName("another.package", "whatever.class");
3839 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3840 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3841
3842 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3843 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3844 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3845 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003846 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3847 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003848 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003849 }
3850
Benjamin Franzcaffa772018-02-05 16:36:10 +00003851 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3852 // Setup a device owner.
3853 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3854 setupDeviceOwner();
3855 // Lock task policy is updated when loading user data.
3856 verifyLockTaskState(UserHandle.USER_SYSTEM);
3857
3858 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3859 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3860 assertExpectException(IllegalArgumentException.class,
3861 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3862 () -> dpm.setLockTaskFeatures(admin1, flags));
3863 }
3864
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003865 public void testIsDeviceManaged() throws Exception {
3866 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3867 setupDeviceOwner();
3868
3869 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3870 // find out that the device has a device owner.
3871 assertTrue(dpm.isDeviceManaged());
3872 mContext.binder.callingUid = 1234567;
3873 mContext.callerPermissions.add(permission.MANAGE_USERS);
3874 assertTrue(dpm.isDeviceManaged());
3875 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3876 mContext.binder.clearCallingIdentity();
3877 assertTrue(dpm.isDeviceManaged());
3878
3879 clearDeviceOwner();
3880
3881 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3882 // not have a device owner.
3883 mContext.binder.callingUid = 1234567;
3884 mContext.callerPermissions.add(permission.MANAGE_USERS);
3885 assertFalse(dpm.isDeviceManaged());
3886 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3887 mContext.binder.clearCallingIdentity();
3888 assertFalse(dpm.isDeviceManaged());
3889 }
3890
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003891 public void testDeviceOwnerOrganizationName() throws Exception {
3892 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3893 setupDeviceOwner();
3894
3895 dpm.setOrganizationName(admin1, "organization");
3896
3897 // Device owner can retrieve organization managing the device.
3898 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3899
3900 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3901 mContext.binder.callingUid = 1234567;
3902 mContext.callerPermissions.add(permission.MANAGE_USERS);
3903 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3904 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3905
3906 // System can retrieve organization managing the device.
3907 mContext.binder.clearCallingIdentity();
3908 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3909
3910 // Removing the device owner clears the organization managing the device.
3911 clearDeviceOwner();
3912 assertNull(dpm.getDeviceOwnerOrganizationName());
3913 }
3914
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003915 public void testWipeDataManagedProfile() throws Exception {
3916 final int MANAGED_PROFILE_USER_ID = 15;
3917 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3918 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3919 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3920
3921 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003922 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003923 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003924 // Get mock reason string since we throw an IAE with empty string input.
3925 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3926 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003927
3928 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003929 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003930 MANAGED_PROFILE_USER_ID);
3931 }
3932
3933 public void testWipeDataManagedProfileDisallowed() throws Exception {
3934 final int MANAGED_PROFILE_USER_ID = 15;
3935 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3936 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3937
3938 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003939 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003940 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3941
Pavel Grafov75c0a892017-05-18 17:28:27 +01003942 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003943 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3944 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3945 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003946 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3947 thenReturn("Just a test string.");
3948
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003949 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003950 // The PO is not allowed to remove the profile if the user restriction was set on the
3951 // profile by the system
3952 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3953 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003954 }
3955
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003956 public void testWipeDataDeviceOwner() throws Exception {
3957 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003958 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003959 UserManager.DISALLOW_FACTORY_RESET,
3960 UserHandle.SYSTEM))
3961 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003962 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3963 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003964
3965 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003966 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003967 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3968 /*wipeEuicc=*/ eq(false));
3969 }
3970
3971 public void testWipeEuiccDataEnabled() throws Exception {
3972 setDeviceOwner();
3973 when(getServices().userManager.getUserRestrictionSource(
3974 UserManager.DISALLOW_FACTORY_RESET,
3975 UserHandle.SYSTEM))
3976 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003977 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3978 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003979
3980 dpm.wipeData(WIPE_EUICC);
3981 verify(getServices().recoverySystem).rebootWipeUserData(
3982 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3983 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003984 }
3985
3986 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3987 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003988 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003989 UserManager.DISALLOW_FACTORY_RESET,
3990 UserHandle.SYSTEM))
3991 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003992 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3993 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003994 // The DO is not allowed to wipe the device if the user restriction was set
3995 // by the system
3996 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3997 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003998 }
3999
4000 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4001 final int MANAGED_PROFILE_USER_ID = 15;
4002 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4003 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4004
4005 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004006 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004007 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4008
Pavel Grafov75c0a892017-05-18 17:28:27 +01004009 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004010 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4011 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4012 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4013
4014 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4015 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4016
4017 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4018 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4019 // Failed password attempts on the parent user are taken into account, as there isn't a
4020 // separate work challenge.
4021 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4022 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4023 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4024
4025 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4026 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004027 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004028 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004029 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004030 }
4031
4032 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4033 throws Exception {
4034 final int MANAGED_PROFILE_USER_ID = 15;
4035 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4036 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4037
4038 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004039 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004040 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4041
Pavel Grafov75c0a892017-05-18 17:28:27 +01004042 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004043 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4044 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4045 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4046
4047 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4048 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4049
4050 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4051 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4052 // Failed password attempts on the parent user are taken into account, as there isn't a
4053 // separate work challenge.
4054 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4055 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4056 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4057
4058 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4059 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004060 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004061 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004062 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004063 }
4064
4065 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4066 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004067 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004068 UserManager.DISALLOW_FACTORY_RESET,
4069 UserHandle.SYSTEM))
4070 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4071
4072 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4073
4074 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4075 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4076 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4077 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4078 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4079
4080 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4081 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004082 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004083 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4084 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004085 }
4086
4087 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4088 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004089 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004090 UserManager.DISALLOW_FACTORY_RESET,
4091 UserHandle.SYSTEM))
4092 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4093
4094 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4095
4096 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4097 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4098 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4099 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4100 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4101
4102 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004103 verifyZeroInteractions(getServices().recoverySystem);
4104 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004105 .removeUserEvenWhenDisallowed(anyInt());
4106 }
4107
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004108 public void testGetPermissionGrantState() throws Exception {
4109 final String permission = "some.permission";
4110 final String app1 = "com.example.app1";
4111 final String app2 = "com.example.app2";
4112
Pavel Grafov75c0a892017-05-18 17:28:27 +01004113 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004114 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004115 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004116 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004117 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004118 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4119 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004120 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004121 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004122 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004123 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004124 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004125 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4126
4127 // System can retrieve permission grant state.
4128 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004129 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004130 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4131 dpm.getPermissionGrantState(null, app1, permission));
4132 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4133 dpm.getPermissionGrantState(null, app2, permission));
4134
4135 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004136 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4137 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004138 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4139 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004140
4141 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004142 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4143 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004144 setAsProfileOwner(admin1);
4145 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4146 dpm.getPermissionGrantState(admin1, app1, permission));
4147 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4148 dpm.getPermissionGrantState(admin1, app2, permission));
4149 }
4150
Rubin Xuaab7a412016-12-30 21:13:29 +00004151 public void testResetPasswordWithToken() throws Exception {
4152 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4153 setupDeviceOwner();
4154 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004155 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4156 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4157
Rubin Xuaab7a412016-12-30 21:13:29 +00004158 // test adding a token
4159 final byte[] token = new byte[32];
4160 final long handle = 123456;
4161 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004162 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4163 nullable(EscrowTokenStateChangeCallback.class)))
4164 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004165 assertTrue(dpm.setResetPasswordToken(admin1, token));
4166
4167 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004168 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004169 .thenReturn(true);
4170 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4171
4172 // test reset password with token
Rich Canningsf64ec632019-02-21 12:40:36 -08004173 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password.getBytes()),
Rubin Xu7cf45092017-08-28 11:47:35 +01004174 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
Adrian Roosebf84c22018-12-06 17:50:41 +01004175 eq(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004176 eq(UserHandle.USER_SYSTEM)))
4177 .thenReturn(true);
4178 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4179
4180 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004181 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004182 .thenReturn(true);
4183 assertTrue(dpm.clearResetPasswordToken(admin1));
4184 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004185
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004186 public void testIsActivePasswordSufficient() throws Exception {
4187 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4188 mContext.packageName = admin1.getPackageName();
4189 setupDeviceOwner();
4190
4191 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4192 dpm.setPasswordMinimumLength(admin1, 8);
4193 dpm.setPasswordMinimumLetters(admin1, 6);
4194 dpm.setPasswordMinimumLowerCase(admin1, 3);
4195 dpm.setPasswordMinimumUpperCase(admin1, 1);
4196 dpm.setPasswordMinimumNonLetter(admin1, 1);
4197 dpm.setPasswordMinimumNumeric(admin1, 1);
4198 dpm.setPasswordMinimumSymbols(admin1, 0);
4199
Rubin Xucc391c22018-01-02 20:37:35 +00004200 reset(mContext.spiedContext);
4201
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004202 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4203 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4204 8, 2,
4205 6, 1,
4206 0, 1);
4207
4208 setActivePasswordState(passwordMetricsNoSymbols);
4209 assertTrue(dpm.isActivePasswordSufficient());
4210
4211 initializeDpms();
4212 reset(mContext.spiedContext);
4213 assertTrue(dpm.isActivePasswordSufficient());
4214
4215 // This call simulates the user entering the password for the first time after a reboot.
4216 // This causes password metrics to be reloaded into memory. Until this happens,
4217 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4218 // even if the DPC changes password requirements so that the password no longer meets the
4219 // requirements. This is a known limitation of the current implementation of
4220 // isActivePasswordSufficient() - see b/34218769.
4221 setActivePasswordState(passwordMetricsNoSymbols);
4222 assertTrue(dpm.isActivePasswordSufficient());
4223
4224 dpm.setPasswordMinimumSymbols(admin1, 1);
4225 // This assertion would fail if we had not called setActivePasswordState() again after
4226 // initializeDpms() - see previous comment.
4227 assertFalse(dpm.isActivePasswordSufficient());
4228
4229 initializeDpms();
4230 reset(mContext.spiedContext);
4231 assertFalse(dpm.isActivePasswordSufficient());
4232
4233 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4234 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4235 7, 2,
4236 5, 1,
4237 1, 2);
4238
4239 setActivePasswordState(passwordMetricsWithSymbols);
4240 assertTrue(dpm.isActivePasswordSufficient());
4241 }
4242
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004243 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4244 // If there is no lock screen, the password is considered empty no matter what, because
4245 // it provides no security.
4246 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4247
4248 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4249 mContext.packageName = admin1.getPackageName();
4250 setupDeviceOwner();
4251
4252 // If no password requirements are set, isActivePasswordSufficient should succeed.
4253 assertTrue(dpm.isActivePasswordSufficient());
4254
4255 // Now set some password quality requirements.
4256 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4257
4258 reset(mContext.spiedContext);
4259 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4260 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4261 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4262 8, 2,
4263 6, 1,
4264 0, 1);
4265 // This should be ignored, as there is no lock screen.
4266 dpm.setActivePasswordState(passwordMetricsNoSymbols, userHandle);
4267 dpm.reportPasswordChanged(userHandle);
4268
4269 // No broadcast should be sent.
4270 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4271 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4272 MockUtils.checkUserHandle(userHandle));
4273
4274 // The active (nonexistent) password doesn't comply with the requirements.
4275 assertFalse(dpm.isActivePasswordSufficient());
4276 }
4277
Pavel Grafov75c0a892017-05-18 17:28:27 +01004278 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4279 throws Exception {
4280 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004281 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004282
Pavel Grafov75c0a892017-05-18 17:28:27 +01004283 dpm.setActivePasswordState(passwordMetrics, userHandle);
4284 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004285
Rubin Xucc391c22018-01-02 20:37:35 +00004286 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4287 // reportPasswordChanged()
Eran Messeri9ecde422018-04-30 16:16:39 +01004288 // This broadcast should be sent 4 times:
4289 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4290 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
4291 // * Twice from calls to DevicePolicyManagerService.saveSettingsLocked
4292 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4293 // the password change is relevant to and another with the credential owner of said
4294 // userId.
4295 verify(mContext.spiedContext, times(4)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004296 MockUtils.checkIntentAction(
4297 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4298 MockUtils.checkUserHandle(userHandle));
4299
Pavel Grafov75c0a892017-05-18 17:28:27 +01004300 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4301 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004302 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004303
4304 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4305 MockUtils.checkIntent(intent),
4306 MockUtils.checkUserHandle(userHandle));
4307
4308 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4309 // let it finish with system uid, otherwise it will throw and crash.
4310 flushTasks();
4311
4312 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004313 }
4314
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004315 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4316 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4317 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4318 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4319 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4320 DpmMockContext.SYSTEM_UID);
4321 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4322 DpmMockContext.SYSTEM_UID);
4323
4324 // Set up a device owner.
4325 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004326 setupDeviceOwner();
4327
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004328 // First and second user set IMEs manually.
4329 mContext.binder.callingUid = firstUserSystemUid;
4330 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4331 mContext.binder.callingUid = secondUserSystemUid;
4332 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004333
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004334 // Device owner changes IME for first user.
4335 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004336 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004337 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004338 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004339 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004340 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004341 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004342 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4343 mContext.binder.callingUid = firstUserSystemUid;
4344 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4345 mContext.binder.callingUid = secondUserSystemUid;
4346 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004347
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004348 // Second user changes IME manually.
4349 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4350 mContext.binder.callingUid = firstUserSystemUid;
4351 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4352 mContext.binder.callingUid = secondUserSystemUid;
4353 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004354
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004355 // First user changes IME manually.
4356 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4357 mContext.binder.callingUid = firstUserSystemUid;
4358 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4359 mContext.binder.callingUid = secondUserSystemUid;
4360 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004361
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004362 // Device owner changes IME for first user again.
4363 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004364 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004365 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004366 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004367 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004368 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004369 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4370 mContext.binder.callingUid = firstUserSystemUid;
4371 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4372 mContext.binder.callingUid = secondUserSystemUid;
4373 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004374
4375 // Restarting the DPMS should not lose information.
4376 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004377 mContext.binder.callingUid = firstUserSystemUid;
4378 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4379 mContext.binder.callingUid = secondUserSystemUid;
4380 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004381
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004382 // Device owner can find out whether it set the current IME itself.
4383 mContext.binder.callingUid = deviceOwnerUid;
4384 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004385
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004386 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004387 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004388 mContext.binder.callingUid = firstUserSystemUid;
4389 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4390 mContext.binder.callingUid = secondUserSystemUid;
4391 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004392 }
4393
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004394 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4395 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4396 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4397 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4398 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4399 DpmMockContext.SYSTEM_UID);
4400 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4401 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004402
4403 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004404 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004405 setupProfileOwner();
4406
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004407 // First and second user set IMEs manually.
4408 mContext.binder.callingUid = firstUserSystemUid;
4409 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4410 mContext.binder.callingUid = secondUserSystemUid;
4411 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004412
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004413 // Profile owner changes IME for second user.
4414 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004415 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004416 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004417 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004418 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004419 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004420 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004421 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4422 mContext.binder.callingUid = firstUserSystemUid;
4423 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4424 mContext.binder.callingUid = secondUserSystemUid;
4425 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004426
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004427 // First user changes IME manually.
4428 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4429 mContext.binder.callingUid = firstUserSystemUid;
4430 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4431 mContext.binder.callingUid = secondUserSystemUid;
4432 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004433
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004434 // Second user changes IME manually.
4435 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4436 mContext.binder.callingUid = firstUserSystemUid;
4437 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4438 mContext.binder.callingUid = secondUserSystemUid;
4439 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004440
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004441 // Profile owner changes IME for second user again.
4442 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004443 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004444 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004445 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004446 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004447 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004448 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4449 mContext.binder.callingUid = firstUserSystemUid;
4450 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4451 mContext.binder.callingUid = secondUserSystemUid;
4452 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004453
4454 // Restarting the DPMS should not lose information.
4455 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004456 mContext.binder.callingUid = firstUserSystemUid;
4457 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4458 mContext.binder.callingUid = secondUserSystemUid;
4459 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004460
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004461 // Profile owner can find out whether it set the current IME itself.
4462 mContext.binder.callingUid = profileOwnerUid;
4463 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004464
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004465 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004466 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004467 mContext.binder.callingUid = firstUserSystemUid;
4468 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4469 mContext.binder.callingUid = secondUserSystemUid;
4470 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004471 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004472
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004473 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4474 throws Exception {
4475 // Set up a device owner.
4476 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4477 setupDeviceOwner();
4478 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4479 }
4480
4481 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4482 throws Exception {
4483 // Set up a profile owner.
4484 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4485 setupProfileOwner();
4486 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4487 }
4488
4489 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4490 int adminUid) throws Exception {
4491 mContext.binder.callingUid = adminUid;
4492 final int userId = UserHandle.getUserId(adminUid);
4493
4494 final String packageName = "some.package";
4495 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4496 admin1, Collections.singletonList(packageName)));
4497 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4498
4499 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4500 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4501
4502 // Attempt to set to empty list (which means no listener is whitelisted)
4503 mContext.binder.callingUid = adminUid;
4504 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004505 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004506 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4507
4508 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4509 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4510 }
4511
4512 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4513 // Set up a managed profile
4514 final int MANAGED_PROFILE_USER_ID = 15;
4515 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4516 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4517 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4518
4519 final String permittedListener = "some.package";
4520 setupPackageInPackageManager(
4521 permittedListener,
4522 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4523 /*appId=*/ 12345, /*flags=*/ 0);
4524
4525 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4526 admin1, Collections.singletonList(permittedListener)));
4527
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004528 // isNotificationListenerServicePermitted should throw if not called from System.
4529 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4530 () -> dpms.isNotificationListenerServicePermitted(
4531 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004532
4533 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4534 assertTrue(dpms.isNotificationListenerServicePermitted(
4535 permittedListener, MANAGED_PROFILE_USER_ID));
4536 }
4537
4538 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4539 throws Exception {
4540 // Set up a managed profile
4541 final int MANAGED_PROFILE_USER_ID = 15;
4542 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4543 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4544 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4545
4546 final String permittedListener = "permitted.package";
4547 int appId = 12345;
4548 setupPackageInPackageManager(
4549 permittedListener,
4550 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4551 appId, /*flags=*/ 0);
4552
4553 final String notPermittedListener = "not.permitted.package";
4554 setupPackageInPackageManager(
4555 notPermittedListener,
4556 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4557 ++appId, /*flags=*/ 0);
4558
4559 final String systemListener = "system.package";
4560 setupPackageInPackageManager(
4561 systemListener,
4562 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4563 ++appId, ApplicationInfo.FLAG_SYSTEM);
4564
4565 // By default all packages are allowed
4566 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4567
4568 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4569 assertTrue(dpms.isNotificationListenerServicePermitted(
4570 permittedListener, MANAGED_PROFILE_USER_ID));
4571 assertTrue(dpms.isNotificationListenerServicePermitted(
4572 notPermittedListener, MANAGED_PROFILE_USER_ID));
4573 assertTrue(dpms.isNotificationListenerServicePermitted(
4574 systemListener, MANAGED_PROFILE_USER_ID));
4575
4576 // Setting only one package in the whitelist
4577 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4578 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4579 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004580 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004581 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4582 assertEquals(1, permittedListeners.size());
4583 assertEquals(permittedListener, permittedListeners.get(0));
4584
4585 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4586 assertTrue(dpms.isNotificationListenerServicePermitted(
4587 permittedListener, MANAGED_PROFILE_USER_ID));
4588 assertFalse(dpms.isNotificationListenerServicePermitted(
4589 notPermittedListener, MANAGED_PROFILE_USER_ID));
4590 // System packages are always allowed (even if not in the whitelist)
4591 assertTrue(dpms.isNotificationListenerServicePermitted(
4592 systemListener, MANAGED_PROFILE_USER_ID));
4593
4594 // Setting an empty whitelist - only system listeners allowed
4595 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4596 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004597 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004598 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4599
4600 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4601 assertFalse(dpms.isNotificationListenerServicePermitted(
4602 permittedListener, MANAGED_PROFILE_USER_ID));
4603 assertFalse(dpms.isNotificationListenerServicePermitted(
4604 notPermittedListener, MANAGED_PROFILE_USER_ID));
4605 // System packages are always allowed (even if not in the whitelist)
4606 assertTrue(dpms.isNotificationListenerServicePermitted(
4607 systemListener, MANAGED_PROFILE_USER_ID));
4608
4609 // Setting a null whitelist - all listeners allowed
4610 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4611 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4612 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4613
4614 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4615 assertTrue(dpms.isNotificationListenerServicePermitted(
4616 permittedListener, MANAGED_PROFILE_USER_ID));
4617 assertTrue(dpms.isNotificationListenerServicePermitted(
4618 notPermittedListener, MANAGED_PROFILE_USER_ID));
4619 assertTrue(dpms.isNotificationListenerServicePermitted(
4620 systemListener, MANAGED_PROFILE_USER_ID));
4621 }
4622
4623 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4624 throws Exception {
4625 // Set up a managed profile
4626 final int MANAGED_PROFILE_USER_ID = 15;
4627 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4628 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4629 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4630
4631 final String nonSystemPackage = "non.system.package";
4632 int appId = 12345;
4633 setupPackageInPackageManager(
4634 nonSystemPackage,
4635 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4636 appId, /*flags=*/ 0);
4637
4638 final String systemListener = "system.package";
4639 setupPackageInPackageManager(
4640 systemListener,
4641 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4642 ++appId, ApplicationInfo.FLAG_SYSTEM);
4643
4644 // By default all packages are allowed (for all profiles)
4645 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4646
4647 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4648 assertTrue(dpms.isNotificationListenerServicePermitted(
4649 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4650 assertTrue(dpms.isNotificationListenerServicePermitted(
4651 systemListener, MANAGED_PROFILE_USER_ID));
4652 assertTrue(dpms.isNotificationListenerServicePermitted(
4653 nonSystemPackage, UserHandle.USER_SYSTEM));
4654 assertTrue(dpms.isNotificationListenerServicePermitted(
4655 systemListener, UserHandle.USER_SYSTEM));
4656
4657 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4658 // all allowed in primary profile
4659 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4660 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004661 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004662 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4663
4664 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4665 assertFalse(dpms.isNotificationListenerServicePermitted(
4666 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4667 assertTrue(dpms.isNotificationListenerServicePermitted(
4668 systemListener, MANAGED_PROFILE_USER_ID));
4669 assertTrue(dpms.isNotificationListenerServicePermitted(
4670 nonSystemPackage, UserHandle.USER_SYSTEM));
4671 assertTrue(dpms.isNotificationListenerServicePermitted(
4672 systemListener, UserHandle.USER_SYSTEM));
4673 }
4674
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004675 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004676 mServiceContext.packageName = mRealTestContext.getPackageName();
4677 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4678 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004679 setDeviceOwner();
4680
Pavel Grafov75c0a892017-05-18 17:28:27 +01004681 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004682 }
4683
4684 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004685 mServiceContext.packageName = mRealTestContext.getPackageName();
4686 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4687 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004688 setAsProfileOwner(admin1);
4689
Pavel Grafov75c0a892017-05-18 17:28:27 +01004690 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4691 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004692 }
4693
4694 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004695 mServiceContext.packageName = mRealTestContext.getPackageName();
4696 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4697 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004698 setAsProfileOwner(admin1);
4699
Pavel Grafov75c0a892017-05-18 17:28:27 +01004700 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4701 caller.packageName = "com.example.delegate";
4702 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4703 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004704
Pavel Grafov75c0a892017-05-18 17:28:27 +01004705 // Make caller a delegated cert installer.
4706 runAsCaller(mAdmin1Context, dpms,
4707 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004708
4709 verifyCanGetOwnerInstalledCaCerts(null, caller);
4710 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004711 }
4712
Rubin Xucc391c22018-01-02 20:37:35 +00004713 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004714 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4715 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004716 Bundle restriction = new Bundle();
4717 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4718
4719 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4720 RestrictionsListener listener = new RestrictionsListener(mContext);
4721 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4722 new Bundle());
4723 verifyDataSharingChangedBroadcast();
4724 }
4725
4726 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004727 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4728 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004729 Bundle restriction = new Bundle();
4730 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4731
4732 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4733 RestrictionsListener listener = new RestrictionsListener(mContext);
4734 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4735 restriction);
4736 verifyDataSharingChangedBroadcast();
4737 }
4738
4739 public void testDisallowSharingIntoProfileUnchanged() {
4740 RestrictionsListener listener = new RestrictionsListener(mContext);
4741 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4742 new Bundle());
4743 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4744 }
4745
4746 private void verifyDataSharingChangedBroadcast() {
4747 Intent expectedIntent = new Intent(
4748 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4749 expectedIntent.setPackage("com.android.managedprovisioning");
4750 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4751 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4752 MockUtils.checkIntent(expectedIntent),
4753 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4754 }
4755
yuemingwe3d9c092018-01-11 12:11:44 +00004756 public void testOverrideApnAPIsFailWithPO() throws Exception {
4757 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004758 ApnSetting apn = (new ApnSetting.Builder())
4759 .setApnName("test")
4760 .setEntryName("test")
4761 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4762 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004763 assertExpectException(SecurityException.class, null, () ->
4764 dpm.addOverrideApn(admin1, apn));
4765 assertExpectException(SecurityException.class, null, () ->
4766 dpm.updateOverrideApn(admin1, 0, apn));
4767 assertExpectException(SecurityException.class, null, () ->
4768 dpm.removeOverrideApn(admin1, 0));
4769 assertExpectException(SecurityException.class, null, () ->
4770 dpm.getOverrideApns(admin1));
4771 assertExpectException(SecurityException.class, null, () ->
4772 dpm.setOverrideApnsEnabled(admin1, false));
4773 assertExpectException(SecurityException.class, null, () ->
4774 dpm.isOverrideApnEnabled(admin1));
4775 }
4776
Robin Lee2c68dad2017-03-17 12:50:24 +00004777 private void verifyCanGetOwnerInstalledCaCerts(
4778 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004779 final String alias = "cert";
4780 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004781
4782 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004783 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004784 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4785 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004786 }
4787 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4788
4789 // caller: device admin or delegated certificate installer
4790 callerContext.applicationInfo = new ApplicationInfo();
4791 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4792
4793 // system_server
4794 final DpmMockContext serviceContext = mContext;
4795 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004796 getServices().addPackageContext(callerUser, admin1Context);
4797 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004798
4799 // Install a CA cert.
4800 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004801 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004802 .thenReturn(alias);
4803 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004804 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004805 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004806 });
4807
Pavel Grafov75c0a892017-05-18 17:28:27 +01004808 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4809 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4810 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004811 flushTasks();
4812
Robin Lee2c68dad2017-03-17 12:50:24 +00004813 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4814
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004815 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004816 runAsCaller(admin1Context, dpms, (dpm) -> {
4817 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004818 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004819 ownerInstalledCaCerts.addAll(installedCaCerts);
4820 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004821
4822 // Restarting the DPMS should not lose information.
4823 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004824 runAsCaller(admin1Context, dpms, (dpm) ->
4825 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004826
4827 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004828 runAsCaller(serviceContext, dpms, (dpm) -> {
4829 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004830
Robin Lee2c68dad2017-03-17 12:50:24 +00004831 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004832 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004833 });
4834
Pavel Grafov75c0a892017-05-18 17:28:27 +01004835 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4836 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4837 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004838 flushTasks();
4839
4840 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4841 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004842 runAsCaller(admin1Context, dpms, (dpm) -> {
4843 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4844 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004845 }
4846
Robin Lee2c68dad2017-03-17 12:50:24 +00004847 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4848 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004849 final String alias = "cert";
4850 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004851
4852 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004853 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004854 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4855 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004856 }
4857 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4858
4859 // caller: device admin or delegated certificate installer
4860 callerContext.applicationInfo = new ApplicationInfo();
4861 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4862
4863 // system_server
4864 final DpmMockContext serviceContext = mContext;
4865 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004866 getServices().addPackageContext(callerUser, admin1Context);
4867 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004868
4869 // Install a CA cert as caller
4870 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004871 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004872 .thenReturn(alias);
4873 assertTrue(dpm.installCaCert(callerName, caCert));
4874 });
4875
4876 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004877 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004878 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004879 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4880 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4881 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004882 flushTasks();
4883
Robin Lee2c68dad2017-03-17 12:50:24 +00004884 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004885 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004886
4887 runAsCaller(serviceContext, dpms, (dpm) -> {
4888 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4889 assertNotNull(ownerInstalledCaCerts);
4890 assertTrue(ownerInstalledCaCerts.isEmpty());
4891 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004892 }
4893
Eran Messeri94d56762017-12-21 20:50:54 +00004894 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4895 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4896 Arrays.sort(gotFlags);
4897 Arrays.sort(expectedFlags);
4898 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4899 }
4900
4901 public void testTranslationOfIdAttestationFlag() {
4902 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4903 int[] correspondingAttUtilsTypes = new int[]{
4904 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4905 AttestationUtils.ID_TYPE_MEID};
4906
4907 // Test translation of zero flags
4908 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4909
4910 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4911 // non-null array
4912 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4913
4914 // Test translation of a single flag
4915 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4916 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4917 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4918
4919 // Test translation of two flags
4920 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4921 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4922 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4923 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4924
4925 // Test translation of all three flags
4926 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4927 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4928 AttestationUtils.ID_TYPE_MEID});
4929 // Test translation of all three flags
4930 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4931 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4932 AttestationUtils.ID_TYPE_MEID});
4933 }
4934
arangelov08d534b2018-01-22 15:20:53 +00004935 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4936 setDeviceOwner();
4937 initializeDpms();
4938 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4939 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4940 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4941 }
4942
4943 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4944 DpmTestUtils.writeInputStreamToFile(
4945 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4946 getDeviceOwnerPoliciesFile());
4947 DpmTestUtils.writeInputStreamToFile(
4948 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4949 getDeviceOwnerFile());
4950 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4951 }
4952
4953 public void testRevertDeviceOwnership_deviceNotMigrated()
4954 throws Exception {
4955 DpmTestUtils.writeInputStreamToFile(
4956 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4957 getDeviceOwnerPoliciesFile());
4958 DpmTestUtils.writeInputStreamToFile(
4959 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4960 getDeviceOwnerFile());
4961 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4962 }
4963
4964 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4965 throws Exception {
4966 DpmTestUtils.writeInputStreamToFile(
4967 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4968 getDeviceOwnerPoliciesFile());
4969 DpmTestUtils.writeInputStreamToFile(
4970 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4971 getDeviceOwnerFile());
4972 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4973 }
4974
4975 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4976 setupProfileOwner();
4977 initializeDpms();
4978 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4979 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4980 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4981 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4982 }
4983
4984 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4985 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4986 UserHandle.USER_SYSTEM);
4987 DpmTestUtils.writeInputStreamToFile(
4988 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4989 getProfileOwnerPoliciesFile());
4990 DpmTestUtils.writeInputStreamToFile(
4991 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
4992 getProfileOwnerFile());
4993 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4994 }
4995
4996 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
4997 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4998 UserHandle.USER_SYSTEM);
4999 DpmTestUtils.writeInputStreamToFile(
5000 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5001 getProfileOwnerPoliciesFile());
5002 DpmTestUtils.writeInputStreamToFile(
5003 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5004 getProfileOwnerFile());
5005 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5006 }
5007
5008 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5009 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5010 UserHandle.USER_SYSTEM);
5011 DpmTestUtils.writeInputStreamToFile(
5012 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5013 getProfileOwnerPoliciesFile());
5014 DpmTestUtils.writeInputStreamToFile(
5015 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5016 getProfileOwnerFile());
5017 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5018 }
5019
Eran Messeribb271892018-10-17 18:27:50 +01005020 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5021 setupProfileOwner();
5022 configureContextForAccess(mContext, false);
5023
5024 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005025 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005026 }
5027
5028 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5029 setupProfileOwner();
5030 configureContextForAccess(mContext, false);
5031
5032 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005033 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005034 }
5035
5036 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5037 setupProfileOwner();
5038
5039 // This method will throw if the system context could not call
5040 // setProfileOwnerCanAccessDeviceIds successfully.
5041 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5042 }
5043
5044 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5045 when(context.spiedContext.checkCallingPermission(
5046 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5047 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5048 : PackageManager.PERMISSION_DENIED);
5049 }
5050
5051 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5052 setupProfileOwner();
5053
5054 final long ident = mServiceContext.binder.clearCallingIdentity();
5055 configureContextForAccess(mServiceContext, true);
5056
5057 mServiceContext.binder.callingUid =
5058 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5059 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5060 try {
5061 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005062 dpm.setProfileOwnerCanAccessDeviceIds(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005063 });
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 -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005315 dpm.setProfileOwnerCanAccessDeviceIds(who);
Eran Messeribb271892018-10-17 18:27:50 +01005316 });
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}