blob: 57ccadd288828e06516166fa0e5d5503eb24fc4e [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;
Benjamin Franz6d009032016-01-25 18:56:38 +000088import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010089import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070090import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070091
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010092import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000093import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000094import com.android.server.LocalServices;
95import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000096import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000097import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000098
Robin Lee7f5c91c2017-02-08 21:27:02 +000099import org.hamcrest.BaseMatcher;
100import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800101import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700102import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103
arangelov08d534b2018-01-22 15:20:53 +0000104import java.io.File;
105import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800106import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000107import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000108import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700109import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700110import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700111import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100112import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000113import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700114
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700116 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000117 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118 m FrameworksServicesTests &&
119 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000120 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700122 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700123
124 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000125 *
126 * , or:
127 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700128 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000129@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100130@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700131public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000132 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
133 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
134 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100135 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800136 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100137 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000138
Pavel Grafov75c0a892017-05-18 17:28:27 +0100139 // TODO replace all instances of this with explicit {@link #mServiceContext}.
140 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700141 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100142
143 private DpmMockContext mServiceContext;
144 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700145 public DevicePolicyManager dpm;
146 public DevicePolicyManagerServiceTestable dpms;
147
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100148 /*
149 * The CA cert below is the content of cacert.pem as generated by:
150 *
151 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
152 */
153 private static final String TEST_CA =
154 "-----BEGIN CERTIFICATE-----\n" +
155 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
156 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
157 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
158 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
159 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
160 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
161 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
162 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
163 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
164 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
165 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
166 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
167 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
168 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
169 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
170 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
171 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
172 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
173 "wQ==\n" +
174 "-----END CERTIFICATE-----\n";
175
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700176 @Override
177 protected void setUp() throws Exception {
178 super.setUp();
179
180 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100181 mServiceContext = mContext;
182 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
183 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700184 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100185 doReturn(Collections.singletonList(new ResolveInfo()))
186 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
187 any(Intent.class),
188 anyInt(),
189 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700190
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800191 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100192 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800193
Makoto Onukia52562c2015-10-01 16:12:31 -0700194 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700195
Sudheer Shanka101c3532018-01-08 16:28:42 -0800196 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800197 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700198 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
199 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
200 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800201 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700202
Pavel Grafov75c0a892017-05-18 17:28:27 +0100203 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
204 mAdmin1Context.packageName = admin1.getPackageName();
205 mAdmin1Context.applicationInfo = new ApplicationInfo();
206 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
207
Makoto Onukib643fb02015-09-22 15:03:44 -0700208 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100209
210 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700211 }
212
arangelov08d534b2018-01-22 15:20:53 +0000213 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
214 return dpms.mTransferOwnershipMetadataManager;
215 }
216
Robin Lee2c68dad2017-03-17 12:50:24 +0000217 @Override
218 protected void tearDown() throws Exception {
219 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000220 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000221 super.tearDown();
222 }
223
Makoto Onukia52562c2015-10-01 16:12:31 -0700224 private void initializeDpms() {
225 // Need clearCallingIdentity() to pass permission checks.
226 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100227 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700228
Pavel Grafov75c0a892017-05-18 17:28:27 +0100229 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
230 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
231 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700232
Pavel Grafov75c0a892017-05-18 17:28:27 +0100233 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700234
Pavel Grafov75c0a892017-05-18 17:28:27 +0100235 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700236 }
237
Makoto Onukib643fb02015-09-22 15:03:44 -0700238 private void setUpUserManager() {
239 // Emulate UserManager.set/getApplicationRestriction().
240 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
241
242 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000243 doAnswer((Answer<Void>) invocation -> {
244 String pkg = (String) invocation.getArguments()[0];
245 Bundle bundle = (Bundle) invocation.getArguments()[1];
246 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700247
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000248 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700249
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000250 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100251 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100252 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700253
254 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000255 doAnswer((Answer<Bundle>) invocation -> {
256 String pkg = (String) invocation.getArguments()[0];
257 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700258
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000259 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100260 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700261 anyString(), any(UserHandle.class));
262
Makoto Onukid932f762015-09-29 16:53:38 -0700263 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100264 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700265 }
266
267 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100268 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700269
Pavel Grafov75c0a892017-05-18 17:28:27 +0100270 mServiceContext.binder.callingUid =
271 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
272 runAsCaller(mServiceContext, dpms, dpm -> {
273 // PO needs to be a DA.
274 dpm.setActiveAdmin(admin, /*replace=*/ false);
275 // Fire!
276 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
277 // Check
278 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
279 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700280
Pavel Grafov75c0a892017-05-18 17:28:27 +0100281 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700282 }
283
284 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100285 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700286 .thenReturn(false);
287
288 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100289 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700290
291 // If the device has no DPMS feature, it shouldn't register the local service.
292 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
293 }
294
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800295 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800296 // Device owner in SYSTEM_USER
297 setDeviceOwner();
298 // Profile owner in CALLER_USER_HANDLE
299 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
300 setAsProfileOwner(admin2);
301 // Active admin in CALLER_USER_HANDLE
302 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
303 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
304 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
305 DpmMockContext.CALLER_USER_HANDLE);
306 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
307 DpmMockContext.CALLER_USER_HANDLE));
308
309 initializeDpms();
310
311 // Verify
312 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800313 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800314 eq(UserHandle.USER_SYSTEM));
315 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800316 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800317 adminAnotherPackage.getPackageName()),
318 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800319 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
320 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
321 }
322
323 public void testLoadAdminData_noAdmins() throws Exception {
324 final int ANOTHER_USER_ID = 15;
325 getServices().addUser(ANOTHER_USER_ID, 0);
326
327 initializeDpms();
328
329 // Verify
330 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
331 null, DpmMockContext.CALLER_USER_HANDLE);
332 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
333 null, ANOTHER_USER_ID);
334 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
335 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800336 }
337
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700338 /**
339 * Caller doesn't have proper permissions.
340 */
341 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700342 // 1. Failure cases.
343
344 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100345 assertExpectException(SecurityException.class, /* messageRegex= */ null,
346 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700347
348 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
349 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100350
351 assertExpectException(SecurityException.class, /* messageRegex= */ null,
352 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700353 }
354
Makoto Onukif76b06a2015-09-22 15:03:44 -0700355 /**
356 * Test for:
357 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800358 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700359 * {@link DevicePolicyManager#isAdminActive}
360 * {@link DevicePolicyManager#isAdminActiveAsUser}
361 * {@link DevicePolicyManager#getActiveAdmins}
362 * {@link DevicePolicyManager#getActiveAdminsAsUser}
363 */
364 public void testSetActiveAdmin() throws Exception {
365 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700366 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
367
Makoto Onukif76b06a2015-09-22 15:03:44 -0700368 // 2. Call the API.
369 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700370
371 // 3. Verify internal calls.
372
373 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700374 verify(mContext.spiedContext).sendBroadcastAsUser(
375 MockUtils.checkIntentAction(
376 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
377 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
378 verify(mContext.spiedContext).sendBroadcastAsUser(
379 MockUtils.checkIntentAction(
380 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700381 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
382
Pavel Grafov75c0a892017-05-18 17:28:27 +0100383 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700384 eq(admin1.getPackageName()),
385 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
386 eq(PackageManager.DONT_KILL_APP),
387 eq(DpmMockContext.CALLER_USER_HANDLE),
388 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700389
Sudheer Shanka101c3532018-01-08 16:28:42 -0800390 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
391 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
392
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700393 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700394
395 // Make sure it's active admin1.
396 assertTrue(dpm.isAdminActive(admin1));
397 assertFalse(dpm.isAdminActive(admin2));
398 assertFalse(dpm.isAdminActive(admin3));
399
400 // But not admin1 for a different user.
401
402 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
403 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
404 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
405
406 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
407 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
408
409 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
410
411 // Next, add one more admin.
412 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700413 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700414 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700415
416 dpm.setActiveAdmin(admin2, /* replace =*/ false);
417
418 // Now we have two admins.
419 assertTrue(dpm.isAdminActive(admin1));
420 assertTrue(dpm.isAdminActive(admin2));
421 assertFalse(dpm.isAdminActive(admin3));
422
423 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
424 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100425 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700426 eq(admin1.getPackageName()),
427 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
428 eq(PackageManager.DONT_KILL_APP),
429 eq(DpmMockContext.CALLER_USER_HANDLE),
430 anyString());
431
Sudheer Shanka101c3532018-01-08 16:28:42 -0800432 // times(2) because it was previously called for admin1 which is in the same package
433 // as admin2.
434 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
435 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
436
Makoto Onukif76b06a2015-09-22 15:03:44 -0700437 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100438 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
439 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700440
441 // 5. Add the same admin1 again with replace, which should succeed.
442 dpm.setActiveAdmin(admin1, /* replace =*/ true);
443
444 // TODO make sure it's replaced.
445
446 // 6. Test getActiveAdmins()
447 List<ComponentName> admins = dpm.getActiveAdmins();
448 assertEquals(2, admins.size());
449 assertEquals(admin1, admins.get(0));
450 assertEquals(admin2, admins.get(1));
451
Sudheer Shanka101c3532018-01-08 16:28:42 -0800452 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
453 // replaced
454 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
455
Makoto Onukif76b06a2015-09-22 15:03:44 -0700456 // Another user has no admins.
457 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
458
459 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
460 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
461
462 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
463 }
464
Makoto Onukid932f762015-09-29 16:53:38 -0700465 public void testSetActiveAdmin_multiUsers() throws Exception {
466
467 final int ANOTHER_USER_ID = 100;
468 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
469
Pavel Grafov75c0a892017-05-18 17:28:27 +0100470 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700471
472 // Set up pacakge manager for the other user.
473 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700474
475 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
476
477 dpm.setActiveAdmin(admin1, /* replace =*/ false);
478
479 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
480 dpm.setActiveAdmin(admin2, /* replace =*/ false);
481
482
483 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
484 assertTrue(dpm.isAdminActive(admin1));
485 assertFalse(dpm.isAdminActive(admin2));
486
487 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
488 assertFalse(dpm.isAdminActive(admin1));
489 assertTrue(dpm.isAdminActive(admin2));
490 }
491
Makoto Onukif76b06a2015-09-22 15:03:44 -0700492 /**
493 * Test for:
494 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800495 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700496 */
497 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
498 // 1. Make sure the caller has proper permissions.
499 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
500
501 dpm.setActiveAdmin(admin1, /* replace =*/ false);
502 assertTrue(dpm.isAdminActive(admin1));
503
504 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100505 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
506 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700507 }
508
509 /**
510 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800511 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
512 * BIND_DEVICE_ADMIN.
513 */
514 public void testSetActiveAdmin_permissionCheck() throws Exception {
515 // 1. Make sure the caller has proper permissions.
516 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
517
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100518 assertExpectException(IllegalArgumentException.class,
519 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
520 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800521 assertFalse(dpm.isAdminActive(adminNoPerm));
522
523 // Change the target API level to MNC. Now it can be set as DA.
524 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
525 VERSION_CODES.M);
526 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
527 assertTrue(dpm.isAdminActive(adminNoPerm));
528
529 // TODO Test the "load from the file" case where DA will still be loaded even without
530 // BIND_DEVICE_ADMIN and target API is N.
531 }
532
533 /**
534 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700535 * {@link DevicePolicyManager#removeActiveAdmin}
536 */
537 public void testRemoveActiveAdmin_SecurityException() {
538 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
539
540 // Add admin.
541
542 dpm.setActiveAdmin(admin1, /* replace =*/ false);
543
544 assertTrue(dpm.isAdminActive(admin1));
545
546 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
547
548 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100549 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
550 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700551
552 // Try to remove active admin with a different caller userid should fail too, without
553 // having MANAGE_DEVICE_ADMINS.
554 mContext.callerPermissions.clear();
555
Makoto Onukid932f762015-09-29 16:53:38 -0700556 // Change the caller, and call into DPMS directly with a different user-id.
557
Makoto Onukif76b06a2015-09-22 15:03:44 -0700558 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100559 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
560 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700561 }
562
563 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800564 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
565 * (because we can't send the remove broadcast).
566 */
567 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
568 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
569
570 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
571
572 // Add admin.
573
574 dpm.setActiveAdmin(admin1, /* replace =*/ false);
575
576 assertTrue(dpm.isAdminActive(admin1));
577
578 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
579
580 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100581 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800582 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100583 assertExpectException(IllegalStateException.class,
584 /* messageRegex= */ "User must be running and unlocked",
585 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800586
587 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800588 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
589 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800590
591 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100592 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800593 .thenReturn(true);
594
595 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700596 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800597 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
598 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800599 }
600
601 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700602 * Test for:
603 * {@link DevicePolicyManager#removeActiveAdmin}
604 */
Makoto Onukid932f762015-09-29 16:53:38 -0700605 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700606 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
607
608 // Add admin1.
609
610 dpm.setActiveAdmin(admin1, /* replace =*/ false);
611
612 assertTrue(dpm.isAdminActive(admin1));
613 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
614
615 // Different user, but should work, because caller has proper permissions.
616 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700617
618 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700619 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700620
621 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700622 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800623 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
624 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700625
626 // TODO DO Still can't be removed in this case.
627 }
628
629 /**
630 * Test for:
631 * {@link DevicePolicyManager#removeActiveAdmin}
632 */
633 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
634 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
635 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
636
637 // Add admin1.
638
639 dpm.setActiveAdmin(admin1, /* replace =*/ false);
640
641 assertTrue(dpm.isAdminActive(admin1));
642 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
643
644 // Broadcast from saveSettingsLocked().
645 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
646 MockUtils.checkIntentAction(
647 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
648 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
649
650 // Remove. No permissions, but same user, so it'll work.
651 mContext.callerPermissions.clear();
652 dpm.removeActiveAdmin(admin1);
653
Makoto Onukif76b06a2015-09-22 15:03:44 -0700654 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
655 MockUtils.checkIntentAction(
656 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
657 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
658 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700659 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700660 eq(dpms.mHandler),
661 eq(Activity.RESULT_OK),
662 isNull(String.class),
663 isNull(Bundle.class));
664
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700665 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800666 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
667 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700668
669 // Again broadcast from saveSettingsLocked().
670 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
671 MockUtils.checkIntentAction(
672 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
673 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
674
675 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700676 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700677
Sudheer Shanka101c3532018-01-08 16:28:42 -0800678 public void testRemoveActiveAdmin_multipleAdminsInUser() {
679 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
680 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
681
682 // Add admin1.
683 dpm.setActiveAdmin(admin1, /* replace =*/ false);
684
685 assertTrue(dpm.isAdminActive(admin1));
686 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
687
688 // Add admin2.
689 dpm.setActiveAdmin(admin2, /* replace =*/ false);
690
691 assertTrue(dpm.isAdminActive(admin2));
692 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
693
694 // Broadcast from saveSettingsLocked().
695 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
696 MockUtils.checkIntentAction(
697 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
698 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
699
700 // Remove. No permissions, but same user, so it'll work.
701 mContext.callerPermissions.clear();
702 dpm.removeActiveAdmin(admin1);
703
704 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
705 MockUtils.checkIntentAction(
706 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
707 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
708 isNull(String.class),
709 any(BroadcastReceiver.class),
710 eq(dpms.mHandler),
711 eq(Activity.RESULT_OK),
712 isNull(String.class),
713 isNull(Bundle.class));
714
715 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
716 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800717 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800718 eq(DpmMockContext.CALLER_USER_HANDLE));
719
720 // Again broadcast from saveSettingsLocked().
721 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
722 MockUtils.checkIntentAction(
723 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
724 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
725 }
726
727 /**
728 * Test for:
729 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
730 */
731 public void testForceRemoveActiveAdmin() throws Exception {
732 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
733
734 // Add admin.
735 setupPackageInPackageManager(admin1.getPackageName(),
736 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
737 /* appId= */ 10138,
738 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
739 dpm.setActiveAdmin(admin1, /* replace =*/ false);
740 assertTrue(dpm.isAdminActive(admin1));
741
742 // Calling from a non-shell uid should fail with a SecurityException
743 mContext.binder.callingUid = 123456;
744 assertExpectException(SecurityException.class,
745 /* messageRegex =*/ "Non-shell user attempted to call",
746 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
747
748 mContext.binder.callingUid = Process.SHELL_UID;
749 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
750
751 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
752 // Verify
753 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
754 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
755 null, DpmMockContext.CALLER_USER_HANDLE);
756 }
757
Makoto Onukib643fb02015-09-22 15:03:44 -0700758 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000759 * Test for: @{link DevicePolicyManager#setActivePasswordState}
760 *
761 * Validates that when the password for a user changes, the notification broadcast intent
762 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
763 * addition to ones in the original user.
764 */
765 public void testSetActivePasswordState_sendToProfiles() throws Exception {
766 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
767
768 final int MANAGED_PROFILE_USER_ID = 78;
769 final int MANAGED_PROFILE_ADMIN_UID =
770 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
771
772 // Setup device owner.
773 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
774 mContext.packageName = admin1.getPackageName();
775 setupDeviceOwner();
776
777 // Add a managed profile belonging to the system user.
778 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
779
780 // Change the parent user's password.
781 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
782
783 // Both the device owner and the managed profile owner should receive this broadcast.
784 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
785 intent.setComponent(admin1);
786 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
787
788 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
789 MockUtils.checkIntent(intent),
790 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
791 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
792 MockUtils.checkIntent(intent),
793 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
794 }
795
796 /**
797 * Test for: @{link DevicePolicyManager#setActivePasswordState}
798 *
799 * Validates that when the password for a managed profile changes, the notification broadcast
800 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
801 * its parent.
802 */
803 public void testSetActivePasswordState_notSentToParent() throws Exception {
804 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
805
806 final int MANAGED_PROFILE_USER_ID = 78;
807 final int MANAGED_PROFILE_ADMIN_UID =
808 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
809
810 // Setup device owner.
811 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
812 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100813 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000814 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
815 setupDeviceOwner();
816
817 // Add a managed profile belonging to the system user.
818 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
819
820 // Change the profile's password.
821 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
822
823 // Both the device owner and the managed profile owner should receive this broadcast.
824 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
825 intent.setComponent(admin1);
826 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
827
828 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
829 MockUtils.checkIntent(intent),
830 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
831 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
832 MockUtils.checkIntent(intent),
833 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
834 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100835
Robin Leed2a73ed2016-12-19 09:07:16 +0000836 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000837 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700838 */
839 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000840 setDeviceOwner();
841
842 // Try to set a profile owner on the same user, which should fail.
843 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
844 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100845 assertExpectException(IllegalStateException.class,
846 /* messageRegex= */ "already has a device owner",
847 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000848
849 // DO admin can't be deactivated.
850 dpm.removeActiveAdmin(admin1);
851 assertTrue(dpm.isAdminActive(admin1));
852
853 // TODO Test getDeviceOwnerName() too. To do so, we need to change
854 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
855 }
856
857 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700858 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800859 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700860 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
861 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
862
Makoto Onukid932f762015-09-29 16:53:38 -0700863 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
865
Makoto Onukid932f762015-09-29 16:53:38 -0700866 // Make sure admin1 is installed on system user.
867 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700868
Makoto Onukic8a5a552015-11-19 14:29:12 -0800869 // Check various get APIs.
870 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
871
Makoto Onukib643fb02015-09-22 15:03:44 -0700872 // DO needs to be an DA.
873 dpm.setActiveAdmin(admin1, /* replace =*/ false);
874
875 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700876 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700877
Makoto Onukic8a5a552015-11-19 14:29:12 -0800878 // getDeviceOwnerComponent should return the admin1 component.
879 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
880 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
881
882 // Check various get APIs.
883 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
884
885 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
886 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
887 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
888 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
889
890 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
891
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000892 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100893 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000894 eq(admin1.getPackageName()));
895
Makoto Onukib643fb02015-09-22 15:03:44 -0700896 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100897 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700898 eq(UserHandle.USER_SYSTEM), eq(false));
899
900 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
901 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
902 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
903
Makoto Onukic8a5a552015-11-19 14:29:12 -0800904 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700905 }
906
Makoto Onukic8a5a552015-11-19 14:29:12 -0800907 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
908 final int origCallingUser = mContext.binder.callingUid;
909 final List origPermissions = new ArrayList(mContext.callerPermissions);
910 mContext.callerPermissions.clear();
911
912 mContext.callerPermissions.add(permission.MANAGE_USERS);
913
914 mContext.binder.callingUid = Process.SYSTEM_UID;
915
916 // TODO Test getDeviceOwnerName() too. To do so, we need to change
917 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
918 if (hasDeviceOwner) {
919 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
920 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
921 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
922
923 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
924 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
925 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
926 } else {
927 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
928 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
929 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
930
931 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
932 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
933 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
934 }
935
936 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
937 if (hasDeviceOwner) {
938 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
939 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
940 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
941
942 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
943 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
944 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
945 } else {
946 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
947 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
948 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
949
950 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
951 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
952 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
953 }
954
955 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
956 // Still with MANAGE_USERS.
957 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
958 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
959 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
960
961 if (hasDeviceOwner) {
962 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
963 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
964 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
965 } else {
966 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
967 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
968 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
969 }
970
971 mContext.binder.callingUid = Process.SYSTEM_UID;
972 mContext.callerPermissions.remove(permission.MANAGE_USERS);
973 // System can still call "OnAnyUser" without MANAGE_USERS.
974 if (hasDeviceOwner) {
975 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
976 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
977 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
978
979 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
980 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
981 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
982 } else {
983 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
984 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
985 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
986
987 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
988 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
989 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
990 }
991
992 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
993 // Still no MANAGE_USERS.
994 if (hasDeviceOwner) {
995 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
996 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
997 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
998 } else {
999 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1000 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1001 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1002 }
1003
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001004 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1005 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1006 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1007 dpm::getDeviceOwnerComponentOnAnyUser);
1008 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1009 dpm::getDeviceOwnerUserId);
1010 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1011 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001012
1013 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1014 // Still no MANAGE_USERS.
1015 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1016 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1017 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1018
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001019 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1020 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1021 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1022 dpm::getDeviceOwnerComponentOnAnyUser);
1023 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1024 dpm::getDeviceOwnerUserId);
1025 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1026 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001027
1028 // Restore.
1029 mContext.binder.callingUid = origCallingUser;
1030 mContext.callerPermissions.addAll(origPermissions);
1031 }
1032
1033
Makoto Onukib643fb02015-09-22 15:03:44 -07001034 /**
1035 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1036 */
1037 public void testSetDeviceOwner_noSuchPackage() {
1038 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001039 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001040 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1041 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1042
1043 // Call from a process on the system user.
1044 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1045
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001046 assertExpectException(IllegalArgumentException.class,
1047 /* messageRegex= */ "Invalid component",
1048 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001049 }
1050
1051 public void testSetDeviceOwner_failures() throws Exception {
1052 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1053 }
1054
Makoto Onukia52562c2015-10-01 16:12:31 -07001055 public void testClearDeviceOwner() throws Exception {
1056 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001057 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001058 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1059 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1060
1061 // Set admin1 as a DA to the secondary user.
1062 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1063
1064 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1065
1066 // Set admin 1 as the DO to the system user.
1067
1068 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1069 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1070 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1071 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1072
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001073 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001074 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001075 eq(admin1.getPackageName()));
1076
Makoto Onukic8a5a552015-11-19 14:29:12 -08001077 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001078
Makoto Onuki90b89652016-01-28 14:44:18 -08001079 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001080 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001081 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001082
1083 assertTrue(dpm.isAdminActive(admin1));
1084 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1085
Makoto Onukia52562c2015-10-01 16:12:31 -07001086 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001087 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001088
1089 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001090 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1091 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001092
1093 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001094 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001095 assertExpectException(IllegalStateException.class,
1096 /* messageRegex= */ "User must be running and unlocked",
1097 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001098
Pavel Grafov75c0a892017-05-18 17:28:27 +01001099 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1100 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001101 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1102
1103 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001104 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001105
Pavel Grafov75c0a892017-05-18 17:28:27 +01001106 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001107 eq(false),
1108 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1109
Pavel Grafov75c0a892017-05-18 17:28:27 +01001110 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001111 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001112 eq(null),
1113 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001114
Sudheer Shanka101c3532018-01-08 16:28:42 -08001115 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1116 null, UserHandle.USER_SYSTEM);
1117
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001118 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001119
1120 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1121 // and once for clearing it.
1122 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1123 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1124 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001125 // TODO Check other calls.
1126 }
1127
1128 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1129 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001130 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001131 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1132 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1133
1134 // Set admin1 as a DA to the secondary user.
1135 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1136
1137 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1138
1139 // Set admin 1 as the DO to the system user.
1140
1141 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1142 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1143 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1144 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1145
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001146 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001147 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001148 eq(admin1.getPackageName()));
1149
Makoto Onukic8a5a552015-11-19 14:29:12 -08001150 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001151
1152 // Now call clear from the secondary user, which should throw.
1153 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1154
1155 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001156 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001157 eq(admin1.getPackageName()),
1158 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001159 assertExpectException(SecurityException.class,
1160 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1161 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001162
Makoto Onukic8a5a552015-11-19 14:29:12 -08001163 // DO shouldn't be removed.
1164 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001165 }
1166
Makoto Onukib643fb02015-09-22 15:03:44 -07001167 public void testSetProfileOwner() throws Exception {
1168 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001169
Makoto Onuki90b89652016-01-28 14:44:18 -08001170 // PO admin can't be deactivated.
1171 dpm.removeActiveAdmin(admin1);
1172 assertTrue(dpm.isAdminActive(admin1));
1173
Makoto Onuki803d6752015-10-30 12:58:39 -07001174 // Try setting DO on the same user, which should fail.
1175 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001176 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1177 runAsCaller(mServiceContext, dpms, dpm -> {
1178 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001179 assertExpectException(IllegalStateException.class,
1180 /* messageRegex= */ "already has a profile owner",
1181 () -> dpm.setDeviceOwner(admin2, "owner-name",
1182 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001183 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001184 }
1185
Makoto Onuki90b89652016-01-28 14:44:18 -08001186 public void testClearProfileOwner() throws Exception {
1187 setAsProfileOwner(admin1);
1188
1189 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1190
1191 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1192 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1193
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001194 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001195 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001196 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001197 assertExpectException(IllegalStateException.class,
1198 /* messageRegex= */ "User must be running and unlocked",
1199 () -> dpm.clearProfileOwner(admin1));
1200
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001201 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001202 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001203 dpm.clearProfileOwner(admin1);
1204
1205 // Check
1206 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001207 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001208 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1209 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001210 }
1211
Makoto Onukib643fb02015-09-22 15:03:44 -07001212 public void testSetProfileOwner_failures() throws Exception {
1213 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1214 }
1215
Makoto Onukia52562c2015-10-01 16:12:31 -07001216 public void testGetDeviceOwnerAdminLocked() throws Exception {
1217 checkDeviceOwnerWithMultipleDeviceAdmins();
1218 }
1219
1220 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1221 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1222 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1223 // make sure it gets the right component from the right user.
1224
1225 final int ANOTHER_USER_ID = 100;
1226 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1227
Pavel Grafov75c0a892017-05-18 17:28:27 +01001228 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001229
1230 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001231 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001232 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1233 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1234
1235 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1236
Pavel Grafov75c0a892017-05-18 17:28:27 +01001237 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001238
Makoto Onukia52562c2015-10-01 16:12:31 -07001239 // Make sure the admin packge is installed to each user.
1240 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1241 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1242
1243 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1244 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1245
1246 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1247
1248
1249 // Set active admins to the users.
1250 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1251 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1252
1253 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1254 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1255
1256 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1257
1258 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001259 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001260 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1261
Makoto Onukic8a5a552015-11-19 14:29:12 -08001262 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001263
1264 // Then check getDeviceOwnerAdminLocked().
1265 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1266 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1267 }
1268
1269 /**
1270 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001271 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1272 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001273 *
1274 * We didn't use to persist the DO component class name, but now we do, and the above method
1275 * finds the right component from a package name upon migration.
1276 */
1277 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001278 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001279 checkDeviceOwnerWithMultipleDeviceAdmins();
1280
1281 // Overwrite the device owner setting and clears the clas name.
1282 dpms.mOwners.setDeviceOwner(
1283 new ComponentName(admin2.getPackageName(), ""),
1284 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1285 dpms.mOwners.writeDeviceOwner();
1286
1287 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001288 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001289
1290 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001291 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001292 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001293 initializeDpms();
1294
1295 // Now the DO component name is a full name.
1296 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1297 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001298 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001299 }
1300
Makoto Onukib643fb02015-09-22 15:03:44 -07001301 public void testSetGetApplicationRestriction() {
1302 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001303 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001304
1305 {
1306 Bundle rest = new Bundle();
1307 rest.putString("KEY_STRING", "Foo1");
1308 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1309 }
1310
1311 {
1312 Bundle rest = new Bundle();
1313 rest.putString("KEY_STRING", "Foo2");
1314 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1315 }
1316
1317 {
1318 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1319 assertNotNull(returned);
1320 assertEquals(returned.size(), 1);
1321 assertEquals(returned.get("KEY_STRING"), "Foo1");
1322 }
1323
1324 {
1325 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1326 assertNotNull(returned);
1327 assertEquals(returned.size(), 1);
1328 assertEquals(returned.get("KEY_STRING"), "Foo2");
1329 }
1330
1331 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1332 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1333 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001334
Edman Anjosf9946772016-11-28 16:35:15 +01001335 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001336 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1337 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001338 *
1339 * @param packageName the name of the package to be setup
1340 * @param appId the application ID to be given to the package
1341 * @return the UID of the package as known by the mock package manager
1342 */
1343 private int setupPackageInPackageManager(final String packageName, final int appId)
1344 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001345 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001346 ApplicationInfo.FLAG_HAS_CODE);
1347 }
1348
1349 /**
1350 * Setup a package in the package manager mock. Useful for faking installed applications.
1351 *
1352 * @param packageName the name of the package to be setup
1353 * @param userId the user id where the package will be "installed"
1354 * @param appId the application ID to be given to the package
1355 * @param flags flags to set in the ApplicationInfo for this package
1356 * @return the UID of the package as known by the mock package manager
1357 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001358 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1359 int flags) throws Exception {
1360 final int uid = UserHandle.getUid(userId, appId);
1361 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001362 final PackageInfo pi = new PackageInfo();
1363 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001364 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001365 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001366 eq(packageName),
1367 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001368 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001369 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001370 eq(packageName),
1371 anyInt(),
1372 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001373 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001374 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001375 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001376 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001377 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001378 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001379 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001380 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001381 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001382 return uid;
1383 }
1384
Robin Lee7f5c91c2017-02-08 21:27:02 +00001385 public void testCertificateDisclosure() throws Exception {
1386 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1387 final UserHandle user = UserHandle.of(userId);
1388
1389 mContext.applicationInfo = new ApplicationInfo();
1390 mContext.callerPermissions.add(permission.MANAGE_USERS);
1391 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001392 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001393 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1394
Robin Leeabaa0692017-02-20 20:54:22 +00001395 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1396 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001397
1398 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1399 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1400
1401 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001402 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001403 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001404 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001405 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001406 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001407 .cancelAsUser(anyString(), anyInt(), eq(user));
1408
1409 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001410 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001411 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001412 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1413 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001414 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001415 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001416 .notifyAsUser(anyString(), anyInt(), argThat(
1417 new BaseMatcher<Notification>() {
1418 @Override
1419 public boolean matches(Object item) {
1420 final Notification noti = (Notification) item;
1421 return TEST_STRING.equals(
1422 noti.extras.getString(Notification.EXTRA_TITLE));
1423 }
1424 @Override
1425 public void describeTo(Description description) {
1426 description.appendText(
1427 "Notification{title=\"" + TEST_STRING + "\"}");
1428 }
1429 }), eq(user));
1430 }
1431
Edman Anjosf9946772016-11-28 16:35:15 +01001432 /**
1433 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1434 * privileges can acually be exercised by a delegate are not covered here.
1435 */
1436 public void testDelegation() throws Exception {
1437 setAsProfileOwner(admin1);
1438
1439 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1440
1441 // Given two packages
1442 final String CERT_DELEGATE = "com.delegate.certs";
1443 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1444 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1445 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1446 20989);
1447
1448 // On delegation
1449 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1450 mContext.packageName = admin1.getPackageName();
1451 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1452 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1453
1454 // DPMS correctly stores and retrieves the delegates
1455 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1456 assertEquals(2, policy.mDelegationMap.size());
1457 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1458 DELEGATION_CERT_INSTALL);
1459 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1460 DELEGATION_CERT_INSTALL);
1461 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1462 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1463 DELEGATION_APP_RESTRICTIONS);
1464 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1465 DELEGATION_APP_RESTRICTIONS);
1466 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1467
1468 // On calling install certificate APIs from an unauthorized process
1469 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1470 mContext.packageName = RESTRICTIONS_DELEGATE;
1471
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001472 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1473 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001474
1475 // On calling install certificate APIs from an authorized process
1476 mContext.binder.callingUid = CERT_DELEGATE_UID;
1477 mContext.packageName = CERT_DELEGATE;
1478
1479 // DPMS executes without a SecurityException
1480 try {
1481 dpm.installCaCert(null, null);
1482 } catch (SecurityException unexpected) {
1483 fail("Threw SecurityException on authorized access");
1484 } catch (NullPointerException expected) {
1485 }
1486
1487 // On removing a delegate
1488 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1489 mContext.packageName = admin1.getPackageName();
1490 dpm.setCertInstallerPackage(admin1, null);
1491
1492 // DPMS does not allow access to ex-delegate
1493 mContext.binder.callingUid = CERT_DELEGATE_UID;
1494 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001495 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1496 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001497
1498 // But still allows access to other existing delegates
1499 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1500 mContext.packageName = RESTRICTIONS_DELEGATE;
1501 try {
1502 dpm.getApplicationRestrictions(null, "pkg");
1503 } catch (SecurityException expected) {
1504 fail("Threw SecurityException on authorized access");
1505 }
1506 }
1507
Esteban Talaverabf60f722015-12-10 16:26:44 +00001508 public void testApplicationRestrictionsManagingApp() throws Exception {
1509 setAsProfileOwner(admin1);
1510
Rubin Xued1928a2016-02-11 17:23:06 +00001511 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001512 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001513 final String nonDelegateExceptionMessageRegex =
1514 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001515 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001516 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1517 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001518
Esteban Talaverabf60f722015-12-10 16:26:44 +00001519 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1520 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001521 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1522 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001523 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001524 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001525 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001526 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1527 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001528
1529 // Check via the profile owner that no restrictions were set.
1530 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001531 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001532 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1533
Rubin Xued1928a2016-02-11 17:23:06 +00001534 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001535 assertExpectException(PackageManager.NameNotFoundException.class,
1536 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1537 () -> dpm.setApplicationRestrictionsManagingPackage(
1538 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001539
Esteban Talaverabf60f722015-12-10 16:26:44 +00001540 // Let appRestrictionsManagerPackage manage app restrictions
1541 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1542 assertEquals(appRestrictionsManagerPackage,
1543 dpm.getApplicationRestrictionsManagingPackage(admin1));
1544
1545 // Now that package should be able to set and retrieve app restrictions.
1546 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001547 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001548 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1549 dpm.setApplicationRestrictions(null, "pkg1", rest);
1550 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1551 assertEquals(1, returned.size(), 1);
1552 assertEquals("Foo1", returned.get("KEY_STRING"));
1553
1554 // The same app running on a separate user shouldn't be able to manage app restrictions.
1555 mContext.binder.callingUid = UserHandle.getUid(
1556 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1557 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001558 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1559 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001560
1561 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1562 // too.
1563 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001564 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001565 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1566 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1567 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1568
1569 // Removing the ability for the package to manage app restrictions.
1570 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1571 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1572 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001573 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001574 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001575 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1576 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001577 }
1578
Makoto Onukia4f11972015-10-01 13:19:58 -07001579 public void testSetUserRestriction_asDo() throws Exception {
1580 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001581 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001582 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1583 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1584
1585 // First, set DO.
1586
1587 // Call from a process on the system user.
1588 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1589
1590 // Make sure admin1 is installed on system user.
1591 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001592
1593 // Call.
1594 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001595 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001596 UserHandle.USER_SYSTEM));
1597
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001598 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001599 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001600 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001601 DpmTestUtils.assertRestrictions(
1602 DpmTestUtils.newRestrictions(defaultRestrictions),
1603 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1604 );
1605 DpmTestUtils.assertRestrictions(
1606 DpmTestUtils.newRestrictions(defaultRestrictions),
1607 dpm.getUserRestrictions(admin1)
1608 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001609 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001610 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001611 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001612 eq(true) /* isDeviceOwner */,
1613 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001614 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001615 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001616
1617 for (String restriction : defaultRestrictions) {
1618 dpm.clearUserRestriction(admin1, restriction);
1619 }
1620
Esteban Talavera548a04b2016-12-20 15:22:30 +00001621 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001622 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001623
1624 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001625 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001626 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001627 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1628 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001629 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001630
Makoto Onukia4f11972015-10-01 13:19:58 -07001631 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001632 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001633 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001634 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1635 UserManager.DISALLOW_ADD_USER),
1636 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001637 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001638
Makoto Onuki068c54a2015-10-13 14:34:03 -07001639 DpmTestUtils.assertRestrictions(
1640 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001641 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001642 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1643 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001644 DpmTestUtils.assertRestrictions(
1645 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001646 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001647 dpm.getUserRestrictions(admin1)
1648 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001649
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001651 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001652 eq(UserHandle.USER_SYSTEM),
1653 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001654 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001655 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001656
Makoto Onuki068c54a2015-10-13 14:34:03 -07001657 DpmTestUtils.assertRestrictions(
1658 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1659 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1660 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001661 DpmTestUtils.assertRestrictions(
1662 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1663 dpm.getUserRestrictions(admin1)
1664 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001665
1666 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001667 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001668 eq(UserHandle.USER_SYSTEM),
1669 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001670 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001671 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001672
Esteban Talavera548a04b2016-12-20 15:22:30 +00001673 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001674
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001675 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1676 // DO sets them, the scope is global.
1677 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001678 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001679 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001680 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001682 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001683 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1684 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001685 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686
1687 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1688 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001689 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001690
1691 // More tests.
1692 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001693 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001694 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001695 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1696 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001697 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698
1699 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001700 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001701 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001702 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001703 UserManager.DISALLOW_ADD_USER),
1704 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001705 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706
1707 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001708 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001709 eq(UserHandle.USER_SYSTEM),
1710 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001711 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001712 UserManager.DISALLOW_ADD_USER),
1713 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001714 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001715 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001716
Eric Sandnessca5969d2018-08-10 13:28:46 +01001717 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1718 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1719 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720
Eric Sandnessca5969d2018-08-10 13:28:46 +01001721 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1722 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001723
Eric Sandnessca5969d2018-08-10 13:28:46 +01001724 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1725 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1726 () -> dpm.setCameraDisabled(admin1, true));
1727 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1728
1729 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1730 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1731 () -> dpm.setKeyguardDisabledFeatures(admin1,
1732 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1733 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1734
1735 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1736 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1737 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1738 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1739
1740 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1741 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1742 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1743 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001744 }
1745
1746 public void testSetUserRestriction_asPo() {
1747 setAsProfileOwner(admin1);
1748
Makoto Onuki068c54a2015-10-13 14:34:03 -07001749 DpmTestUtils.assertRestrictions(
1750 DpmTestUtils.newRestrictions(),
1751 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1752 .ensureUserRestrictions()
1753 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001754
1755 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001756 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001757 eq(DpmMockContext.CALLER_USER_HANDLE),
1758 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001759 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001760 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001761
Makoto Onukia4f11972015-10-01 13:19:58 -07001762 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001763 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001764 eq(DpmMockContext.CALLER_USER_HANDLE),
1765 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1766 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001767 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001768 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001769
Makoto Onuki068c54a2015-10-13 14:34:03 -07001770 DpmTestUtils.assertRestrictions(
1771 DpmTestUtils.newRestrictions(
1772 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1773 UserManager.DISALLOW_OUTGOING_CALLS
1774 ),
1775 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1776 .ensureUserRestrictions()
1777 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001778 DpmTestUtils.assertRestrictions(
1779 DpmTestUtils.newRestrictions(
1780 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1781 UserManager.DISALLOW_OUTGOING_CALLS
1782 ),
1783 dpm.getUserRestrictions(admin1)
1784 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001785
1786 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001787 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788 eq(DpmMockContext.CALLER_USER_HANDLE),
1789 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001790 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001791 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001792
1793 DpmTestUtils.assertRestrictions(
1794 DpmTestUtils.newRestrictions(
1795 UserManager.DISALLOW_OUTGOING_CALLS
1796 ),
1797 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1798 .ensureUserRestrictions()
1799 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001800 DpmTestUtils.assertRestrictions(
1801 DpmTestUtils.newRestrictions(
1802 UserManager.DISALLOW_OUTGOING_CALLS
1803 ),
1804 dpm.getUserRestrictions(admin1)
1805 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001806
1807 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001808 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001809 eq(DpmMockContext.CALLER_USER_HANDLE),
1810 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001811 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001812 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001813
Makoto Onuki068c54a2015-10-13 14:34:03 -07001814 DpmTestUtils.assertRestrictions(
1815 DpmTestUtils.newRestrictions(),
1816 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1817 .ensureUserRestrictions()
1818 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001819 DpmTestUtils.assertRestrictions(
1820 DpmTestUtils.newRestrictions(),
1821 dpm.getUserRestrictions(admin1)
1822 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001823
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001824 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1825 // though when DO sets them they'll be applied globally.
1826 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001827 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001828 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001829 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001830 eq(DpmMockContext.CALLER_USER_HANDLE),
1831 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1832 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001833 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001834 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001835
1836 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001837 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001838 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001839 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001840 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001841 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001842 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001843
Makoto Onukia4f11972015-10-01 13:19:58 -07001844 // TODO Make sure restrictions are written to the file.
1845 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001846
Esteban Talavera548a04b2016-12-20 15:22:30 +00001847
1848 public void testDefaultEnabledUserRestrictions() throws Exception {
1849 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1850 mContext.callerPermissions.add(permission.MANAGE_USERS);
1851 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1852 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1853
1854 // First, set DO.
1855
1856 // Call from a process on the system user.
1857 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1858
1859 // Make sure admin1 is installed on system user.
1860 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1861
1862 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1863 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1864 UserHandle.USER_SYSTEM));
1865
1866 // Check that the user restrictions that are enabled by default are set. Then unset them.
1867 String[] defaultRestrictions = UserRestrictionsUtils
1868 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1869 assertTrue(defaultRestrictions.length > 0);
1870 DpmTestUtils.assertRestrictions(
1871 DpmTestUtils.newRestrictions(defaultRestrictions),
1872 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1873 );
1874 DpmTestUtils.assertRestrictions(
1875 DpmTestUtils.newRestrictions(defaultRestrictions),
1876 dpm.getUserRestrictions(admin1)
1877 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001878 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001879 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001880 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001881 eq(true) /* isDeviceOwner */,
1882 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001883 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001884 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001885
1886 for (String restriction : defaultRestrictions) {
1887 dpm.clearUserRestriction(admin1, restriction);
1888 }
1889
1890 assertNoDeviceOwnerRestrictions();
1891
1892 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001893 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001894 initializeDpms();
1895 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1896 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1897
1898 assertNoDeviceOwnerRestrictions();
1899
1900 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1901 // is set as it wasn't enabled during setDeviceOwner.
1902 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1903 assertFalse(UserRestrictionsUtils
1904 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1905 UserRestrictionsUtils
1906 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1907 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001908 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001909 initializeDpms();
1910 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1911 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1912
1913 DpmTestUtils.assertRestrictions(
1914 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1915 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1916 );
1917 DpmTestUtils.assertRestrictions(
1918 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1919 dpm.getUserRestrictions(admin1)
1920 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001921 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001922 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001923 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001924 eq(true) /* isDeviceOwner */,
1925 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001926 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001927 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001928
1929 // Remove the restriction.
1930 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1931
1932 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1933 initializeDpms();
1934 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1935 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1936 assertNoDeviceOwnerRestrictions();
1937 } finally {
1938 UserRestrictionsUtils
1939 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1940 }
1941 }
1942
1943 private void assertNoDeviceOwnerRestrictions() {
1944 DpmTestUtils.assertRestrictions(
1945 DpmTestUtils.newRestrictions(),
1946 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1947 );
1948 DpmTestUtils.assertRestrictions(
1949 DpmTestUtils.newRestrictions(),
1950 dpm.getUserRestrictions(admin1)
1951 );
1952 }
1953
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001954 public void testGetMacAddress() throws Exception {
1955 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1956 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1957 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1958
1959 // In this test, change the caller user to "system".
1960 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1961
1962 // Make sure admin1 is installed on system user.
1963 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1964
1965 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001966 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1967 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001968
1969 // DO needs to be an DA.
1970 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1971 assertTrue(dpm.isAdminActive(admin1));
1972
1973 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001974 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1975 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001976
1977 // Test 3. Caller has PO, but not DO.
1978 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001979 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1980 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001981
1982 // Remove PO.
1983 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001984 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001985 // Test 4, Caller is DO now.
1986 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1987
xshu425b9a62018-12-13 14:18:18 -08001988 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001989 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001990
xshu425b9a62018-12-13 14:18:18 -08001991 // 4-2. When WifiManager returns an empty array, dpm should also output null.
1992 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001993 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001994
1995 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08001996 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
1997 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001998 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001999 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002000
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002001 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002002 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2003 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2004
2005 // In this test, change the caller user to "system".
2006 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2007
2008 // Make sure admin1 is installed on system user.
2009 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2010
2011 // Set admin1 as DA.
2012 dpm.setActiveAdmin(admin1, false);
2013 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002014 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2015 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002016
2017 // Set admin1 as PO.
2018 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002019 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2020 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002021
2022 // Remove PO and add DO.
2023 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002024 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002025 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2026
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002027 // admin1 is DO.
2028 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002029 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002030 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002031 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2032 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002033
2034 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002035 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002036 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002037 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2038 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002039
2040 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002041 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002042 dpm.reboot(admin1);
2043 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002044
2045 public void testSetGetSupportText() {
2046 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2047 dpm.setActiveAdmin(admin1, true);
2048 dpm.setActiveAdmin(admin2, true);
2049 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2050
2051 // Null default support messages.
2052 {
2053 assertNull(dpm.getLongSupportMessage(admin1));
2054 assertNull(dpm.getShortSupportMessage(admin1));
2055 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2056 assertNull(dpm.getShortSupportMessageForUser(admin1,
2057 DpmMockContext.CALLER_USER_HANDLE));
2058 assertNull(dpm.getLongSupportMessageForUser(admin1,
2059 DpmMockContext.CALLER_USER_HANDLE));
2060 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2061 }
2062
2063 // Only system can call the per user versions.
2064 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002065 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2066 () -> dpm.getShortSupportMessageForUser(admin1,
2067 DpmMockContext.CALLER_USER_HANDLE));
2068 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2069 () -> dpm.getLongSupportMessageForUser(admin1,
2070 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002071 }
2072
2073 // Can't set message for admin in another uid.
2074 {
2075 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002076 assertExpectException(SecurityException.class,
2077 /* messageRegex= */ "is not owned by uid",
2078 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002079 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2080 }
2081
2082 // Set/Get short returns what it sets and other admins text isn't changed.
2083 {
2084 final String supportText = "Some text to test with.";
2085 dpm.setShortSupportMessage(admin1, supportText);
2086 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2087 assertNull(dpm.getLongSupportMessage(admin1));
2088 assertNull(dpm.getShortSupportMessage(admin2));
2089
2090 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2091 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2092 DpmMockContext.CALLER_USER_HANDLE));
2093 assertNull(dpm.getShortSupportMessageForUser(admin2,
2094 DpmMockContext.CALLER_USER_HANDLE));
2095 assertNull(dpm.getLongSupportMessageForUser(admin1,
2096 DpmMockContext.CALLER_USER_HANDLE));
2097 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2098
2099 dpm.setShortSupportMessage(admin1, null);
2100 assertNull(dpm.getShortSupportMessage(admin1));
2101 }
2102
2103 // Set/Get long returns what it sets and other admins text isn't changed.
2104 {
2105 final String supportText = "Some text to test with.\nWith more text.";
2106 dpm.setLongSupportMessage(admin1, supportText);
2107 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2108 assertNull(dpm.getShortSupportMessage(admin1));
2109 assertNull(dpm.getLongSupportMessage(admin2));
2110
2111 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2112 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2113 DpmMockContext.CALLER_USER_HANDLE));
2114 assertNull(dpm.getLongSupportMessageForUser(admin2,
2115 DpmMockContext.CALLER_USER_HANDLE));
2116 assertNull(dpm.getShortSupportMessageForUser(admin1,
2117 DpmMockContext.CALLER_USER_HANDLE));
2118 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2119
2120 dpm.setLongSupportMessage(admin1, null);
2121 assertNull(dpm.getLongSupportMessage(admin1));
2122 }
2123 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002124
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002125 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002126 setAsProfileOwner(admin1);
2127
2128 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002129 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002130
2131 // Setup
2132 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2133 final String package1 = "com.example.one";
2134 final String package2 = "com.example.two";
2135 pkgsToRestrict.add(package1);
2136 pkgsToRestrict.add(package2);
2137 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2138 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002139 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002140
2141 // Verify
2142 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002143 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002144 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2145 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2146 eq(DpmMockContext.CALLER_USER_HANDLE));
2147
2148 // Setup
2149 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002150 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002151
2152 // Verify
2153 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002154 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002155 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2156 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2157 eq(DpmMockContext.CALLER_USER_HANDLE));
2158 }
2159
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002160 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002161 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2162 dpm.setActiveAdmin(admin1, true);
2163 assertTrue(dpm.isAdminActive(admin1));
2164 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2165
2166 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002167 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002168 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002169 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002170 }
2171
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002172 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002173 setAsProfileOwner(admin1);
2174
2175 // Setup
2176 final ArrayList<String> emptyList = new ArrayList<>();
2177 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2178 final String package1 = "com.example.one";
2179 final String package2 = "com.example.two";
2180 final String package3 = "com.example.three";
2181 pkgsToRestrict.add(package1);
2182 pkgsToRestrict.add(package2);
2183 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2184 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002185 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002186
2187 // Verify
2188 assertEquals(emptyList, excludedPkgs);
2189 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2190 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002191 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002192 DpmMockContext.CALLER_USER_HANDLE));
2193 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002194 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002195 DpmMockContext.CALLER_USER_HANDLE));
2196 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002197 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002198 DpmMockContext.CALLER_USER_HANDLE));
2199 }
2200
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002201 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002202 setAsProfileOwner(admin1);
2203 assertExpectException(SecurityException.class,
2204 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002205 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002206 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2207 dpm.clearProfileOwner(admin1);
2208
2209 setDeviceOwner();
2210 assertExpectException(SecurityException.class,
2211 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002212 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002213 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2214 clearDeviceOwner();
2215 }
2216
phweiss73145f42017-01-17 19:06:38 +01002217 public void testCreateAdminSupportIntent() throws Exception {
2218 // Setup device owner.
2219 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2220 setupDeviceOwner();
2221
2222 // Nonexisting permission returns null
2223 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2224 assertNull(intent);
2225
2226 // Existing permission that is not set returns null
2227 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2228 assertNull(intent);
2229
2230 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002231 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002232 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2233 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2234 .thenReturn(true);
2235 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2236 assertNull(intent);
2237
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002238 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2239 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2240 new UserManager.EnforcingUser(
2241 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2242 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002243 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002244 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002245 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2246 assertNotNull(intent);
2247 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2248 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2249 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002250 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002251 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2252 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2253
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002254 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2255 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002256
2257 // Camera is not disabled
2258 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2259 assertNull(intent);
2260
2261 // Camera is disabled
2262 dpm.setCameraDisabled(admin1, true);
2263 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2264 assertNotNull(intent);
2265 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2266 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2267
2268 // Screen capture is not disabled
2269 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2270 assertNull(intent);
2271
2272 // Screen capture is disabled
2273 dpm.setScreenCaptureDisabled(admin1, true);
2274 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2275 assertNotNull(intent);
2276 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2277 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2278
2279 // Same checks for different user
2280 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2281 // Camera should be disabled by device owner
2282 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2283 assertNotNull(intent);
2284 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2285 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2286 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2287 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2288 // ScreenCapture should not be disabled by device owner
2289 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2290 assertNull(intent);
2291 }
2292
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002293 /**
2294 * Test for:
2295 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002296 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002297 * {@link DevicePolicyManager#isAffiliatedUser}
2298 */
2299 public void testUserAffiliation() throws Exception {
2300 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2301 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2302 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2303
2304 // Check that the system user is unaffiliated.
2305 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2306 assertFalse(dpm.isAffiliatedUser());
2307
2308 // Set a device owner on the system user. Check that the system user becomes affiliated.
2309 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2310 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2311 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2312 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002313 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002314
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002315 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002316 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2317 setAsProfileOwner(admin2);
2318 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002319 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002320
2321 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2322 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002323 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002324 userAffiliationIds.add("red");
2325 userAffiliationIds.add("green");
2326 userAffiliationIds.add("blue");
2327 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002328 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002329 assertFalse(dpm.isAffiliatedUser());
2330
2331 // Have the device owner specify a set of affiliation ids that do not intersect with those
2332 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002333 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002334 deviceAffiliationIds.add("cyan");
2335 deviceAffiliationIds.add("yellow");
2336 deviceAffiliationIds.add("magenta");
2337 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2338 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002339 MoreAsserts.assertContentsInAnyOrder(
2340 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002341 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2342 assertFalse(dpm.isAffiliatedUser());
2343
2344 // Have the profile owner specify a set of affiliation ids that intersect with those
2345 // specified by the device owner. Check that the test user becomes affiliated.
2346 userAffiliationIds.add("yellow");
2347 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002348 MoreAsserts.assertContentsInAnyOrder(
2349 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002350 assertTrue(dpm.isAffiliatedUser());
2351
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002352 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002353 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002354 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002355 assertFalse(dpm.isAffiliatedUser());
2356
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002357 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2358 dpm.setAffiliationIds(admin2, userAffiliationIds);
2359 assertTrue(dpm.isAffiliatedUser());
2360 dpm.clearProfileOwner(admin2);
2361 assertFalse(dpm.isAffiliatedUser());
2362
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002363 // Check that the system user remains affiliated.
2364 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2365 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002366
2367 // Clear the device owner - the user becomes unaffiliated.
2368 clearDeviceOwner();
2369 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002370 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002371
2372 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002373 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002374 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2375 }
2376
2377 public void testSetUserProvisioningState_permission() throws Exception {
2378 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002379
2380 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2381 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2382 }
2383
2384 public void testSetUserProvisioningState_unprivileged() throws Exception {
2385 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002386 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2387 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2388 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002389 }
2390
2391 public void testSetUserProvisioningState_noManagement() {
2392 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002393 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002394 assertExpectException(IllegalStateException.class,
2395 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2396 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2397 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002398 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2399 }
2400
2401 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2402 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2403 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002404
2405 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2406 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2407 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2408 }
2409
2410 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2411 throws Exception {
2412 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2413 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002414
2415 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2416 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2417 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2418 }
2419
2420 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2421 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2422 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002423
2424 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2425 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2426 }
2427
2428 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2429 throws Exception {
2430 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002431
2432 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2433 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2434 DevicePolicyManager.STATE_USER_UNMANAGED);
2435 }
2436
2437 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2438 throws Exception {
2439 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002440
2441 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2442 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2443 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2444 }
2445
2446 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2447 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002448
2449 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2450 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2451 }
2452
2453 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2454 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002455
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002456 assertExpectException(IllegalStateException.class,
2457 /* messageRegex= */ "Cannot move to user provisioning state",
2458 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2459 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2460 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002461 }
2462
2463 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2464 throws Exception {
2465 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002466
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002467 assertExpectException(IllegalStateException.class,
2468 /* messageRegex= */ "Cannot move to user provisioning state",
2469 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2470 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2471 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002472 }
2473
2474 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002475 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2476 mContext.callerPermissions.add(permission.MANAGE_USERS);
2477
Alan Treadwayafad8782016-01-19 15:15:08 +00002478 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2479 for (int state : states) {
2480 dpm.setUserProvisioningState(state, userId);
2481 assertEquals(state, dpm.getUserProvisioningState());
2482 }
2483 }
2484
2485 private void setupProfileOwner() throws Exception {
2486 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2487
2488 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2489 dpm.setActiveAdmin(admin1, false);
2490 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2491
2492 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2493 }
2494
2495 private void setupDeviceOwner() throws Exception {
2496 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2497
2498 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2499 dpm.setActiveAdmin(admin1, false);
2500 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2501
2502 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2503 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002504
2505 public void testSetMaximumTimeToLock() {
2506 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2507
2508 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2509 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2510
Pavel Grafov75c0a892017-05-18 17:28:27 +01002511 reset(getServices().powerManagerInternal);
2512 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002513
2514 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002515 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2516 verifyStayOnWhilePluggedCleared(false);
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, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002521 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2522 verifyStayOnWhilePluggedCleared(true);
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(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002527 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2528 verifyStayOnWhilePluggedCleared(false);
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(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002533 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2534 verifyStayOnWhilePluggedCleared(true);
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(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002539 verifyScreenTimeoutCall(4L, 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(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002545 reset(getServices().powerManagerInternal);
2546 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002547
Pavel Grafov28939982017-10-03 15:11:52 +01002548 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2549 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2550 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002551 reset(getServices().powerManagerInternal);
2552 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002553
2554 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002555 verifyScreenTimeoutCall(10L, 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
Pavel Grafov28939982017-10-03 15:11:52 +01002560 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002561 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002562 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2563 verifyStayOnWhilePluggedCleared(false);
2564 }
2565
2566 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2567 // uses separate challenge.
2568 public void testSetMaximumTimeToLockProfile() throws Exception {
2569 final int PROFILE_USER = 15;
2570 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2571 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2572 mContext.binder.callingUid = PROFILE_ADMIN;
2573 final DevicePolicyManagerInternal dpmi =
2574 LocalServices.getService(DevicePolicyManagerInternal.class);
2575
2576 dpm.setMaximumTimeToLock(admin1, 0);
2577
2578 reset(getServices().powerManagerInternal);
2579 reset(getServices().settings);
2580
2581 // First add timeout for the profile.
2582 dpm.setMaximumTimeToLock(admin1, 10);
2583 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2584
2585 reset(getServices().powerManagerInternal);
2586 reset(getServices().settings);
2587
2588 // Add separate challenge
2589 when(getServices().lockPatternUtils
2590 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2591 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2592
2593 verifyScreenTimeoutCall(10L, PROFILE_USER);
2594 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2595
2596 reset(getServices().powerManagerInternal);
2597 reset(getServices().settings);
2598
2599 // Remove the timeout.
2600 dpm.setMaximumTimeToLock(admin1, 0);
2601 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2602 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2603
2604 reset(getServices().powerManagerInternal);
2605 reset(getServices().settings);
2606
2607 // Add it back.
2608 dpm.setMaximumTimeToLock(admin1, 10);
2609 verifyScreenTimeoutCall(10L, PROFILE_USER);
2610 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2611
2612 reset(getServices().powerManagerInternal);
2613 reset(getServices().settings);
2614
2615 // Remove separate challenge.
2616 reset(getServices().lockPatternUtils);
2617 when(getServices().lockPatternUtils
2618 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2619 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002620 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002621
2622 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2623 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2624
2625 reset(getServices().powerManagerInternal);
2626 reset(getServices().settings);
2627
2628 // Remove the timeout.
2629 dpm.setMaximumTimeToLock(admin1, 0);
2630 verifyScreenTimeoutCall(null, PROFILE_USER);
2631 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002632 }
2633
Michal Karpinski943aabd2016-10-06 11:09:25 +01002634 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2635 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2636 setupDeviceOwner();
2637 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2638
Michal Karpinskid084ca52017-01-18 15:54:18 +00002639 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2640 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2641 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2642 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2643 - ONE_MINUTE;
2644
2645 // verify that the minimum timeout cannot be modified on user builds (system property is
2646 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002647 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002648
2649 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2650 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2651 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2652
Pavel Grafov75c0a892017-05-18 17:28:27 +01002653 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002654
2655 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002656 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002657
Michal Karpinskid084ca52017-01-18 15:54:18 +00002658 // reset to default (0 means the admin is not participating, so default should be returned)
2659 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002660
2661 // aggregation should be the default if unset by any admin
2662 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2663 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2664
2665 // admin not participating by default
2666 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2667
2668 //clamping from the top
2669 dpm.setRequiredStrongAuthTimeout(admin1,
2670 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2671 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2672 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2673 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2674 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2675
Michal Karpinskid084ca52017-01-18 15:54:18 +00002676 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002677 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2678 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2679 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2680 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2681
2682 // clamping from the bottom
2683 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2684 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2685 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2686
Michal Karpinskid084ca52017-01-18 15:54:18 +00002687 // values within range
2688 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2689 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2690 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2691
2692 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2693 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2694 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002695
2696 // reset to default
2697 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2698 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2699 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2700 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2701
2702 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002703 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2704 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002705 }
2706
Pavel Grafov28939982017-10-03 15:11:52 +01002707 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002708 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002709 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002710 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002711 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002712 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002713 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002714 }
Pavel Grafov28939982017-10-03 15:11:52 +01002715 }
2716
2717 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002718 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2719 // UnfinishedVerificationException.
2720 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002721
Esteban Talavera01576862016-12-15 11:16:44 +00002722 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002723 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002724 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002725 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002726 .thenReturn(false);
2727 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002728 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2729 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002730 .thenReturn(true);
2731 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2732
2733 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002734 }
Victor Chang3e794af2016-03-04 13:48:17 +00002735
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002736 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2737 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002738 mContext.packageName = admin1.getPackageName();
2739 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002740 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2741 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2742 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2743 false);
2744 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2745 }
2746
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002747 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2748 setup_DeviceAdminFeatureOff();
2749 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2750 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2751 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2752 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2753 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2754 assertCheckProvisioningPreCondition(
2755 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2756 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2757 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2758 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2759 }
2760
Esteban Talavera01576862016-12-15 11:16:44 +00002761 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002762 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002763 .thenReturn(false);
2764 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002765 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2766 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002767 .thenReturn(true);
2768 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2769
2770 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002771 }
Victor Chang3e794af2016-03-04 13:48:17 +00002772
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002773 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2774 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002775 mContext.packageName = admin1.getPackageName();
2776 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002777 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2778 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2779 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2780 false);
2781 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2782
2783 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002784 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2786 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2787 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2788 true);
2789 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2790 }
2791
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002792 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2793 setup_ManagedProfileFeatureOff();
2794 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2795 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2796 DevicePolicyManager.CODE_OK);
2797 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2798 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2799 assertCheckProvisioningPreCondition(
2800 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2801 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2802 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2803 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2804
2805 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002806 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002807 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2808 DevicePolicyManager.CODE_OK);
2809 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2810 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2811 assertCheckProvisioningPreCondition(
2812 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2813 DevicePolicyManager.CODE_OK);
2814 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2815 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2816 }
2817
Esteban Talavera01576862016-12-15 11:16:44 +00002818 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002819 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002820 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002821 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2822 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002823 .thenReturn(true);
2824 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2825
2826 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002827 }
Victor Chang3e794af2016-03-04 13:48:17 +00002828
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002829 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2830 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002831 mContext.packageName = admin1.getPackageName();
2832 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002833 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2834 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2835 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2836 false /* because of non-split user */);
2837 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2838 false /* because of non-split user */);
2839 }
2840
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002841 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002842 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002843 setup_nonSplitUser_firstBoot_primaryUser();
2844 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2845 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2846 DevicePolicyManager.CODE_OK);
2847 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2848 DevicePolicyManager.CODE_OK);
2849 assertCheckProvisioningPreCondition(
2850 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2851 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2852 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2853 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2854 }
2855
Esteban Talavera01576862016-12-15 11:16:44 +00002856 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002857 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002858 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002859 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2860 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002861 .thenReturn(true);
2862 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2863
2864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002865 }
Victor Chang3e794af2016-03-04 13:48:17 +00002866
Nicolas Prevot45d29072017-01-18 16:11:19 +00002867 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2868 setDeviceOwner();
2869 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2870 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2871 }
2872
2873 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2874 setup_nonSplitUser_withDo_primaryUser();
2875 final int MANAGED_PROFILE_USER_ID = 18;
2876 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2877 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002878 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002879 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002880 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002881 true)).thenReturn(true);
2882 }
2883
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002884 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2885 throws Exception {
2886 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002887 mContext.packageName = admin1.getPackageName();
2888 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002889 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2890 false/* because of completed device setup */);
2891 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2892 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2893 false/* because of non-split user */);
2894 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2895 false/* because of non-split user */);
2896 }
2897
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002898 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2899 throws Exception {
2900 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2901 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2902 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2903 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2904 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2905 DevicePolicyManager.CODE_OK);
2906 assertCheckProvisioningPreCondition(
2907 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2908 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2909 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2910 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2911 }
2912
Nicolas Prevot45d29072017-01-18 16:11:19 +00002913 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2914 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002915 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002916 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2917
2918 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2919 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002920 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002921
2922 // COMP mode is allowed.
2923 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2924 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002925 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002926
Nicolas Prevot45d29072017-01-18 16:11:19 +00002927 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002928 assertCheckProvisioningPreCondition(
2929 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002930 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002931 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002932 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2933 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2934 }
Esteban Talavera01576862016-12-15 11:16:44 +00002935
Nicolas Prevot45d29072017-01-18 16:11:19 +00002936 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2937 setup_nonSplitUser_withDo_primaryUser();
2938 mContext.packageName = admin1.getPackageName();
2939 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2940 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2941 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002942 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002943 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2944 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2945 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002946 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002947 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2948 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2949 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2950 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2951 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002952 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002953 assertCheckProvisioningPreCondition(
2954 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002955 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002956 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002957 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2958 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2959 }
Esteban Talavera01576862016-12-15 11:16:44 +00002960
Nicolas Prevot45d29072017-01-18 16:11:19 +00002961 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2962 throws Exception {
2963 setup_nonSplitUser_withDo_primaryUser();
2964 mContext.packageName = admin1.getPackageName();
2965 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002966 // The DO should not be allowed to initiate provisioning if the restriction is set by
2967 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002968 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002969 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2970 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2971 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002972 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002973 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2974 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2975 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2976 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2977 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002978 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2979
2980 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002981 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002982 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002983 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002984 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2985 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2986 }
2987
2988 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2989 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2990 mContext.packageName = admin1.getPackageName();
2991 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2992
2993 // We can delete the managed profile to create a new one, so provisioning is allowed.
2994 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2995 DevicePolicyManager.CODE_OK);
2996 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2997 assertCheckProvisioningPreCondition(
2998 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2999 DpmMockContext.ANOTHER_PACKAGE_NAME,
3000 DevicePolicyManager.CODE_OK);
3001 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3002 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3003 }
3004
3005 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3006 throws Exception {
3007 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3008 mContext.packageName = admin1.getPackageName();
3009 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003010 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003011 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3012 eq(UserHandle.SYSTEM)))
3013 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003014 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003015 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3016 eq(UserHandle.SYSTEM)))
3017 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003018
3019 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003020 assertCheckProvisioningPreCondition(
3021 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3022 DpmMockContext.ANOTHER_PACKAGE_NAME,
3023 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3024 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3025 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003026
3027 // But the device owner can still do it because it has set the restriction itself.
3028 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3029 DevicePolicyManager.CODE_OK);
3030 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003031 }
3032
3033 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003034 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003035 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003036 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3037 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003038 .thenReturn(false);
3039 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3040
3041 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003042 }
Victor Chang3e794af2016-03-04 13:48:17 +00003043
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003044 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3045 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003046 mContext.packageName = admin1.getPackageName();
3047 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003048 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3049 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3050 false /* because canAddMoreManagedProfiles returns false */);
3051 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3052 true);
3053 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3054 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003055 }
3056
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003057 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3058 throws Exception {
3059 setup_splitUser_firstBoot_systemUser();
3060 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3061 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3062 DevicePolicyManager.CODE_OK);
3063 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003064 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003065 assertCheckProvisioningPreCondition(
3066 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3067 DevicePolicyManager.CODE_OK);
3068 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3069 DevicePolicyManager.CODE_SYSTEM_USER);
3070 }
3071
Esteban Talavera01576862016-12-15 11:16:44 +00003072 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003073 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003074 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003075 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3076 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003077 .thenReturn(false);
3078 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3079
3080 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003081 }
Victor Chang3e794af2016-03-04 13:48:17 +00003082
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003083 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3084 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003085 mContext.packageName = admin1.getPackageName();
3086 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003087 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3088 true/* it's undefined behavior. Can be changed into false in the future */);
3089 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3090 false /* because canAddMoreManagedProfiles returns false */);
3091 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3092 true/* it's undefined behavior. Can be changed into false in the future */);
3093 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3094 false/* because calling uid is system user */);
3095 }
3096
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003097 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3098 throws Exception {
3099 setup_splitUser_afterDeviceSetup_systemUser();
3100 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3101 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3102 DevicePolicyManager.CODE_OK);
3103 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003104 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003105 assertCheckProvisioningPreCondition(
3106 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3107 DevicePolicyManager.CODE_OK);
3108 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3109 DevicePolicyManager.CODE_SYSTEM_USER);
3110 }
3111
Esteban Talavera01576862016-12-15 11:16:44 +00003112 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003113 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003114 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003115 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3116 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003117 true)).thenReturn(true);
3118 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3119
3120 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003121 }
Victor Chang3e794af2016-03-04 13:48:17 +00003122
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003123 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3124 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003125 mContext.packageName = admin1.getPackageName();
3126 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003127 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3128 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3129 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3130 true);
3131 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003132 }
3133
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003134 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003135 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003136 setup_splitUser_firstBoot_primaryUser();
3137 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3138 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3139 DevicePolicyManager.CODE_OK);
3140 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3141 DevicePolicyManager.CODE_OK);
3142 assertCheckProvisioningPreCondition(
3143 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3144 DevicePolicyManager.CODE_OK);
3145 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3146 DevicePolicyManager.CODE_OK);
3147 }
3148
Esteban Talavera01576862016-12-15 11:16:44 +00003149 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003150 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003151 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003152 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3153 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003154 true)).thenReturn(true);
3155 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3156
3157 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003158 }
Victor Chang3e794af2016-03-04 13:48:17 +00003159
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003160 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3161 throws Exception {
3162 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003163 mContext.packageName = admin1.getPackageName();
3164 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003165 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3166 true/* it's undefined behavior. Can be changed into false in the future */);
3167 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3168 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3169 true/* it's undefined behavior. Can be changed into false in the future */);
3170 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3171 false/* because user setup completed */);
3172 }
3173
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003174 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003175 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003176 setup_splitUser_afterDeviceSetup_primaryUser();
3177 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3178 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3179 DevicePolicyManager.CODE_OK);
3180 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3181 DevicePolicyManager.CODE_OK);
3182 assertCheckProvisioningPreCondition(
3183 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3184 DevicePolicyManager.CODE_OK);
3185 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3186 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3187 }
3188
Esteban Talavera01576862016-12-15 11:16:44 +00003189 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003190 setDeviceOwner();
3191
Pavel Grafov75c0a892017-05-18 17:28:27 +01003192 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003193 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003194 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3195 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003196 .thenReturn(false);
3197 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3198
3199 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003200 }
Victor Chang3e794af2016-03-04 13:48:17 +00003201
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003202 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3203 throws Exception {
3204 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003205 mContext.packageName = admin1.getPackageName();
3206 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003207 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3208 false /* can't provision managed profile on system user */);
3209 }
3210
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003211 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003212 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003213 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3214 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3215 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3216 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3217 }
3218
3219 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003220 setDeviceOwner();
3221
Pavel Grafov75c0a892017-05-18 17:28:27 +01003222 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003223 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003224 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3225 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003226 true)).thenReturn(true);
3227 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3228
3229 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003230 }
Victor Chang3e794af2016-03-04 13:48:17 +00003231
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003232 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3233 throws Exception {
3234 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003235 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3236 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003237 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3238 }
3239
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003240 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003241 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003242 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3243 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003244
3245 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003246 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3247 DevicePolicyManager.CODE_OK);
3248 }
3249
3250 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003251 setDeviceOwner();
3252
Pavel Grafov75c0a892017-05-18 17:28:27 +01003253 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003254 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003255 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3256 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003257 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3258 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003259 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003260 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003261 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003262 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003263 true)).thenReturn(true);
3264 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3265
3266 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003267 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003268
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003269 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3270 throws Exception {
3271 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003272 mContext.packageName = admin1.getPackageName();
3273 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003274 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3275 }
3276
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003277 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3278 throws Exception {
3279 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3280 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3281 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3282 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3283 }
3284
3285 public void testCheckProvisioningPreCondition_permission() {
3286 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003287 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3288 () -> dpm.checkProvisioningPreCondition(
3289 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003290 }
3291
Victor Chang3577ed22016-08-25 18:49:26 +01003292 public void testForceUpdateUserSetupComplete_permission() {
3293 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003294 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3295 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003296 }
3297
3298 public void testForceUpdateUserSetupComplete_systemUser() {
3299 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3300 // GIVEN calling from user 20
3301 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003302 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3303 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003304 }
3305
3306 public void testForceUpdateUserSetupComplete_userbuild() {
3307 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3308 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3309
3310 final int userId = UserHandle.USER_SYSTEM;
3311 // GIVEN userComplete is false in SettingsProvider
3312 setUserSetupCompleteForUser(false, userId);
3313
3314 // GIVEN userComplete is true in DPM
3315 DevicePolicyManagerService.DevicePolicyData userData =
3316 new DevicePolicyManagerService.DevicePolicyData(userId);
3317 userData.mUserSetupComplete = true;
3318 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3319
3320 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003321 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003322
3323 assertTrue(dpms.hasUserSetupCompleted());
3324
3325 dpm.forceUpdateUserSetupComplete();
3326
3327 // THEN the state in dpms is not changed
3328 assertTrue(dpms.hasUserSetupCompleted());
3329 }
3330
3331 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3332 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3333 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3334
3335 final int userId = UserHandle.USER_SYSTEM;
3336 // GIVEN userComplete is false in SettingsProvider
3337 setUserSetupCompleteForUser(false, userId);
3338
3339 // GIVEN userComplete is true in DPM
3340 DevicePolicyManagerService.DevicePolicyData userData =
3341 new DevicePolicyManagerService.DevicePolicyData(userId);
3342 userData.mUserSetupComplete = true;
3343 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3344
3345 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003346 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003347
3348 assertTrue(dpms.hasUserSetupCompleted());
3349
3350 dpm.forceUpdateUserSetupComplete();
3351
3352 // THEN the state in dpms is not changed
3353 assertFalse(dpms.hasUserSetupCompleted());
3354 }
3355
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003356 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003357 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003358 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003359
3360 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3361 runAsCaller(mAdmin1Context, dpms, dpm -> {
3362 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3363 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003364 }
3365
3366 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3367 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3368 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003369
3370 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3371 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003372 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003373 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3374 .thenReturn(true);
3375
3376 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003377 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003378
3379 // Enabling logging should not change the timestamp.
3380 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003381 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003382 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003383 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003384 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003385 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003386
3387 // Retrieving the logs should update the timestamp.
3388 final long beforeRetrieval = System.currentTimeMillis();
3389 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003390 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003391 final long afterRetrieval = System.currentTimeMillis();
3392 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3393 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3394
3395 // Retrieving the pre-boot logs should update the timestamp.
3396 Thread.sleep(2);
3397 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003398 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003399 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3400
3401 // Checking the timestamp again should not change it.
3402 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003403 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003404
3405 // Retrieving the logs again should update the timestamp.
3406 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003407 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003408 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3409
3410 // Disabling logging should not change the timestamp.
3411 Thread.sleep(2);
3412 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003413 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003414
3415 // Restarting the DPMS should not lose the timestamp.
3416 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003417 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003418
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003419 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3420 mContext.binder.callingUid = 1234567;
3421 mContext.callerPermissions.add(permission.MANAGE_USERS);
3422 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3423 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3424
3425 // System can retrieve the timestamp.
3426 mContext.binder.clearCallingIdentity();
3427 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3428
3429 // Removing the device owner should clear the timestamp.
3430 clearDeviceOwner();
3431 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003432 }
3433
yuemingw0de748d2017-11-15 19:22:27 +00003434 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3435 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3436 setupDeviceOwner();
3437 assertExpectException(SecurityException.class, null, () ->
3438 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3439 }
3440
yuemingwc0281f12018-03-28 15:58:49 +01003441 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003442 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3443 setupDeviceOwner();
3444 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003445 verify(getServices().settings).settingsSystemPutStringForUser(
3446 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3447 }
3448
3449 public void testSetSystemSettingWithPO() throws Exception {
3450 setupProfileOwner();
3451 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3452 verify(getServices().settings).settingsSystemPutStringForUser(
3453 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003454 }
3455
yuemingwe43cdf72017-10-12 16:52:11 +01003456 public void testSetTime() throws Exception {
3457 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3458 setupDeviceOwner();
3459 dpm.setTime(admin1, 0);
3460 verify(getServices().alarmManager).setTime(0);
3461 }
3462
3463 public void testSetTimeFailWithPO() throws Exception {
3464 setupProfileOwner();
3465 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3466 }
3467
3468 public void testSetTimeWithAutoTimeOn() throws Exception {
3469 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3470 setupDeviceOwner();
3471 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3472 .thenReturn(1);
3473 assertFalse(dpm.setTime(admin1, 0));
3474 }
3475
3476 public void testSetTimeZone() throws Exception {
3477 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3478 setupDeviceOwner();
3479 dpm.setTimeZone(admin1, "Asia/Shanghai");
3480 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3481 }
3482
3483 public void testSetTimeZoneFailWithPO() throws Exception {
3484 setupProfileOwner();
3485 assertExpectException(SecurityException.class, null,
3486 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3487 }
3488
3489 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3490 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3491 setupDeviceOwner();
3492 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3493 .thenReturn(1);
3494 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3495 }
3496
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003497 public void testGetLastBugReportRequestTime() throws Exception {
3498 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3499 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003500
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003501 mContext.packageName = admin1.getPackageName();
3502 mContext.applicationInfo = new ApplicationInfo();
3503 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3504 .thenReturn(Color.WHITE);
3505 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3506 anyObject())).thenReturn(Color.WHITE);
3507
Esteban Talaverad36dd152016-12-15 08:51:45 +00003508 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3509 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003510 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003511
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003512 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003513 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003514
3515 // Requesting a bug report should update the timestamp.
3516 final long beforeRequest = System.currentTimeMillis();
3517 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003518 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003519 final long afterRequest = System.currentTimeMillis();
3520 assertTrue(bugReportRequestTime >= beforeRequest);
3521 assertTrue(bugReportRequestTime <= afterRequest);
3522
3523 // Checking the timestamp again should not change it.
3524 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003525 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003526
3527 // Restarting the DPMS should not lose the timestamp.
3528 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003529 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003530
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003531 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3532 mContext.binder.callingUid = 1234567;
3533 mContext.callerPermissions.add(permission.MANAGE_USERS);
3534 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3535 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3536
3537 // System can retrieve the timestamp.
3538 mContext.binder.clearCallingIdentity();
3539 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3540
3541 // Removing the device owner should clear the timestamp.
3542 clearDeviceOwner();
3543 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003544 }
3545
3546 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3547 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3548 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003549 mContext.packageName = admin1.getPackageName();
3550 mContext.applicationInfo = new ApplicationInfo();
3551 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3552 .thenReturn(Color.WHITE);
3553 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3554 anyObject())).thenReturn(Color.WHITE);
3555
3556 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3557 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003558 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003559 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003560 .thenReturn(true);
3561
3562 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003563 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003564
3565 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3566 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003567 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003568
3569 // Enabling logging should not change the timestamp.
3570 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003571 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003572
3573 // Retrieving the logs should update the timestamp.
3574 final long beforeRetrieval = System.currentTimeMillis();
3575 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003576 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003577 final long afterRetrieval = System.currentTimeMillis();
3578 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3579 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3580
3581 // Checking the timestamp again should not change it.
3582 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003583 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003584
3585 // Retrieving the logs again should update the timestamp.
3586 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003587 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003588 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3589
3590 // Disabling logging should not change the timestamp.
3591 Thread.sleep(2);
3592 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003593 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003594
3595 // Restarting the DPMS should not lose the timestamp.
3596 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003597 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3598
3599 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3600 mContext.binder.callingUid = 1234567;
3601 mContext.callerPermissions.add(permission.MANAGE_USERS);
3602 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3603 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3604
3605 // System can retrieve the timestamp.
3606 mContext.binder.clearCallingIdentity();
3607 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3608
3609 // Removing the device owner should clear the timestamp.
3610 clearDeviceOwner();
3611 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003612 }
3613
Tony Mak2f26b792016-11-28 17:54:51 +00003614 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3615 // Setup device owner.
3616 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3617 setupDeviceOwner();
3618
3619 // Only device owner is setup, the result list should be empty.
3620 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3621 MoreAsserts.assertEmpty(targetUsers);
3622
3623 // Setup a managed profile managed by the same admin.
3624 final int MANAGED_PROFILE_USER_ID = 15;
3625 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3626 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3627
3628 // Add a secondary user, it should never talk with.
3629 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003630 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003631
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003632 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3633 // other.
3634 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3635 MoreAsserts.assertEmpty(targetUsers);
3636
3637 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3638 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3639 MoreAsserts.assertEmpty(targetUsers);
3640
3641 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003642 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003643 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3644 dpm.setAffiliationIds(admin1, userAffiliationIds);
3645
3646 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3647 dpm.setAffiliationIds(admin1, userAffiliationIds);
3648
Tony Mak2f26b792016-11-28 17:54:51 +00003649 // Calling from device owner admin, the result list should just contain the managed
3650 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003651 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003652 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3653 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3654
3655 // Calling from managed profile admin, the result list should just contain the system
3656 // user id.
3657 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3658 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3659 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003660
3661 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003662 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003663
3664 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3665 // to each other.
3666 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3667 MoreAsserts.assertEmpty(targetUsers);
3668
3669 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3670 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3671 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003672 }
3673
3674 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3675 // Setup a device owner.
3676 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3677 setupDeviceOwner();
3678
3679 // Set up a managed profile managed by different package.
3680 final int MANAGED_PROFILE_USER_ID = 15;
3681 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3682 final ComponentName adminDifferentPackage =
3683 new ComponentName("another.package", "whatever.class");
3684 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3685
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003686 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003687 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003688 dpm.setAffiliationIds(admin1, userAffiliationIds);
3689
3690 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3691 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3692
Tony Mak2f26b792016-11-28 17:54:51 +00003693 // Calling from device owner admin, we should get zero bind device admin target users as
3694 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003695 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003696 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3697 MoreAsserts.assertEmpty(targetUsers);
3698
3699 // Calling from managed profile admin, we should still get zero target users for the same
3700 // reason.
3701 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3702 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3703 MoreAsserts.assertEmpty(targetUsers);
3704 }
3705
Jason Parks3c13b642017-11-28 15:39:43 -06003706 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003707 verifyLockTaskState(userId, new String[0],
3708 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003709 }
3710
3711 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3712 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003713 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003714 }
3715
3716 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3717 int flags) throws Exception {
3718 mContext.binder.callingUid = uid;
3719 dpm.setLockTaskPackages(who, packages);
3720 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3721 for (String p : packages) {
3722 assertTrue(dpm.isLockTaskPermitted(p));
3723 }
3724 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3725 // Test to see if set lock task features can be set
3726 dpm.setLockTaskFeatures(who, flags);
3727 verifyLockTaskState(userId, packages, flags);
3728 }
3729
3730 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3731 int flags) throws Exception {
3732 mContext.binder.callingUid = uid;
3733 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3734 () -> dpm.setLockTaskPackages(who, packages));
3735 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3736 () -> dpm.getLockTaskPackages(who));
3737 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3738 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3739 () -> dpm.setLockTaskFeatures(who, flags));
3740 }
3741
Charles Hee078db72017-10-19 18:03:20 +01003742 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003743 // Setup a device owner.
3744 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3745 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003746 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003747 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003748
3749 // Set up a managed profile managed by different package (package name shouldn't matter)
3750 final int MANAGED_PROFILE_USER_ID = 15;
3751 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3752 final ComponentName adminDifferentPackage =
3753 new ComponentName("another.package", "whatever.class");
3754 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003755 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3756
3757 // Setup a PO on the secondary user
3758 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3759 setAsProfileOwner(admin3);
3760 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003761
3762 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003763 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003764 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003765 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3766 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003767 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3768
3769 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3770 final int secondaryPoFlags = 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 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003774
3775 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3776 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3777 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003778 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003779 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3780 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003781 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003782
3783 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003784 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003785 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3786 dpm.setAffiliationIds(admin1, userAffiliationIds);
3787
3788 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3789 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3790
3791 // Now the managed profile can set lock task packages.
3792 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3793 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3794 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3795 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003796 // And it can set lock task features.
3797 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003798 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003799
3800 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003801 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003802 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3803 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003804 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3805 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003806 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003807 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003808
Jason Parks3c13b642017-11-28 15:39:43 -06003809 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003810 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3811 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003812
3813 }
3814
3815 public void testLockTaskPolicyForProfileOwner() throws Exception {
3816 // Setup a PO
3817 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3818 setAsProfileOwner(admin1);
3819 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3820
3821 final String[] poPackages = {"poPackage1", "poPackage2"};
3822 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003823 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3824 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003825 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3826 poPackages, poFlags);
3827
3828 // Set up a managed profile managed by different package (package name shouldn't matter)
3829 final int MANAGED_PROFILE_USER_ID = 15;
3830 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3831 final ComponentName adminDifferentPackage =
3832 new ComponentName("another.package", "whatever.class");
3833 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3834 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3835
3836 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3837 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3838 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3839 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003840 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3841 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003842 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003843 }
3844
Benjamin Franzcaffa772018-02-05 16:36:10 +00003845 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3846 // Setup a device owner.
3847 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3848 setupDeviceOwner();
3849 // Lock task policy is updated when loading user data.
3850 verifyLockTaskState(UserHandle.USER_SYSTEM);
3851
3852 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3853 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3854 assertExpectException(IllegalArgumentException.class,
3855 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3856 () -> dpm.setLockTaskFeatures(admin1, flags));
3857 }
3858
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003859 public void testIsDeviceManaged() throws Exception {
3860 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3861 setupDeviceOwner();
3862
3863 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3864 // find out that the device has a device owner.
3865 assertTrue(dpm.isDeviceManaged());
3866 mContext.binder.callingUid = 1234567;
3867 mContext.callerPermissions.add(permission.MANAGE_USERS);
3868 assertTrue(dpm.isDeviceManaged());
3869 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3870 mContext.binder.clearCallingIdentity();
3871 assertTrue(dpm.isDeviceManaged());
3872
3873 clearDeviceOwner();
3874
3875 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3876 // not have a device owner.
3877 mContext.binder.callingUid = 1234567;
3878 mContext.callerPermissions.add(permission.MANAGE_USERS);
3879 assertFalse(dpm.isDeviceManaged());
3880 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3881 mContext.binder.clearCallingIdentity();
3882 assertFalse(dpm.isDeviceManaged());
3883 }
3884
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003885 public void testDeviceOwnerOrganizationName() throws Exception {
3886 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3887 setupDeviceOwner();
3888
3889 dpm.setOrganizationName(admin1, "organization");
3890
3891 // Device owner can retrieve organization managing the device.
3892 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3893
3894 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3895 mContext.binder.callingUid = 1234567;
3896 mContext.callerPermissions.add(permission.MANAGE_USERS);
3897 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3898 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3899
3900 // System can retrieve organization managing the device.
3901 mContext.binder.clearCallingIdentity();
3902 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3903
3904 // Removing the device owner clears the organization managing the device.
3905 clearDeviceOwner();
3906 assertNull(dpm.getDeviceOwnerOrganizationName());
3907 }
3908
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003909 public void testWipeDataManagedProfile() throws Exception {
3910 final int MANAGED_PROFILE_USER_ID = 15;
3911 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3912 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3913 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3914
3915 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003916 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003917 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003918 // Get mock reason string since we throw an IAE with empty string input.
3919 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3920 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003921
3922 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003923 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003924 MANAGED_PROFILE_USER_ID);
3925 }
3926
3927 public void testWipeDataManagedProfileDisallowed() throws Exception {
3928 final int MANAGED_PROFILE_USER_ID = 15;
3929 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3930 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3931
3932 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003933 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003934 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3935
Pavel Grafov75c0a892017-05-18 17:28:27 +01003936 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003937 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3938 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3939 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003940 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3941 thenReturn("Just a test string.");
3942
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003943 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003944 // The PO is not allowed to remove the profile if the user restriction was set on the
3945 // profile by the system
3946 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3947 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003948 }
3949
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003950 public void testWipeDataDeviceOwner() throws Exception {
3951 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003952 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003953 UserManager.DISALLOW_FACTORY_RESET,
3954 UserHandle.SYSTEM))
3955 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003956 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3957 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003958
3959 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003960 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003961 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3962 /*wipeEuicc=*/ eq(false));
3963 }
3964
3965 public void testWipeEuiccDataEnabled() throws Exception {
3966 setDeviceOwner();
3967 when(getServices().userManager.getUserRestrictionSource(
3968 UserManager.DISALLOW_FACTORY_RESET,
3969 UserHandle.SYSTEM))
3970 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003971 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3972 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003973
3974 dpm.wipeData(WIPE_EUICC);
3975 verify(getServices().recoverySystem).rebootWipeUserData(
3976 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3977 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003978 }
3979
3980 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3981 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003982 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003983 UserManager.DISALLOW_FACTORY_RESET,
3984 UserHandle.SYSTEM))
3985 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003986 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3987 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003988 // The DO is not allowed to wipe the device if the user restriction was set
3989 // by the system
3990 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3991 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003992 }
3993
3994 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3995 final int MANAGED_PROFILE_USER_ID = 15;
3996 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3997 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3998
3999 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004000 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004001 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4002
Pavel Grafov75c0a892017-05-18 17:28:27 +01004003 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004004 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4005 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4006 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4007
4008 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4009 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4010
4011 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4012 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4013 // Failed password attempts on the parent user are taken into account, as there isn't a
4014 // separate work challenge.
4015 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4016 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4017 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4018
4019 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4020 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004021 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004022 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004023 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004024 }
4025
4026 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4027 throws Exception {
4028 final int MANAGED_PROFILE_USER_ID = 15;
4029 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4030 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4031
4032 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004033 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004034 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4035
Pavel Grafov75c0a892017-05-18 17:28:27 +01004036 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004037 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4038 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4039 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4040
4041 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4042 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4043
4044 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4045 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4046 // Failed password attempts on the parent user are taken into account, as there isn't a
4047 // separate work challenge.
4048 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4049 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4050 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4051
4052 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4053 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004054 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004055 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004056 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004057 }
4058
4059 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4060 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004061 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004062 UserManager.DISALLOW_FACTORY_RESET,
4063 UserHandle.SYSTEM))
4064 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4065
4066 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4067
4068 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4069 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4070 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4071 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4072 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4073
4074 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4075 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004076 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004077 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4078 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004079 }
4080
4081 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4082 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004083 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004084 UserManager.DISALLOW_FACTORY_RESET,
4085 UserHandle.SYSTEM))
4086 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4087
4088 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4089
4090 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4091 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4092 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4093 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4094 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4095
4096 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004097 verifyZeroInteractions(getServices().recoverySystem);
4098 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004099 .removeUserEvenWhenDisallowed(anyInt());
4100 }
4101
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004102 public void testGetPermissionGrantState() throws Exception {
4103 final String permission = "some.permission";
4104 final String app1 = "com.example.app1";
4105 final String app2 = "com.example.app2";
4106
Pavel Grafov75c0a892017-05-18 17:28:27 +01004107 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004108 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004109 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004110 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004111 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004112 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4113 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004114 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004115 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004116 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004117 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004118 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004119 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4120
4121 // System can retrieve permission grant state.
4122 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004123 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004124 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4125 dpm.getPermissionGrantState(null, app1, permission));
4126 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4127 dpm.getPermissionGrantState(null, app2, permission));
4128
4129 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004130 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4131 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004132 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4133 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004134
4135 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004136 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4137 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004138 setAsProfileOwner(admin1);
4139 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4140 dpm.getPermissionGrantState(admin1, app1, permission));
4141 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4142 dpm.getPermissionGrantState(admin1, app2, permission));
4143 }
4144
Rubin Xuaab7a412016-12-30 21:13:29 +00004145 public void testResetPasswordWithToken() throws Exception {
4146 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4147 setupDeviceOwner();
4148 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004149 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4150 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4151
Rubin Xuaab7a412016-12-30 21:13:29 +00004152 // test adding a token
4153 final byte[] token = new byte[32];
4154 final long handle = 123456;
4155 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004156 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4157 nullable(EscrowTokenStateChangeCallback.class)))
4158 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004159 assertTrue(dpm.setResetPasswordToken(admin1, token));
4160
4161 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004162 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004163 .thenReturn(true);
4164 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4165
4166 // test reset password with token
Rich Canningsf64ec632019-02-21 12:40:36 -08004167 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password.getBytes()),
Rubin Xu7cf45092017-08-28 11:47:35 +01004168 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
Adrian Roosebf84c22018-12-06 17:50:41 +01004169 eq(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004170 eq(UserHandle.USER_SYSTEM)))
4171 .thenReturn(true);
4172 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4173
4174 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004175 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004176 .thenReturn(true);
4177 assertTrue(dpm.clearResetPasswordToken(admin1));
4178 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004179
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004180 public void testIsActivePasswordSufficient() throws Exception {
4181 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4182 mContext.packageName = admin1.getPackageName();
4183 setupDeviceOwner();
4184
4185 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4186 dpm.setPasswordMinimumLength(admin1, 8);
4187 dpm.setPasswordMinimumLetters(admin1, 6);
4188 dpm.setPasswordMinimumLowerCase(admin1, 3);
4189 dpm.setPasswordMinimumUpperCase(admin1, 1);
4190 dpm.setPasswordMinimumNonLetter(admin1, 1);
4191 dpm.setPasswordMinimumNumeric(admin1, 1);
4192 dpm.setPasswordMinimumSymbols(admin1, 0);
4193
Rubin Xucc391c22018-01-02 20:37:35 +00004194 reset(mContext.spiedContext);
4195
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004196 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4197 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4198 8, 2,
4199 6, 1,
4200 0, 1);
4201
4202 setActivePasswordState(passwordMetricsNoSymbols);
4203 assertTrue(dpm.isActivePasswordSufficient());
4204
4205 initializeDpms();
4206 reset(mContext.spiedContext);
4207 assertTrue(dpm.isActivePasswordSufficient());
4208
4209 // This call simulates the user entering the password for the first time after a reboot.
4210 // This causes password metrics to be reloaded into memory. Until this happens,
4211 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4212 // even if the DPC changes password requirements so that the password no longer meets the
4213 // requirements. This is a known limitation of the current implementation of
4214 // isActivePasswordSufficient() - see b/34218769.
4215 setActivePasswordState(passwordMetricsNoSymbols);
4216 assertTrue(dpm.isActivePasswordSufficient());
4217
4218 dpm.setPasswordMinimumSymbols(admin1, 1);
4219 // This assertion would fail if we had not called setActivePasswordState() again after
4220 // initializeDpms() - see previous comment.
4221 assertFalse(dpm.isActivePasswordSufficient());
4222
4223 initializeDpms();
4224 reset(mContext.spiedContext);
4225 assertFalse(dpm.isActivePasswordSufficient());
4226
4227 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4228 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4229 7, 2,
4230 5, 1,
4231 1, 2);
4232
4233 setActivePasswordState(passwordMetricsWithSymbols);
4234 assertTrue(dpm.isActivePasswordSufficient());
4235 }
4236
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004237 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4238 // If there is no lock screen, the password is considered empty no matter what, because
4239 // it provides no security.
4240 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4241
4242 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4243 mContext.packageName = admin1.getPackageName();
4244 setupDeviceOwner();
4245
4246 // If no password requirements are set, isActivePasswordSufficient should succeed.
4247 assertTrue(dpm.isActivePasswordSufficient());
4248
4249 // Now set some password quality requirements.
4250 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4251
4252 reset(mContext.spiedContext);
4253 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4254 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4255 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4256 8, 2,
4257 6, 1,
4258 0, 1);
4259 // This should be ignored, as there is no lock screen.
4260 dpm.setActivePasswordState(passwordMetricsNoSymbols, userHandle);
4261 dpm.reportPasswordChanged(userHandle);
4262
4263 // No broadcast should be sent.
4264 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4265 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4266 MockUtils.checkUserHandle(userHandle));
4267
4268 // The active (nonexistent) password doesn't comply with the requirements.
4269 assertFalse(dpm.isActivePasswordSufficient());
4270 }
4271
Pavel Grafov75c0a892017-05-18 17:28:27 +01004272 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4273 throws Exception {
4274 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004275 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004276
Pavel Grafov75c0a892017-05-18 17:28:27 +01004277 dpm.setActivePasswordState(passwordMetrics, userHandle);
4278 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004279
Rubin Xucc391c22018-01-02 20:37:35 +00004280 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4281 // reportPasswordChanged()
Eran Messeri9ecde422018-04-30 16:16:39 +01004282 // This broadcast should be sent 4 times:
4283 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4284 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
4285 // * Twice from calls to DevicePolicyManagerService.saveSettingsLocked
4286 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4287 // the password change is relevant to and another with the credential owner of said
4288 // userId.
4289 verify(mContext.spiedContext, times(4)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004290 MockUtils.checkIntentAction(
4291 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4292 MockUtils.checkUserHandle(userHandle));
4293
Pavel Grafov75c0a892017-05-18 17:28:27 +01004294 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4295 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004296 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004297
4298 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4299 MockUtils.checkIntent(intent),
4300 MockUtils.checkUserHandle(userHandle));
4301
4302 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4303 // let it finish with system uid, otherwise it will throw and crash.
4304 flushTasks();
4305
4306 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004307 }
4308
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004309 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4310 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4311 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4312 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4313 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4314 DpmMockContext.SYSTEM_UID);
4315 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4316 DpmMockContext.SYSTEM_UID);
4317
4318 // Set up a device owner.
4319 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004320 setupDeviceOwner();
4321
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004322 // First and second user set IMEs manually.
4323 mContext.binder.callingUid = firstUserSystemUid;
4324 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4325 mContext.binder.callingUid = secondUserSystemUid;
4326 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004327
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004328 // Device owner changes IME for first user.
4329 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004330 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004331 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004332 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004333 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004334 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004335 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004336 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4337 mContext.binder.callingUid = firstUserSystemUid;
4338 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4339 mContext.binder.callingUid = secondUserSystemUid;
4340 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004341
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004342 // Second user changes IME manually.
4343 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4344 mContext.binder.callingUid = firstUserSystemUid;
4345 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4346 mContext.binder.callingUid = secondUserSystemUid;
4347 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004348
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004349 // First user changes IME manually.
4350 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4351 mContext.binder.callingUid = firstUserSystemUid;
4352 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4353 mContext.binder.callingUid = secondUserSystemUid;
4354 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004355
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004356 // Device owner changes IME for first user again.
4357 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004358 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004359 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004360 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004361 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004362 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004363 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4364 mContext.binder.callingUid = firstUserSystemUid;
4365 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4366 mContext.binder.callingUid = secondUserSystemUid;
4367 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004368
4369 // Restarting the DPMS should not lose information.
4370 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004371 mContext.binder.callingUid = firstUserSystemUid;
4372 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4373 mContext.binder.callingUid = secondUserSystemUid;
4374 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004375
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004376 // Device owner can find out whether it set the current IME itself.
4377 mContext.binder.callingUid = deviceOwnerUid;
4378 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004379
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004380 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004381 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004382 mContext.binder.callingUid = firstUserSystemUid;
4383 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4384 mContext.binder.callingUid = secondUserSystemUid;
4385 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004386 }
4387
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004388 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4389 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4390 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4391 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4392 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4393 DpmMockContext.SYSTEM_UID);
4394 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4395 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004396
4397 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004398 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004399 setupProfileOwner();
4400
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004401 // First and second user set IMEs manually.
4402 mContext.binder.callingUid = firstUserSystemUid;
4403 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4404 mContext.binder.callingUid = secondUserSystemUid;
4405 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004406
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004407 // Profile owner changes IME for second user.
4408 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004409 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004410 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004411 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004412 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004413 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004414 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004415 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4416 mContext.binder.callingUid = firstUserSystemUid;
4417 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4418 mContext.binder.callingUid = secondUserSystemUid;
4419 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004420
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004421 // First user changes IME manually.
4422 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4423 mContext.binder.callingUid = firstUserSystemUid;
4424 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4425 mContext.binder.callingUid = secondUserSystemUid;
4426 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004427
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004428 // Second user changes IME manually.
4429 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4430 mContext.binder.callingUid = firstUserSystemUid;
4431 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4432 mContext.binder.callingUid = secondUserSystemUid;
4433 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004434
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004435 // Profile owner changes IME for second user again.
4436 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004437 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004438 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004439 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004440 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004441 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004442 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4443 mContext.binder.callingUid = firstUserSystemUid;
4444 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4445 mContext.binder.callingUid = secondUserSystemUid;
4446 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004447
4448 // Restarting the DPMS should not lose information.
4449 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004450 mContext.binder.callingUid = firstUserSystemUid;
4451 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4452 mContext.binder.callingUid = secondUserSystemUid;
4453 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004454
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004455 // Profile owner can find out whether it set the current IME itself.
4456 mContext.binder.callingUid = profileOwnerUid;
4457 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004458
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004459 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004460 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004461 mContext.binder.callingUid = firstUserSystemUid;
4462 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4463 mContext.binder.callingUid = secondUserSystemUid;
4464 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004465 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004466
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004467 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4468 throws Exception {
4469 // Set up a device owner.
4470 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4471 setupDeviceOwner();
4472 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4473 }
4474
4475 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4476 throws Exception {
4477 // Set up a profile owner.
4478 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4479 setupProfileOwner();
4480 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4481 }
4482
4483 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4484 int adminUid) throws Exception {
4485 mContext.binder.callingUid = adminUid;
4486 final int userId = UserHandle.getUserId(adminUid);
4487
4488 final String packageName = "some.package";
4489 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4490 admin1, Collections.singletonList(packageName)));
4491 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4492
4493 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4494 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4495
4496 // Attempt to set to empty list (which means no listener is whitelisted)
4497 mContext.binder.callingUid = adminUid;
4498 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004499 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004500 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4501
4502 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4503 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4504 }
4505
4506 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4507 // Set up a managed profile
4508 final int MANAGED_PROFILE_USER_ID = 15;
4509 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4510 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4511 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4512
4513 final String permittedListener = "some.package";
4514 setupPackageInPackageManager(
4515 permittedListener,
4516 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4517 /*appId=*/ 12345, /*flags=*/ 0);
4518
4519 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4520 admin1, Collections.singletonList(permittedListener)));
4521
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004522 // isNotificationListenerServicePermitted should throw if not called from System.
4523 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4524 () -> dpms.isNotificationListenerServicePermitted(
4525 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004526
4527 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4528 assertTrue(dpms.isNotificationListenerServicePermitted(
4529 permittedListener, MANAGED_PROFILE_USER_ID));
4530 }
4531
4532 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4533 throws Exception {
4534 // Set up a managed profile
4535 final int MANAGED_PROFILE_USER_ID = 15;
4536 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4537 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4538 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4539
4540 final String permittedListener = "permitted.package";
4541 int appId = 12345;
4542 setupPackageInPackageManager(
4543 permittedListener,
4544 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4545 appId, /*flags=*/ 0);
4546
4547 final String notPermittedListener = "not.permitted.package";
4548 setupPackageInPackageManager(
4549 notPermittedListener,
4550 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4551 ++appId, /*flags=*/ 0);
4552
4553 final String systemListener = "system.package";
4554 setupPackageInPackageManager(
4555 systemListener,
4556 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4557 ++appId, ApplicationInfo.FLAG_SYSTEM);
4558
4559 // By default all packages are allowed
4560 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4561
4562 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4563 assertTrue(dpms.isNotificationListenerServicePermitted(
4564 permittedListener, MANAGED_PROFILE_USER_ID));
4565 assertTrue(dpms.isNotificationListenerServicePermitted(
4566 notPermittedListener, MANAGED_PROFILE_USER_ID));
4567 assertTrue(dpms.isNotificationListenerServicePermitted(
4568 systemListener, MANAGED_PROFILE_USER_ID));
4569
4570 // Setting only one package in the whitelist
4571 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4572 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4573 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004574 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004575 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4576 assertEquals(1, permittedListeners.size());
4577 assertEquals(permittedListener, permittedListeners.get(0));
4578
4579 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4580 assertTrue(dpms.isNotificationListenerServicePermitted(
4581 permittedListener, MANAGED_PROFILE_USER_ID));
4582 assertFalse(dpms.isNotificationListenerServicePermitted(
4583 notPermittedListener, MANAGED_PROFILE_USER_ID));
4584 // System packages are always allowed (even if not in the whitelist)
4585 assertTrue(dpms.isNotificationListenerServicePermitted(
4586 systemListener, MANAGED_PROFILE_USER_ID));
4587
4588 // Setting an empty whitelist - only system listeners allowed
4589 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4590 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004591 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004592 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4593
4594 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4595 assertFalse(dpms.isNotificationListenerServicePermitted(
4596 permittedListener, MANAGED_PROFILE_USER_ID));
4597 assertFalse(dpms.isNotificationListenerServicePermitted(
4598 notPermittedListener, MANAGED_PROFILE_USER_ID));
4599 // System packages are always allowed (even if not in the whitelist)
4600 assertTrue(dpms.isNotificationListenerServicePermitted(
4601 systemListener, MANAGED_PROFILE_USER_ID));
4602
4603 // Setting a null whitelist - all listeners allowed
4604 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4605 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4606 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4607
4608 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4609 assertTrue(dpms.isNotificationListenerServicePermitted(
4610 permittedListener, MANAGED_PROFILE_USER_ID));
4611 assertTrue(dpms.isNotificationListenerServicePermitted(
4612 notPermittedListener, MANAGED_PROFILE_USER_ID));
4613 assertTrue(dpms.isNotificationListenerServicePermitted(
4614 systemListener, MANAGED_PROFILE_USER_ID));
4615 }
4616
4617 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4618 throws Exception {
4619 // Set up a managed profile
4620 final int MANAGED_PROFILE_USER_ID = 15;
4621 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4622 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4623 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4624
4625 final String nonSystemPackage = "non.system.package";
4626 int appId = 12345;
4627 setupPackageInPackageManager(
4628 nonSystemPackage,
4629 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4630 appId, /*flags=*/ 0);
4631
4632 final String systemListener = "system.package";
4633 setupPackageInPackageManager(
4634 systemListener,
4635 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4636 ++appId, ApplicationInfo.FLAG_SYSTEM);
4637
4638 // By default all packages are allowed (for all profiles)
4639 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4640
4641 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4642 assertTrue(dpms.isNotificationListenerServicePermitted(
4643 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4644 assertTrue(dpms.isNotificationListenerServicePermitted(
4645 systemListener, MANAGED_PROFILE_USER_ID));
4646 assertTrue(dpms.isNotificationListenerServicePermitted(
4647 nonSystemPackage, UserHandle.USER_SYSTEM));
4648 assertTrue(dpms.isNotificationListenerServicePermitted(
4649 systemListener, UserHandle.USER_SYSTEM));
4650
4651 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4652 // all allowed in primary profile
4653 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4654 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004655 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004656 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4657
4658 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4659 assertFalse(dpms.isNotificationListenerServicePermitted(
4660 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4661 assertTrue(dpms.isNotificationListenerServicePermitted(
4662 systemListener, MANAGED_PROFILE_USER_ID));
4663 assertTrue(dpms.isNotificationListenerServicePermitted(
4664 nonSystemPackage, UserHandle.USER_SYSTEM));
4665 assertTrue(dpms.isNotificationListenerServicePermitted(
4666 systemListener, UserHandle.USER_SYSTEM));
4667 }
4668
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004669 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004670 mServiceContext.packageName = mRealTestContext.getPackageName();
4671 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4672 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004673 setDeviceOwner();
4674
Pavel Grafov75c0a892017-05-18 17:28:27 +01004675 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004676 }
4677
4678 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004679 mServiceContext.packageName = mRealTestContext.getPackageName();
4680 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4681 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004682 setAsProfileOwner(admin1);
4683
Pavel Grafov75c0a892017-05-18 17:28:27 +01004684 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4685 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004686 }
4687
4688 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004689 mServiceContext.packageName = mRealTestContext.getPackageName();
4690 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4691 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004692 setAsProfileOwner(admin1);
4693
Pavel Grafov75c0a892017-05-18 17:28:27 +01004694 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4695 caller.packageName = "com.example.delegate";
4696 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4697 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004698
Pavel Grafov75c0a892017-05-18 17:28:27 +01004699 // Make caller a delegated cert installer.
4700 runAsCaller(mAdmin1Context, dpms,
4701 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004702
4703 verifyCanGetOwnerInstalledCaCerts(null, caller);
4704 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004705 }
4706
Rubin Xucc391c22018-01-02 20:37:35 +00004707 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004708 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4709 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004710 Bundle restriction = new Bundle();
4711 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4712
4713 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4714 RestrictionsListener listener = new RestrictionsListener(mContext);
4715 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4716 new Bundle());
4717 verifyDataSharingChangedBroadcast();
4718 }
4719
4720 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004721 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4722 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004723 Bundle restriction = new Bundle();
4724 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4725
4726 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4727 RestrictionsListener listener = new RestrictionsListener(mContext);
4728 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4729 restriction);
4730 verifyDataSharingChangedBroadcast();
4731 }
4732
4733 public void testDisallowSharingIntoProfileUnchanged() {
4734 RestrictionsListener listener = new RestrictionsListener(mContext);
4735 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4736 new Bundle());
4737 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4738 }
4739
4740 private void verifyDataSharingChangedBroadcast() {
4741 Intent expectedIntent = new Intent(
4742 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4743 expectedIntent.setPackage("com.android.managedprovisioning");
4744 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4745 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4746 MockUtils.checkIntent(expectedIntent),
4747 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4748 }
4749
yuemingwe3d9c092018-01-11 12:11:44 +00004750 public void testOverrideApnAPIsFailWithPO() throws Exception {
4751 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004752 ApnSetting apn = (new ApnSetting.Builder())
4753 .setApnName("test")
4754 .setEntryName("test")
4755 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4756 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004757 assertExpectException(SecurityException.class, null, () ->
4758 dpm.addOverrideApn(admin1, apn));
4759 assertExpectException(SecurityException.class, null, () ->
4760 dpm.updateOverrideApn(admin1, 0, apn));
4761 assertExpectException(SecurityException.class, null, () ->
4762 dpm.removeOverrideApn(admin1, 0));
4763 assertExpectException(SecurityException.class, null, () ->
4764 dpm.getOverrideApns(admin1));
4765 assertExpectException(SecurityException.class, null, () ->
4766 dpm.setOverrideApnsEnabled(admin1, false));
4767 assertExpectException(SecurityException.class, null, () ->
4768 dpm.isOverrideApnEnabled(admin1));
4769 }
4770
Robin Lee2c68dad2017-03-17 12:50:24 +00004771 private void verifyCanGetOwnerInstalledCaCerts(
4772 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004773 final String alias = "cert";
4774 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004775
4776 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004777 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004778 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4779 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004780 }
4781 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4782
4783 // caller: device admin or delegated certificate installer
4784 callerContext.applicationInfo = new ApplicationInfo();
4785 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4786
4787 // system_server
4788 final DpmMockContext serviceContext = mContext;
4789 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004790 getServices().addPackageContext(callerUser, admin1Context);
4791 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004792
4793 // Install a CA cert.
4794 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004795 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004796 .thenReturn(alias);
4797 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004798 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004799 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004800 });
4801
Pavel Grafov75c0a892017-05-18 17:28:27 +01004802 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4803 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4804 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004805 flushTasks();
4806
Robin Lee2c68dad2017-03-17 12:50:24 +00004807 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4808
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004809 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004810 runAsCaller(admin1Context, dpms, (dpm) -> {
4811 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004812 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004813 ownerInstalledCaCerts.addAll(installedCaCerts);
4814 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004815
4816 // Restarting the DPMS should not lose information.
4817 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004818 runAsCaller(admin1Context, dpms, (dpm) ->
4819 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004820
4821 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004822 runAsCaller(serviceContext, dpms, (dpm) -> {
4823 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004824
Robin Lee2c68dad2017-03-17 12:50:24 +00004825 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004826 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004827 });
4828
Pavel Grafov75c0a892017-05-18 17:28:27 +01004829 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4830 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4831 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004832 flushTasks();
4833
4834 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4835 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004836 runAsCaller(admin1Context, dpms, (dpm) -> {
4837 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4838 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004839 }
4840
Robin Lee2c68dad2017-03-17 12:50:24 +00004841 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4842 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004843 final String alias = "cert";
4844 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004845
4846 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004847 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004848 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4849 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004850 }
4851 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4852
4853 // caller: device admin or delegated certificate installer
4854 callerContext.applicationInfo = new ApplicationInfo();
4855 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4856
4857 // system_server
4858 final DpmMockContext serviceContext = mContext;
4859 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004860 getServices().addPackageContext(callerUser, admin1Context);
4861 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004862
4863 // Install a CA cert as caller
4864 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004865 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004866 .thenReturn(alias);
4867 assertTrue(dpm.installCaCert(callerName, caCert));
4868 });
4869
4870 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004871 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004872 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004873 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4874 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4875 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004876 flushTasks();
4877
Robin Lee2c68dad2017-03-17 12:50:24 +00004878 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004879 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004880
4881 runAsCaller(serviceContext, dpms, (dpm) -> {
4882 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4883 assertNotNull(ownerInstalledCaCerts);
4884 assertTrue(ownerInstalledCaCerts.isEmpty());
4885 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004886 }
4887
Eran Messeri94d56762017-12-21 20:50:54 +00004888 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4889 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4890 Arrays.sort(gotFlags);
4891 Arrays.sort(expectedFlags);
4892 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4893 }
4894
4895 public void testTranslationOfIdAttestationFlag() {
4896 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4897 int[] correspondingAttUtilsTypes = new int[]{
4898 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4899 AttestationUtils.ID_TYPE_MEID};
4900
4901 // Test translation of zero flags
4902 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4903
4904 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4905 // non-null array
4906 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4907
4908 // Test translation of a single flag
4909 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4910 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4911 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4912
4913 // Test translation of two flags
4914 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4915 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4916 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4917 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4918
4919 // Test translation of all three flags
4920 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4921 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4922 AttestationUtils.ID_TYPE_MEID});
4923 // Test translation of all three flags
4924 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4925 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4926 AttestationUtils.ID_TYPE_MEID});
4927 }
4928
arangelov08d534b2018-01-22 15:20:53 +00004929 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4930 setDeviceOwner();
4931 initializeDpms();
4932 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4933 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4934 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4935 }
4936
4937 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4938 DpmTestUtils.writeInputStreamToFile(
4939 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4940 getDeviceOwnerPoliciesFile());
4941 DpmTestUtils.writeInputStreamToFile(
4942 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4943 getDeviceOwnerFile());
4944 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4945 }
4946
4947 public void testRevertDeviceOwnership_deviceNotMigrated()
4948 throws Exception {
4949 DpmTestUtils.writeInputStreamToFile(
4950 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4951 getDeviceOwnerPoliciesFile());
4952 DpmTestUtils.writeInputStreamToFile(
4953 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4954 getDeviceOwnerFile());
4955 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4956 }
4957
4958 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4959 throws Exception {
4960 DpmTestUtils.writeInputStreamToFile(
4961 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4962 getDeviceOwnerPoliciesFile());
4963 DpmTestUtils.writeInputStreamToFile(
4964 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4965 getDeviceOwnerFile());
4966 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4967 }
4968
4969 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4970 setupProfileOwner();
4971 initializeDpms();
4972 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4973 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4974 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4975 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4976 }
4977
4978 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4979 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4980 UserHandle.USER_SYSTEM);
4981 DpmTestUtils.writeInputStreamToFile(
4982 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4983 getProfileOwnerPoliciesFile());
4984 DpmTestUtils.writeInputStreamToFile(
4985 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
4986 getProfileOwnerFile());
4987 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4988 }
4989
4990 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
4991 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4992 UserHandle.USER_SYSTEM);
4993 DpmTestUtils.writeInputStreamToFile(
4994 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4995 getProfileOwnerPoliciesFile());
4996 DpmTestUtils.writeInputStreamToFile(
4997 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4998 getProfileOwnerFile());
4999 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5000 }
5001
5002 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5003 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5004 UserHandle.USER_SYSTEM);
5005 DpmTestUtils.writeInputStreamToFile(
5006 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5007 getProfileOwnerPoliciesFile());
5008 DpmTestUtils.writeInputStreamToFile(
5009 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5010 getProfileOwnerFile());
5011 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5012 }
5013
Eran Messeribb271892018-10-17 18:27:50 +01005014 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5015 setupProfileOwner();
5016 configureContextForAccess(mContext, false);
5017
5018 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005019 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005020 }
5021
5022 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5023 setupProfileOwner();
5024 configureContextForAccess(mContext, false);
5025
5026 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005027 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005028 }
5029
5030 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5031 setupProfileOwner();
5032
5033 // This method will throw if the system context could not call
5034 // setProfileOwnerCanAccessDeviceIds successfully.
5035 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5036 }
5037
5038 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5039 when(context.spiedContext.checkCallingPermission(
5040 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5041 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5042 : PackageManager.PERMISSION_DENIED);
5043 }
5044
5045 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5046 setupProfileOwner();
5047
5048 final long ident = mServiceContext.binder.clearCallingIdentity();
5049 configureContextForAccess(mServiceContext, true);
5050
5051 mServiceContext.binder.callingUid =
5052 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5053 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5054 try {
5055 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005056 dpm.setProfileOwnerCanAccessDeviceIds(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005057 });
5058 } finally {
5059 mServiceContext.binder.restoreCallingIdentity(ident);
5060 }
5061 }
5062
5063 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5064 throws Exception {
5065 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5066 setupDeviceOwner();
5067 configureContextForAccess(mContext, false);
5068
5069 // Device owner should be allowed to request Device ID attestation.
5070 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5071 DpmMockContext.CALLER_SYSTEM_USER_UID);
5072
5073 // Another package must not be allowed to request Device ID attestation.
5074 assertExpectException(SecurityException.class, null,
5075 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5076 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5077 // Another component that is not the admin must not be allowed to request Device ID
5078 // attestation.
5079 assertExpectException(SecurityException.class, null,
5080 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5081 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5082 }
5083
5084 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5085 throws Exception {
5086 configureContextForAccess(mContext, false);
5087
5088 // Make sure a security exception is thrown if the device has no profile owner.
5089 assertExpectException(SecurityException.class, null,
5090 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5091 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5092
5093 setupProfileOwner();
5094 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5095
5096 // The profile owner is allowed to request Device ID attestation.
5097 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5098 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5099 DpmMockContext.CALLER_UID);
5100 // But not another package.
5101 assertExpectException(SecurityException.class, null,
5102 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5103 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5104 // Or another component which is not the admin.
5105 assertExpectException(SecurityException.class, null,
5106 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5107 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5108 }
5109
5110 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5111 final long ident = mServiceContext.binder.clearCallingIdentity();
5112
5113 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5114 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5115 try {
5116 runAsCaller(mServiceContext, dpms, action);
5117 } finally {
5118 mServiceContext.binder.restoreCallingIdentity(ident);
5119 }
5120 }
5121
5122 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5123 setupProfileOwner();
5124 markDelegatedCertInstallerAsInstalled();
5125
5126 // Configure a delegated cert installer.
5127 runAsCaller(mServiceContext, dpms,
5128 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5129 Arrays.asList(DELEGATION_CERT_INSTALL)));
5130
5131 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5132
5133 // Make sure that the profile owner can still request Device ID attestation.
5134 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5135 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5136 DpmMockContext.CALLER_UID);
5137
5138 runAsDelegatedCertInstaller(dpm -> {
5139 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5140 DpmMockContext.DELEGATE_PACKAGE_NAME,
5141 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5142 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5143 });
5144 }
5145
5146 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5147 throws Exception {
5148 setupProfileOwner();
5149 markDelegatedCertInstallerAsInstalled();
5150
5151 // Configure a delegated cert installer.
5152 runAsCaller(mServiceContext, dpms,
5153 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5154 Arrays.asList(DELEGATION_CERT_INSTALL)));
5155
5156
5157 assertExpectException(SecurityException.class, null,
5158 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5159 admin1.getPackageName(),
5160 DpmMockContext.CALLER_UID));
5161
5162 runAsDelegatedCertInstaller(dpm -> {
5163 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5164 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5165 DpmMockContext.DELEGATE_PACKAGE_NAME,
5166 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5167 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5168 });
5169 }
5170
Bernard Chaue9586552018-11-29 10:59:31 +00005171 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5172 assertThrows(SecurityException.class,
5173 () -> new DevicePolicyManagerTestable(
5174 mServiceContext,
5175 dpms,
5176 /* parentInstance= */ true)
5177 .getPasswordComplexity());
5178 }
5179
5180 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5181 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5182 .thenReturn(false);
5183 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5184 }
5185
5186 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5187 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5188 .thenReturn(true);
5189 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5190 }
5191
5192
5193 public void testGetPasswordComplexity_currentUserNoPassword() {
5194 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5195 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005196 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005197 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5198 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5199
5200 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5201 }
5202
5203 public void testGetPasswordComplexity_currentUserHasPassword() {
5204 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5205 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005206 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005207 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5208 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5209 dpms.mUserPasswordMetrics.put(
5210 DpmMockContext.CALLER_USER_HANDLE,
Rich Canningsf64ec632019-02-21 12:40:36 -08005211 PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005212
5213 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5214 }
5215
5216 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5217 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5218 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005219 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005220
5221 UserInfo parentUser = new UserInfo();
5222 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5223 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5224 .thenReturn(parentUser.id);
5225
5226 dpms.mUserPasswordMetrics.put(
5227 DpmMockContext.CALLER_USER_HANDLE,
Rich Canningsf64ec632019-02-21 12:40:36 -08005228 PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005229 dpms.mUserPasswordMetrics.put(
5230 parentUser.id,
Rich Canningsf64ec632019-02-21 12:40:36 -08005231 PasswordMetrics.computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005232
5233 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5234 }
5235
yuemingwd2bfbc82019-01-02 11:42:25 +00005236 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5237 setAsProfileOwner(admin1);
5238 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5239 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5240 }
5241
5242 public void testCrossProfileCalendarPackages_reopenDpms() {
5243 setAsProfileOwner(admin1);
5244 dpm.setCrossProfileCalendarPackages(admin1, null);
5245 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5246 assertTrue(packages == null);
5247 initializeDpms();
5248 packages = dpm.getCrossProfileCalendarPackages(admin1);
5249 assertTrue(packages == null);
5250
5251 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5252 packages = dpm.getCrossProfileCalendarPackages(admin1);
5253 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5254 initializeDpms();
5255 packages = dpm.getCrossProfileCalendarPackages(admin1);
5256 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5257
5258 final String dummyPackageName = "test";
5259 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5260 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5261 packages = dpm.getCrossProfileCalendarPackages(admin1);
5262 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5263 initializeDpms();
5264 packages = dpm.getCrossProfileCalendarPackages(admin1);
5265 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5266 }
5267
5268 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5269 assertTrue(expected != null);
5270 assertTrue(actual != null);
5271 assertTrue(expected.containsAll(actual));
5272 assertTrue(actual.containsAll(expected));
5273 }
5274
yuemingwdded98f2019-01-30 17:08:12 +00005275 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5276 setAsProfileOwner(admin1);
5277 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5278 when(getServices().settings.settingsSecureGetIntForUser(
5279 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5280 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5281 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5282 }
5283
5284 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5285 final String testPackage = "TEST_PACKAGE";
5286 setAsProfileOwner(admin1);
5287 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5288 when(getServices().settings.settingsSecureGetIntForUser(
5289 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5290 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5291 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5292 }
5293
5294 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5295 final String testPackage = "TEST_PACKAGE";
5296 setAsProfileOwner(admin1);
5297 dpm.setCrossProfileCalendarPackages(admin1, null);
5298 when(getServices().settings.settingsSecureGetIntForUser(
5299 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5300 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5301 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5302 }
5303
Eran Messeribb271892018-10-17 18:27:50 +01005304 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5305 final long ident = mServiceContext.binder.clearCallingIdentity();
5306 mServiceContext.binder.callingUid =
5307 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5308 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005309 dpm.setProfileOwnerCanAccessDeviceIds(who);
Eran Messeribb271892018-10-17 18:27:50 +01005310 });
5311 mServiceContext.binder.restoreCallingIdentity(ident);
5312 }
5313
arangelov08d534b2018-01-22 15:20:53 +00005314 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5315 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5316 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5317 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5318
5319 final long ident = mServiceContext.binder.clearCallingIdentity();
5320 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5321 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5322 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5323 // To simulate a reboot, we just reinitialize dpms and call systemReady
5324 initializeDpms();
5325
5326 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5327 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5328 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5329 assertTrue(dpm.isAdminActive(admin1));
5330 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5331 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5332
5333 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5334 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5335 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5336 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5337
5338 mServiceContext.binder.restoreCallingIdentity(ident);
5339 }
5340
5341 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5342 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5343 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5344 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5345
5346 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5347 DpmMockContext.CALLER_SYSTEM_USER_UID);
5348 setUpPackageManagerForAdmin(admin1, uid);
5349 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5350 // To simulate a reboot, we just reinitialize dpms and call systemReady
5351 initializeDpms();
5352
5353 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5354 assertTrue(dpm.isAdminActive(admin1));
5355 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5356 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5357 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5358 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5359 }
5360
5361 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5362 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5363 metadataManager.deleteMetadataFile();
5364
5365 final TransferOwnershipMetadataManager.Metadata metadata =
5366 new TransferOwnershipMetadataManager.Metadata(
5367 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5368 callerUserHandle,
5369 adminType);
5370 metadataManager.saveMetadataFile(metadata);
5371 }
5372
5373 private File getDeviceOwnerFile() {
5374 return dpms.mOwners.getDeviceOwnerFile();
5375 }
5376
5377 private File getProfileOwnerFile() {
5378 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5379 }
5380
5381 private File getProfileOwnerPoliciesFile() {
5382 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5383 DpmMockContext.CALLER_USER_HANDLE);
5384 return getPoliciesFile(parentDir);
5385 }
5386
5387 private File getDeviceOwnerPoliciesFile() {
5388 return getPoliciesFile(getServices().systemUserDataDir);
5389 }
5390
5391 private File getPoliciesFile(File parentDir) {
5392 return new File(parentDir, "device_policies.xml");
5393 }
5394
5395 private InputStream getRawStream(@RawRes int id) {
5396 return mRealTestContext.getResources().openRawResource(id);
5397 }
5398
Victor Chang3e794af2016-03-04 13:48:17 +00005399 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005400 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005401 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5402 dpms.notifyChangeToContentObserver(
5403 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5404 }
5405
5406 private void assertProvisioningAllowed(String action, boolean expected) {
5407 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5408 dpm.isProvisioningAllowed(action));
5409 }
Tony Mak2f26b792016-11-28 17:54:51 +00005410
Nicolas Prevot45d29072017-01-18 16:11:19 +00005411 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5412 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005413 final String previousPackageName = mContext.packageName;
5414 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005415
5416 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5417 mContext.packageName = packageName;
5418 mMockContext.binder.callingUid = uid;
5419 assertProvisioningAllowed(action, expected);
5420
5421 // Set the previous package name / calling uid to go back to the initial state.
5422 mContext.packageName = previousPackageName;
5423 mMockContext.binder.callingUid = previousUid;
5424 }
5425
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005426 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005427 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5428 }
5429
5430 private void assertCheckProvisioningPreCondition(
5431 String action, String packageName, int provisioningCondition) {
5432 assertEquals("checkProvisioningPreCondition("
5433 + action + ", " + packageName + ") returning unexpected result",
5434 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005435 }
5436
Tony Mak2f26b792016-11-28 17:54:51 +00005437 /**
5438 * Setup a managed profile with the specified admin and its uid.
5439 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5440 * @param adminUid uid of the admin package.
5441 * @param copyFromAdmin package information for {@code admin} will be built based on this
5442 * component's information.
5443 */
5444 private void addManagedProfile(
5445 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5446 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005447 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005448 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5449 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5450 dpm.setActiveAdmin(admin, false, userId);
5451 assertTrue(dpm.setProfileOwner(admin, null, userId));
5452 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5453 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005454
5455 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005456 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005457 */
Robin Leeabaa0692017-02-20 20:54:22 +00005458 private static StringParceledListSlice asSlice(String[] s) {
5459 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005460 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005461
5462 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005463 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5464 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005465
Robin Lee2c68dad2017-03-17 12:50:24 +00005466 // We can't let exceptions happen on the background thread. Throw them here if they happen
5467 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005468 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005469 }
Victor Chang3e794af2016-03-04 13:48:17 +00005470}