blob: aeccfc5310e93e7fb9ecd9804da7cfc44a5a7132 [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 Grafov6f334842019-08-06 14:37:06 +010028import static android.app.admin.PasswordMetrics.computeForPassword;
Pavel Grafov6a40f092016-10-25 15:46:51 +010029import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
30import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
31import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
32
Pavel Grafov6f334842019-08-06 14:37:06 +010033import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080034import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Eugene Susla4f8680b2017-08-07 17:25:30 -070035import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010036
Pavel Grafov75c0a892017-05-18 17:28:27 +010037import static org.mockito.Matchers.any;
38import static org.mockito.Matchers.anyInt;
39import static org.mockito.Matchers.anyLong;
40import static org.mockito.Matchers.anyObject;
41import static org.mockito.Matchers.anyString;
42import static org.mockito.Matchers.eq;
43import static org.mockito.Matchers.isNull;
44import static org.mockito.Mockito.atLeast;
Rubin Xu19854862019-08-15 16:37:23 +010045import static org.mockito.Mockito.atMost;
Pavel Grafov75c0a892017-05-18 17:28:27 +010046import static org.mockito.Mockito.doAnswer;
47import static org.mockito.Mockito.doReturn;
48import static org.mockito.Mockito.never;
49import static org.mockito.Mockito.nullable;
50import static org.mockito.Mockito.reset;
51import static org.mockito.Mockito.timeout;
52import static org.mockito.Mockito.times;
53import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080054import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010055import static org.mockito.Mockito.verifyZeroInteractions;
56import static org.mockito.Mockito.when;
57import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000058import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010059
Makoto Onukif76b06a2015-09-22 15:03:44 -070060import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000061import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070062import android.app.Activity;
Jonathan Scott367ebf42019-05-16 15:13:17 +010063import android.app.AppOpsManager;
Robin Lee7f5c91c2017-02-08 21:27:02 +000064import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070065import android.app.admin.DeviceAdminReceiver;
66import android.app.admin.DevicePolicyManager;
67import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010068import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070069import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070070import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000071import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000072import android.content.pm.ApplicationInfo;
73import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070074import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010075import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000076import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000077import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010078import android.graphics.Color;
79import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080080import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070081import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080082import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070083import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070084import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010085import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080086import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010087import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000088import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000089import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000090import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080091import android.test.MoreAsserts;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010092import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070093import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070094
Pavel Grafov57f1b662019-03-27 14:55:38 +000095import androidx.test.filters.SmallTest;
96
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010097import com.android.internal.R;
Rubin Xua58125d2019-09-06 20:11:48 +010098import com.android.internal.widget.LockscreenCredential;
Alan Treadwayafad8782016-01-19 15:15:08 +000099import com.android.server.LocalServices;
100import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +0000101import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +0000102import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +0000103
Robin Lee7f5c91c2017-02-08 21:27:02 +0000104import org.hamcrest.BaseMatcher;
105import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800106import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700107import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108
arangelov08d534b2018-01-22 15:20:53 +0000109import java.io.File;
110import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800111import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000112import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000113import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700114import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700116import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100117import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000118import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700119
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700120/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700121 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000122 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700123 m FrameworksServicesTests &&
124 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000125 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700126 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700127 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700128
129 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000130 *
131 * , or:
132 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700133 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000134@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100135@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700136public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000137 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
138 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
139 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100140 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800141 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100142 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000143
Pavel Grafov75c0a892017-05-18 17:28:27 +0100144 // TODO replace all instances of this with explicit {@link #mServiceContext}.
145 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700146 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100147
148 private DpmMockContext mServiceContext;
149 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700150 public DevicePolicyManager dpm;
151 public DevicePolicyManagerServiceTestable dpms;
152
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100153 /*
154 * The CA cert below is the content of cacert.pem as generated by:
155 *
156 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
157 */
158 private static final String TEST_CA =
159 "-----BEGIN CERTIFICATE-----\n" +
160 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
161 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
162 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
163 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
164 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
165 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
166 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
167 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
168 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
169 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
170 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
171 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
172 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
173 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
174 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
175 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
176 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
177 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
178 "wQ==\n" +
179 "-----END CERTIFICATE-----\n";
180
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700181 @Override
182 protected void setUp() throws Exception {
183 super.setUp();
184
185 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100186 mServiceContext = mContext;
187 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
188 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700189 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100190 doReturn(Collections.singletonList(new ResolveInfo()))
191 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
192 any(Intent.class),
193 anyInt(),
194 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700195
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800196 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100197 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800198
Makoto Onukia52562c2015-10-01 16:12:31 -0700199 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700200
Sudheer Shanka101c3532018-01-08 16:28:42 -0800201 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800202 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700203 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
204 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
205 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800206 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700207
Pavel Grafov75c0a892017-05-18 17:28:27 +0100208 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
209 mAdmin1Context.packageName = admin1.getPackageName();
210 mAdmin1Context.applicationInfo = new ApplicationInfo();
211 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
212
Makoto Onukib643fb02015-09-22 15:03:44 -0700213 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100214
215 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700216 }
217
arangelov08d534b2018-01-22 15:20:53 +0000218 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
219 return dpms.mTransferOwnershipMetadataManager;
220 }
221
Robin Lee2c68dad2017-03-17 12:50:24 +0000222 @Override
223 protected void tearDown() throws Exception {
224 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000225 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000226 super.tearDown();
227 }
228
Makoto Onukia52562c2015-10-01 16:12:31 -0700229 private void initializeDpms() {
230 // Need clearCallingIdentity() to pass permission checks.
231 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100232 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700233
Pavel Grafov75c0a892017-05-18 17:28:27 +0100234 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
235 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
236 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700237
Pavel Grafov75c0a892017-05-18 17:28:27 +0100238 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700239
Pavel Grafov75c0a892017-05-18 17:28:27 +0100240 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700241 }
242
Makoto Onukib643fb02015-09-22 15:03:44 -0700243 private void setUpUserManager() {
244 // Emulate UserManager.set/getApplicationRestriction().
245 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
246
247 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000248 doAnswer((Answer<Void>) invocation -> {
249 String pkg = (String) invocation.getArguments()[0];
250 Bundle bundle = (Bundle) invocation.getArguments()[1];
251 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700252
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000253 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700254
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000255 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100256 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100257 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700258
259 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000260 doAnswer((Answer<Bundle>) invocation -> {
261 String pkg = (String) invocation.getArguments()[0];
262 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700263
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000264 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100265 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700266 anyString(), any(UserHandle.class));
267
Makoto Onukid932f762015-09-29 16:53:38 -0700268 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100269 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700270 }
271
272 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100273 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700274
Pavel Grafov75c0a892017-05-18 17:28:27 +0100275 mServiceContext.binder.callingUid =
276 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
277 runAsCaller(mServiceContext, dpms, dpm -> {
278 // PO needs to be a DA.
279 dpm.setActiveAdmin(admin, /*replace=*/ false);
280 // Fire!
281 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
282 // Check
283 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
284 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700285
Pavel Grafov75c0a892017-05-18 17:28:27 +0100286 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700287 }
288
289 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100290 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700291 .thenReturn(false);
292
293 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100294 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700295
296 // If the device has no DPMS feature, it shouldn't register the local service.
297 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
298 }
299
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800300 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800301 // Device owner in SYSTEM_USER
302 setDeviceOwner();
303 // Profile owner in CALLER_USER_HANDLE
304 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
305 setAsProfileOwner(admin2);
306 // Active admin in CALLER_USER_HANDLE
307 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
308 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
309 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
310 DpmMockContext.CALLER_USER_HANDLE);
311 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
312 DpmMockContext.CALLER_USER_HANDLE));
313
314 initializeDpms();
315
316 // Verify
317 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800318 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800319 eq(UserHandle.USER_SYSTEM));
320 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800321 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800322 adminAnotherPackage.getPackageName()),
323 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800324 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
325 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
326 }
327
328 public void testLoadAdminData_noAdmins() throws Exception {
329 final int ANOTHER_USER_ID = 15;
330 getServices().addUser(ANOTHER_USER_ID, 0);
331
332 initializeDpms();
333
334 // Verify
335 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
336 null, DpmMockContext.CALLER_USER_HANDLE);
337 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
338 null, ANOTHER_USER_ID);
339 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
340 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800341 }
342
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700343 /**
344 * Caller doesn't have proper permissions.
345 */
346 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700347 // 1. Failure cases.
348
349 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100350 assertExpectException(SecurityException.class, /* messageRegex= */ null,
351 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700352
353 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
354 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100355
356 assertExpectException(SecurityException.class, /* messageRegex= */ null,
357 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700358 }
359
Makoto Onukif76b06a2015-09-22 15:03:44 -0700360 /**
361 * Test for:
362 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800363 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700364 * {@link DevicePolicyManager#isAdminActive}
365 * {@link DevicePolicyManager#isAdminActiveAsUser}
366 * {@link DevicePolicyManager#getActiveAdmins}
367 * {@link DevicePolicyManager#getActiveAdminsAsUser}
368 */
369 public void testSetActiveAdmin() throws Exception {
370 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700371 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
372
Makoto Onukif76b06a2015-09-22 15:03:44 -0700373 // 2. Call the API.
374 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700375
376 // 3. Verify internal calls.
377
378 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700379 verify(mContext.spiedContext).sendBroadcastAsUser(
380 MockUtils.checkIntentAction(
381 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
382 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
383 verify(mContext.spiedContext).sendBroadcastAsUser(
384 MockUtils.checkIntentAction(
385 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100386 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
387 eq(null),
388 any(Bundle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700389
Pavel Grafov75c0a892017-05-18 17:28:27 +0100390 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700391 eq(admin1.getPackageName()),
392 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
393 eq(PackageManager.DONT_KILL_APP),
394 eq(DpmMockContext.CALLER_USER_HANDLE),
395 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700396
Sudheer Shanka101c3532018-01-08 16:28:42 -0800397 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
398 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
399
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700400 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700401
402 // Make sure it's active admin1.
403 assertTrue(dpm.isAdminActive(admin1));
404 assertFalse(dpm.isAdminActive(admin2));
405 assertFalse(dpm.isAdminActive(admin3));
406
407 // But not admin1 for a different user.
408
409 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
410 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
411 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
412
413 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
414 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
415
416 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
417
418 // Next, add one more admin.
419 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700420 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700421 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700422
423 dpm.setActiveAdmin(admin2, /* replace =*/ false);
424
425 // Now we have two admins.
426 assertTrue(dpm.isAdminActive(admin1));
427 assertTrue(dpm.isAdminActive(admin2));
428 assertFalse(dpm.isAdminActive(admin3));
429
430 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
431 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100432 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700433 eq(admin1.getPackageName()),
434 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
435 eq(PackageManager.DONT_KILL_APP),
436 eq(DpmMockContext.CALLER_USER_HANDLE),
437 anyString());
438
Sudheer Shanka101c3532018-01-08 16:28:42 -0800439 // times(2) because it was previously called for admin1 which is in the same package
440 // as admin2.
441 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
442 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
443
Makoto Onukif76b06a2015-09-22 15:03:44 -0700444 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100445 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
446 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700447
448 // 5. Add the same admin1 again with replace, which should succeed.
449 dpm.setActiveAdmin(admin1, /* replace =*/ true);
450
451 // TODO make sure it's replaced.
452
453 // 6. Test getActiveAdmins()
454 List<ComponentName> admins = dpm.getActiveAdmins();
455 assertEquals(2, admins.size());
456 assertEquals(admin1, admins.get(0));
457 assertEquals(admin2, admins.get(1));
458
Sudheer Shanka101c3532018-01-08 16:28:42 -0800459 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
460 // replaced
461 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
462
Makoto Onukif76b06a2015-09-22 15:03:44 -0700463 // Another user has no admins.
464 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
465
466 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
467 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
468
469 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
470 }
471
Makoto Onukid932f762015-09-29 16:53:38 -0700472 public void testSetActiveAdmin_multiUsers() throws Exception {
473
474 final int ANOTHER_USER_ID = 100;
475 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
476
Pavel Grafov75c0a892017-05-18 17:28:27 +0100477 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700478
479 // Set up pacakge manager for the other user.
480 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700481
482 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
483
484 dpm.setActiveAdmin(admin1, /* replace =*/ false);
485
486 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
487 dpm.setActiveAdmin(admin2, /* replace =*/ false);
488
489
490 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
491 assertTrue(dpm.isAdminActive(admin1));
492 assertFalse(dpm.isAdminActive(admin2));
493
494 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
495 assertFalse(dpm.isAdminActive(admin1));
496 assertTrue(dpm.isAdminActive(admin2));
497 }
498
Makoto Onukif76b06a2015-09-22 15:03:44 -0700499 /**
500 * Test for:
501 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800502 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700503 */
504 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
505 // 1. Make sure the caller has proper permissions.
506 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
507
508 dpm.setActiveAdmin(admin1, /* replace =*/ false);
509 assertTrue(dpm.isAdminActive(admin1));
510
511 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100512 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
513 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700514 }
515
516 /**
517 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800518 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
519 * BIND_DEVICE_ADMIN.
520 */
521 public void testSetActiveAdmin_permissionCheck() throws Exception {
522 // 1. Make sure the caller has proper permissions.
523 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
524
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100525 assertExpectException(IllegalArgumentException.class,
526 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
527 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800528 assertFalse(dpm.isAdminActive(adminNoPerm));
529
530 // Change the target API level to MNC. Now it can be set as DA.
531 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
532 VERSION_CODES.M);
533 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
534 assertTrue(dpm.isAdminActive(adminNoPerm));
535
536 // TODO Test the "load from the file" case where DA will still be loaded even without
537 // BIND_DEVICE_ADMIN and target API is N.
538 }
539
540 /**
541 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700542 * {@link DevicePolicyManager#removeActiveAdmin}
543 */
544 public void testRemoveActiveAdmin_SecurityException() {
545 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
546
547 // Add admin.
548
549 dpm.setActiveAdmin(admin1, /* replace =*/ false);
550
551 assertTrue(dpm.isAdminActive(admin1));
552
553 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
554
555 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100556 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
557 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700558
559 // Try to remove active admin with a different caller userid should fail too, without
560 // having MANAGE_DEVICE_ADMINS.
561 mContext.callerPermissions.clear();
562
Makoto Onukid932f762015-09-29 16:53:38 -0700563 // Change the caller, and call into DPMS directly with a different user-id.
564
Makoto Onukif76b06a2015-09-22 15:03:44 -0700565 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100566 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
567 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700568 }
569
570 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800571 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
572 * (because we can't send the remove broadcast).
573 */
574 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
575 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
576
577 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
578
579 // Add admin.
580
581 dpm.setActiveAdmin(admin1, /* replace =*/ false);
582
583 assertTrue(dpm.isAdminActive(admin1));
584
585 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
586
587 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100588 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800589 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100590 assertExpectException(IllegalStateException.class,
591 /* messageRegex= */ "User must be running and unlocked",
592 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800593
594 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800595 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
596 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800597
598 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100599 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800600 .thenReturn(true);
601
602 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700603 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800604 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
605 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800606 }
607
608 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700609 * Test for:
610 * {@link DevicePolicyManager#removeActiveAdmin}
611 */
Makoto Onukid932f762015-09-29 16:53:38 -0700612 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700613 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
614
615 // Add admin1.
616
617 dpm.setActiveAdmin(admin1, /* replace =*/ false);
618
619 assertTrue(dpm.isAdminActive(admin1));
620 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
621
622 // Different user, but should work, because caller has proper permissions.
623 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700624
625 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700626 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700627
628 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700629 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800630 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
631 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700632
633 // TODO DO Still can't be removed in this case.
634 }
635
636 /**
637 * Test for:
638 * {@link DevicePolicyManager#removeActiveAdmin}
639 */
640 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
641 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
642 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
643
644 // Add admin1.
645
646 dpm.setActiveAdmin(admin1, /* replace =*/ false);
647
648 assertTrue(dpm.isAdminActive(admin1));
649 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
650
651 // Broadcast from saveSettingsLocked().
652 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
653 MockUtils.checkIntentAction(
654 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
655 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
656
657 // Remove. No permissions, but same user, so it'll work.
658 mContext.callerPermissions.clear();
659 dpm.removeActiveAdmin(admin1);
660
Makoto Onukif76b06a2015-09-22 15:03:44 -0700661 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
662 MockUtils.checkIntentAction(
663 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
664 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
665 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100666 eq(AppOpsManager.OP_NONE),
667 any(Bundle.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700668 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700669 eq(dpms.mHandler),
670 eq(Activity.RESULT_OK),
671 isNull(String.class),
672 isNull(Bundle.class));
673
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700674 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800675 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
676 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700677
678 // Again broadcast from saveSettingsLocked().
679 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
680 MockUtils.checkIntentAction(
681 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
682 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
683
684 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700685 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700686
Sudheer Shanka101c3532018-01-08 16:28:42 -0800687 public void testRemoveActiveAdmin_multipleAdminsInUser() {
688 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
689 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
690
691 // Add admin1.
692 dpm.setActiveAdmin(admin1, /* replace =*/ false);
693
694 assertTrue(dpm.isAdminActive(admin1));
695 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
696
697 // Add admin2.
698 dpm.setActiveAdmin(admin2, /* replace =*/ false);
699
700 assertTrue(dpm.isAdminActive(admin2));
701 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
702
703 // Broadcast from saveSettingsLocked().
704 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
705 MockUtils.checkIntentAction(
706 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
707 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
708
709 // Remove. No permissions, but same user, so it'll work.
710 mContext.callerPermissions.clear();
711 dpm.removeActiveAdmin(admin1);
712
713 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
714 MockUtils.checkIntentAction(
715 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
716 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
717 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100718 eq(AppOpsManager.OP_NONE),
719 any(Bundle.class),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800720 any(BroadcastReceiver.class),
721 eq(dpms.mHandler),
722 eq(Activity.RESULT_OK),
723 isNull(String.class),
724 isNull(Bundle.class));
725
726 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
727 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800728 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800729 eq(DpmMockContext.CALLER_USER_HANDLE));
730
731 // Again broadcast from saveSettingsLocked().
732 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
733 MockUtils.checkIntentAction(
734 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
735 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
736 }
737
738 /**
739 * Test for:
740 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
741 */
742 public void testForceRemoveActiveAdmin() throws Exception {
743 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
744
745 // Add admin.
746 setupPackageInPackageManager(admin1.getPackageName(),
747 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
748 /* appId= */ 10138,
749 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
750 dpm.setActiveAdmin(admin1, /* replace =*/ false);
751 assertTrue(dpm.isAdminActive(admin1));
752
753 // Calling from a non-shell uid should fail with a SecurityException
754 mContext.binder.callingUid = 123456;
755 assertExpectException(SecurityException.class,
756 /* messageRegex =*/ "Non-shell user attempted to call",
757 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
758
759 mContext.binder.callingUid = Process.SHELL_UID;
760 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
761
762 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
763 // Verify
764 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
765 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
766 null, DpmMockContext.CALLER_USER_HANDLE);
767 }
768
Makoto Onukib643fb02015-09-22 15:03:44 -0700769 /**
Alex Johnston9a6f4412019-09-16 16:05:18 +0100770 * Test for: {@link DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)}
771 *
772 * Validates that when the password history length is set, it is persisted after rebooting
773 */
774 public void testSaveAndLoadPasswordHistoryLength_persistedAfterReboot() throws Exception {
775 int passwordHistoryLength = 2;
776
777 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
778 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
779 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
780
781 // Install admin1 on system user.
782 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
783
784 // Set admin1 to active admin and device owner
785 dpm.setActiveAdmin(admin1, false);
786 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
787
788 // Save password history length
789 dpm.setPasswordHistoryLength(admin1, passwordHistoryLength);
790
791 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
792
793 initializeDpms();
794 reset(mContext.spiedContext);
795
796 // Password history length should persist after rebooted
797 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
798 }
799
800 /**
801 * Test for: {@link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000802 *
803 * Validates that when the password for a user changes, the notification broadcast intent
804 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
805 * addition to ones in the original user.
806 */
807 public void testSetActivePasswordState_sendToProfiles() throws Exception {
808 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
809
810 final int MANAGED_PROFILE_USER_ID = 78;
811 final int MANAGED_PROFILE_ADMIN_UID =
812 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
813
814 // Setup device owner.
815 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
816 mContext.packageName = admin1.getPackageName();
817 setupDeviceOwner();
818
819 // Add a managed profile belonging to the system user.
820 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
821
822 // Change the parent user's password.
823 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
824
825 // Both the device owner and the managed profile owner should receive this broadcast.
826 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
827 intent.setComponent(admin1);
828 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
829
830 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
831 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100832 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
833 eq(null),
834 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000835 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
836 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100837 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
838 eq(null),
839 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000840 }
841
842 /**
Rubin Xu19854862019-08-15 16:37:23 +0100843 * Test for: @{link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000844 *
845 * Validates that when the password for a managed profile changes, the notification broadcast
846 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
847 * its parent.
848 */
849 public void testSetActivePasswordState_notSentToParent() throws Exception {
850 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
851
852 final int MANAGED_PROFILE_USER_ID = 78;
853 final int MANAGED_PROFILE_ADMIN_UID =
854 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
855
856 // Setup device owner.
857 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
858 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100859 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000860 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
861 setupDeviceOwner();
862
863 // Add a managed profile belonging to the system user.
864 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
865
866 // Change the profile's password.
867 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
868
869 // Both the device owner and the managed profile owner should receive this broadcast.
870 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
871 intent.setComponent(admin1);
872 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
873
874 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
875 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100876 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
877 eq(null),
878 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000879 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
880 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100881 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
882 eq(null),
883 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000884 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100885
Robin Leed2a73ed2016-12-19 09:07:16 +0000886 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000887 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700888 */
889 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000890 setDeviceOwner();
891
892 // Try to set a profile owner on the same user, which should fail.
893 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
894 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100895 assertExpectException(IllegalStateException.class,
896 /* messageRegex= */ "already has a device owner",
897 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000898
899 // DO admin can't be deactivated.
900 dpm.removeActiveAdmin(admin1);
901 assertTrue(dpm.isAdminActive(admin1));
902
903 // TODO Test getDeviceOwnerName() too. To do so, we need to change
904 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
905 }
906
907 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700908 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800909 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700910 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
911 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
912
Makoto Onukid932f762015-09-29 16:53:38 -0700913 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700914 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
915
Makoto Onukid932f762015-09-29 16:53:38 -0700916 // Make sure admin1 is installed on system user.
917 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700918
Makoto Onukic8a5a552015-11-19 14:29:12 -0800919 // Check various get APIs.
920 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
921
Makoto Onukib643fb02015-09-22 15:03:44 -0700922 // DO needs to be an DA.
923 dpm.setActiveAdmin(admin1, /* replace =*/ false);
924
925 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700926 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700927
Makoto Onukic8a5a552015-11-19 14:29:12 -0800928 // getDeviceOwnerComponent should return the admin1 component.
929 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
930 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
931
932 // Check various get APIs.
933 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
934
935 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
936 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
937 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
938 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
939
940 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
941
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000942 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100943 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000944 eq(admin1.getPackageName()));
945
Makoto Onukib643fb02015-09-22 15:03:44 -0700946 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100947 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700948 eq(UserHandle.USER_SYSTEM), eq(false));
949
950 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
951 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
952 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
953
Makoto Onukic8a5a552015-11-19 14:29:12 -0800954 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700955 }
956
Makoto Onukic8a5a552015-11-19 14:29:12 -0800957 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
958 final int origCallingUser = mContext.binder.callingUid;
959 final List origPermissions = new ArrayList(mContext.callerPermissions);
960 mContext.callerPermissions.clear();
961
962 mContext.callerPermissions.add(permission.MANAGE_USERS);
963
964 mContext.binder.callingUid = Process.SYSTEM_UID;
965
966 // TODO Test getDeviceOwnerName() too. To do so, we need to change
967 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
968 if (hasDeviceOwner) {
969 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
970 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
971 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
972
973 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
974 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
975 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
976 } else {
977 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
978 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
979 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
980
981 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
982 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
983 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
984 }
985
986 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
987 if (hasDeviceOwner) {
988 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
989 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
990 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
991
992 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
993 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
994 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
995 } else {
996 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
997 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
998 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
999
1000 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1001 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1002 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1003 }
1004
1005 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1006 // Still with MANAGE_USERS.
1007 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1008 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1009 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1010
1011 if (hasDeviceOwner) {
1012 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1013 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1014 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1015 } else {
1016 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1017 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1018 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1019 }
1020
1021 mContext.binder.callingUid = Process.SYSTEM_UID;
1022 mContext.callerPermissions.remove(permission.MANAGE_USERS);
1023 // System can still call "OnAnyUser" without MANAGE_USERS.
1024 if (hasDeviceOwner) {
1025 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1026 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1027 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1028
1029 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1030 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1031 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1032 } else {
1033 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1034 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1035 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1036
1037 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1038 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1039 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1040 }
1041
1042 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1043 // Still no MANAGE_USERS.
1044 if (hasDeviceOwner) {
1045 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1046 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1047 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1048 } else {
1049 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1050 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1051 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1052 }
1053
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001054 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1055 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1056 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1057 dpm::getDeviceOwnerComponentOnAnyUser);
1058 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1059 dpm::getDeviceOwnerUserId);
1060 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1061 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001062
1063 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1064 // Still no MANAGE_USERS.
1065 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1066 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1067 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1068
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001069 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1070 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1071 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1072 dpm::getDeviceOwnerComponentOnAnyUser);
1073 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1074 dpm::getDeviceOwnerUserId);
1075 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1076 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001077
1078 // Restore.
1079 mContext.binder.callingUid = origCallingUser;
1080 mContext.callerPermissions.addAll(origPermissions);
1081 }
1082
1083
Makoto Onukib643fb02015-09-22 15:03:44 -07001084 /**
1085 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1086 */
1087 public void testSetDeviceOwner_noSuchPackage() {
1088 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001089 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001090 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1091 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1092
1093 // Call from a process on the system user.
1094 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1095
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001096 assertExpectException(IllegalArgumentException.class,
1097 /* messageRegex= */ "Invalid component",
1098 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001099 }
1100
1101 public void testSetDeviceOwner_failures() throws Exception {
1102 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1103 }
1104
Makoto Onukia52562c2015-10-01 16:12:31 -07001105 public void testClearDeviceOwner() throws Exception {
1106 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001107 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001108 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1109 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1110
1111 // Set admin1 as a DA to the secondary user.
1112 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1113
1114 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1115
1116 // Set admin 1 as the DO to the system user.
1117
1118 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1119 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1120 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1121 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1122
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001123 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001124 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001125 eq(admin1.getPackageName()));
1126
Makoto Onukic8a5a552015-11-19 14:29:12 -08001127 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001128
Makoto Onuki90b89652016-01-28 14:44:18 -08001129 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001130 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001131 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001132
1133 assertTrue(dpm.isAdminActive(admin1));
1134 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1135
Makoto Onukia52562c2015-10-01 16:12:31 -07001136 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001137 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001138
1139 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001140 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1141 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001142
1143 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001144 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001145 assertExpectException(IllegalStateException.class,
1146 /* messageRegex= */ "User must be running and unlocked",
1147 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001148
Pavel Grafov75c0a892017-05-18 17:28:27 +01001149 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1150 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001151 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1152
1153 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001154 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001155
Pavel Grafov75c0a892017-05-18 17:28:27 +01001156 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001157 eq(false),
1158 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1159
Pavel Grafov75c0a892017-05-18 17:28:27 +01001160 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001161 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001162 eq(null),
1163 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001164
Sudheer Shanka101c3532018-01-08 16:28:42 -08001165 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1166 null, UserHandle.USER_SYSTEM);
1167
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001168 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001169
1170 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1171 // and once for clearing it.
1172 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1173 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1174 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001175 // TODO Check other calls.
1176 }
1177
1178 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1179 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001180 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001181 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1182 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1183
1184 // Set admin1 as a DA to the secondary user.
1185 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1186
1187 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1188
1189 // Set admin 1 as the DO to the system user.
1190
1191 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1192 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1193 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1194 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1195
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001196 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001197 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001198 eq(admin1.getPackageName()));
1199
Makoto Onukic8a5a552015-11-19 14:29:12 -08001200 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001201
1202 // Now call clear from the secondary user, which should throw.
1203 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1204
1205 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001206 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001207 eq(admin1.getPackageName()),
1208 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001209 assertExpectException(SecurityException.class,
1210 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1211 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001212
Makoto Onukic8a5a552015-11-19 14:29:12 -08001213 // DO shouldn't be removed.
1214 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001215 }
1216
Alex Johnston63220932019-09-26 10:10:51 +01001217 /**
1218 * Test for: {@link DevicePolicyManager#clearDeviceOwnerApp(String)}
1219 *
1220 * Validates that when the device owner is removed, the reset password token is cleared
1221 */
1222 public void testClearDeviceOwner_clearResetPasswordToken() throws Exception {
1223 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1224 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1225 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1226
1227 // Install admin1 on system user
1228 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1229
1230 // Set admin1 to active admin and device owner
1231 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1232 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
1233
1234 // Add reset password token
1235 final long handle = 12000;
1236 final byte[] token = new byte[32];
1237 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
1238 nullable(EscrowTokenStateChangeCallback.class)))
1239 .thenReturn(handle);
1240 assertTrue(dpm.setResetPasswordToken(admin1, token));
1241
1242 // Assert reset password token is active
1243 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle),
1244 eq(UserHandle.USER_SYSTEM)))
1245 .thenReturn(true);
1246 assertTrue(dpm.isResetPasswordTokenActive(admin1));
1247
1248 // Remove the device owner
1249 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1250
1251 // Verify password reset password token was removed
1252 verify(getServices().lockPatternUtils).removeEscrowToken(eq(handle),
1253 eq(UserHandle.USER_SYSTEM));
1254 }
1255
Makoto Onukib643fb02015-09-22 15:03:44 -07001256 public void testSetProfileOwner() throws Exception {
1257 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001258
Makoto Onuki90b89652016-01-28 14:44:18 -08001259 // PO admin can't be deactivated.
1260 dpm.removeActiveAdmin(admin1);
1261 assertTrue(dpm.isAdminActive(admin1));
1262
Makoto Onuki803d6752015-10-30 12:58:39 -07001263 // Try setting DO on the same user, which should fail.
1264 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001265 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1266 runAsCaller(mServiceContext, dpms, dpm -> {
1267 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001268 assertExpectException(IllegalStateException.class,
1269 /* messageRegex= */ "already has a profile owner",
1270 () -> dpm.setDeviceOwner(admin2, "owner-name",
1271 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001272 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001273 }
1274
Makoto Onuki90b89652016-01-28 14:44:18 -08001275 public void testClearProfileOwner() throws Exception {
1276 setAsProfileOwner(admin1);
1277
1278 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1279
1280 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1281 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1282
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001283 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001284 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001285 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001286 assertExpectException(IllegalStateException.class,
1287 /* messageRegex= */ "User must be running and unlocked",
1288 () -> dpm.clearProfileOwner(admin1));
1289
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001290 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001291 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001292 dpm.clearProfileOwner(admin1);
1293
1294 // Check
1295 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001296 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001297 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1298 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001299 }
1300
Makoto Onukib643fb02015-09-22 15:03:44 -07001301 public void testSetProfileOwner_failures() throws Exception {
1302 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1303 }
1304
Makoto Onukia52562c2015-10-01 16:12:31 -07001305 public void testGetDeviceOwnerAdminLocked() throws Exception {
1306 checkDeviceOwnerWithMultipleDeviceAdmins();
1307 }
1308
1309 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1310 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1311 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1312 // make sure it gets the right component from the right user.
1313
1314 final int ANOTHER_USER_ID = 100;
1315 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1316
Pavel Grafov75c0a892017-05-18 17:28:27 +01001317 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001318
1319 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001320 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001321 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1322 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1323
1324 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1325
Pavel Grafov75c0a892017-05-18 17:28:27 +01001326 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001327
Makoto Onukia52562c2015-10-01 16:12:31 -07001328 // Make sure the admin packge is installed to each user.
1329 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1330 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1331
1332 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1333 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1334
1335 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1336
1337
1338 // Set active admins to the users.
1339 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1340 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1341
1342 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1343 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1344
1345 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1346
1347 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001348 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001349 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1350
Makoto Onukic8a5a552015-11-19 14:29:12 -08001351 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001352
1353 // Then check getDeviceOwnerAdminLocked().
1354 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1355 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1356 }
1357
1358 /**
1359 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001360 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1361 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001362 *
1363 * We didn't use to persist the DO component class name, but now we do, and the above method
1364 * finds the right component from a package name upon migration.
1365 */
1366 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001367 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001368 checkDeviceOwnerWithMultipleDeviceAdmins();
1369
1370 // Overwrite the device owner setting and clears the clas name.
1371 dpms.mOwners.setDeviceOwner(
1372 new ComponentName(admin2.getPackageName(), ""),
1373 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1374 dpms.mOwners.writeDeviceOwner();
1375
1376 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001377 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001378
1379 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001380 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001381 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001382 initializeDpms();
1383
1384 // Now the DO component name is a full name.
1385 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1386 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001387 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001388 }
1389
Makoto Onukib643fb02015-09-22 15:03:44 -07001390 public void testSetGetApplicationRestriction() {
1391 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001392 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001393
1394 {
1395 Bundle rest = new Bundle();
1396 rest.putString("KEY_STRING", "Foo1");
1397 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1398 }
1399
1400 {
1401 Bundle rest = new Bundle();
1402 rest.putString("KEY_STRING", "Foo2");
1403 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1404 }
1405
1406 {
1407 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1408 assertNotNull(returned);
1409 assertEquals(returned.size(), 1);
1410 assertEquals(returned.get("KEY_STRING"), "Foo1");
1411 }
1412
1413 {
1414 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1415 assertNotNull(returned);
1416 assertEquals(returned.size(), 1);
1417 assertEquals(returned.get("KEY_STRING"), "Foo2");
1418 }
1419
1420 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1421 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1422 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001423
Edman Anjosf9946772016-11-28 16:35:15 +01001424 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001425 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1426 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001427 *
1428 * @param packageName the name of the package to be setup
1429 * @param appId the application ID to be given to the package
1430 * @return the UID of the package as known by the mock package manager
1431 */
1432 private int setupPackageInPackageManager(final String packageName, final int appId)
1433 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001434 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001435 ApplicationInfo.FLAG_HAS_CODE);
1436 }
1437
1438 /**
1439 * Setup a package in the package manager mock. Useful for faking installed applications.
1440 *
1441 * @param packageName the name of the package to be setup
1442 * @param userId the user id where the package will be "installed"
1443 * @param appId the application ID to be given to the package
1444 * @param flags flags to set in the ApplicationInfo for this package
1445 * @return the UID of the package as known by the mock package manager
1446 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001447 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1448 int flags) throws Exception {
1449 final int uid = UserHandle.getUid(userId, appId);
1450 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001451 final PackageInfo pi = new PackageInfo();
1452 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001453 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001454 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001455 eq(packageName),
1456 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001457 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001458 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001459 eq(packageName),
1460 anyInt(),
1461 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001462 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001463 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001464 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001465 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001466 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001467 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001468 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001469 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001470 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001471 return uid;
1472 }
1473
Robin Lee7f5c91c2017-02-08 21:27:02 +00001474 public void testCertificateDisclosure() throws Exception {
1475 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1476 final UserHandle user = UserHandle.of(userId);
1477
1478 mContext.applicationInfo = new ApplicationInfo();
1479 mContext.callerPermissions.add(permission.MANAGE_USERS);
1480 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001481 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001482 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1483
Robin Leeabaa0692017-02-20 20:54:22 +00001484 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1485 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001486
1487 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1488 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1489
1490 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001491 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001492 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001493 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001494 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001495 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001496 .cancelAsUser(anyString(), anyInt(), eq(user));
1497
1498 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001499 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001500 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001501 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1502 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001503 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001504 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001505 .notifyAsUser(anyString(), anyInt(), argThat(
1506 new BaseMatcher<Notification>() {
1507 @Override
1508 public boolean matches(Object item) {
1509 final Notification noti = (Notification) item;
1510 return TEST_STRING.equals(
1511 noti.extras.getString(Notification.EXTRA_TITLE));
1512 }
1513 @Override
1514 public void describeTo(Description description) {
1515 description.appendText(
1516 "Notification{title=\"" + TEST_STRING + "\"}");
1517 }
1518 }), eq(user));
1519 }
1520
Edman Anjosf9946772016-11-28 16:35:15 +01001521 /**
1522 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1523 * privileges can acually be exercised by a delegate are not covered here.
1524 */
1525 public void testDelegation() throws Exception {
1526 setAsProfileOwner(admin1);
1527
1528 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1529
1530 // Given two packages
1531 final String CERT_DELEGATE = "com.delegate.certs";
1532 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1533 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1534 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1535 20989);
1536
1537 // On delegation
1538 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1539 mContext.packageName = admin1.getPackageName();
1540 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1541 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1542
1543 // DPMS correctly stores and retrieves the delegates
1544 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1545 assertEquals(2, policy.mDelegationMap.size());
1546 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1547 DELEGATION_CERT_INSTALL);
1548 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1549 DELEGATION_CERT_INSTALL);
1550 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1551 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1552 DELEGATION_APP_RESTRICTIONS);
1553 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1554 DELEGATION_APP_RESTRICTIONS);
1555 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1556
1557 // On calling install certificate APIs from an unauthorized process
1558 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1559 mContext.packageName = RESTRICTIONS_DELEGATE;
1560
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001561 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1562 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001563
1564 // On calling install certificate APIs from an authorized process
1565 mContext.binder.callingUid = CERT_DELEGATE_UID;
1566 mContext.packageName = CERT_DELEGATE;
1567
1568 // DPMS executes without a SecurityException
1569 try {
1570 dpm.installCaCert(null, null);
1571 } catch (SecurityException unexpected) {
1572 fail("Threw SecurityException on authorized access");
1573 } catch (NullPointerException expected) {
1574 }
1575
1576 // On removing a delegate
1577 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1578 mContext.packageName = admin1.getPackageName();
1579 dpm.setCertInstallerPackage(admin1, null);
1580
1581 // DPMS does not allow access to ex-delegate
1582 mContext.binder.callingUid = CERT_DELEGATE_UID;
1583 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001584 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1585 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001586
1587 // But still allows access to other existing delegates
1588 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1589 mContext.packageName = RESTRICTIONS_DELEGATE;
1590 try {
1591 dpm.getApplicationRestrictions(null, "pkg");
1592 } catch (SecurityException expected) {
1593 fail("Threw SecurityException on authorized access");
1594 }
1595 }
1596
Esteban Talaverabf60f722015-12-10 16:26:44 +00001597 public void testApplicationRestrictionsManagingApp() throws Exception {
1598 setAsProfileOwner(admin1);
1599
Rubin Xued1928a2016-02-11 17:23:06 +00001600 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001601 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001602 final String nonDelegateExceptionMessageRegex =
1603 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001604 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001605 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1606 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001607
Esteban Talaverabf60f722015-12-10 16:26:44 +00001608 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1609 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001610 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1611 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001612 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001613 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001614 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001615 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1616 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001617
1618 // Check via the profile owner that no restrictions were set.
1619 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001620 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001621 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1622
Rubin Xued1928a2016-02-11 17:23:06 +00001623 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001624 assertExpectException(PackageManager.NameNotFoundException.class,
1625 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1626 () -> dpm.setApplicationRestrictionsManagingPackage(
1627 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001628
Esteban Talaverabf60f722015-12-10 16:26:44 +00001629 // Let appRestrictionsManagerPackage manage app restrictions
1630 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1631 assertEquals(appRestrictionsManagerPackage,
1632 dpm.getApplicationRestrictionsManagingPackage(admin1));
1633
1634 // Now that package should be able to set and retrieve app restrictions.
1635 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001636 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001637 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1638 dpm.setApplicationRestrictions(null, "pkg1", rest);
1639 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1640 assertEquals(1, returned.size(), 1);
1641 assertEquals("Foo1", returned.get("KEY_STRING"));
1642
1643 // The same app running on a separate user shouldn't be able to manage app restrictions.
1644 mContext.binder.callingUid = UserHandle.getUid(
1645 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1646 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001647 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1648 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001649
1650 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1651 // too.
1652 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001653 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001654 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1655 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1656 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1657
1658 // Removing the ability for the package to manage app restrictions.
1659 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1660 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1661 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001662 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001663 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001664 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1665 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001666 }
1667
Makoto Onukia4f11972015-10-01 13:19:58 -07001668 public void testSetUserRestriction_asDo() throws Exception {
1669 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001670 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001671 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1672 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1673
1674 // First, set DO.
1675
1676 // Call from a process on the system user.
1677 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1678
1679 // Make sure admin1 is installed on system user.
1680 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001681
1682 // Call.
1683 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001684 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001685 UserHandle.USER_SYSTEM));
1686
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001687 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001688 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001689 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001690 DpmTestUtils.assertRestrictions(
1691 DpmTestUtils.newRestrictions(defaultRestrictions),
1692 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1693 );
1694 DpmTestUtils.assertRestrictions(
1695 DpmTestUtils.newRestrictions(defaultRestrictions),
1696 dpm.getUserRestrictions(admin1)
1697 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001698 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001699 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001700 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001701 eq(true) /* isDeviceOwner */,
1702 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001703 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001704 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001705
1706 for (String restriction : defaultRestrictions) {
1707 dpm.clearUserRestriction(admin1, restriction);
1708 }
1709
Esteban Talavera548a04b2016-12-20 15:22:30 +00001710 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001711 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001712
1713 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001714 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001716 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1717 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001718 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001719
Makoto Onukia4f11972015-10-01 13:19:58 -07001720 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001721 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001723 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1724 UserManager.DISALLOW_ADD_USER),
1725 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001726 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001727
Makoto Onuki068c54a2015-10-13 14:34:03 -07001728 DpmTestUtils.assertRestrictions(
1729 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001730 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001731 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1732 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001733 DpmTestUtils.assertRestrictions(
1734 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001735 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001736 dpm.getUserRestrictions(admin1)
1737 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001738
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001740 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001741 eq(UserHandle.USER_SYSTEM),
1742 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001743 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001744 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001745
Makoto Onuki068c54a2015-10-13 14:34:03 -07001746 DpmTestUtils.assertRestrictions(
1747 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1748 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1749 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001750 DpmTestUtils.assertRestrictions(
1751 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1752 dpm.getUserRestrictions(admin1)
1753 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001754
1755 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001756 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001757 eq(UserHandle.USER_SYSTEM),
1758 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001759 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001760 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001761
Esteban Talavera548a04b2016-12-20 15:22:30 +00001762 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001763
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001764 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1765 // DO sets them, the scope is global.
1766 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001767 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001768 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001769 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001770 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001771 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001772 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1773 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001774 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001775
1776 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1777 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001778 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001779
1780 // More tests.
1781 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001782 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001783 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001784 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1785 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001786 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001787
1788 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001789 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001790 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001791 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001792 UserManager.DISALLOW_ADD_USER),
1793 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001794 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001795
1796 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001797 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001798 eq(UserHandle.USER_SYSTEM),
1799 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001800 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001801 UserManager.DISALLOW_ADD_USER),
1802 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001803 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001804 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001805
Eric Sandnessca5969d2018-08-10 13:28:46 +01001806 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1807 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1808 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001809
Eric Sandnessca5969d2018-08-10 13:28:46 +01001810 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1811 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001812
Eric Sandnessca5969d2018-08-10 13:28:46 +01001813 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1814 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1815 () -> dpm.setCameraDisabled(admin1, true));
1816 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1817
1818 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1819 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1820 () -> dpm.setKeyguardDisabledFeatures(admin1,
1821 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1822 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1823
1824 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1825 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1826 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1827 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1828
1829 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1830 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1831 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1832 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001833 }
1834
1835 public void testSetUserRestriction_asPo() {
1836 setAsProfileOwner(admin1);
1837
Makoto Onuki068c54a2015-10-13 14:34:03 -07001838 DpmTestUtils.assertRestrictions(
1839 DpmTestUtils.newRestrictions(),
1840 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1841 .ensureUserRestrictions()
1842 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001843
1844 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001845 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001846 eq(DpmMockContext.CALLER_USER_HANDLE),
1847 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001848 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001849 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001850
Makoto Onukia4f11972015-10-01 13:19:58 -07001851 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001852 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001853 eq(DpmMockContext.CALLER_USER_HANDLE),
1854 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1855 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001856 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001857 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001858
Makoto Onuki068c54a2015-10-13 14:34:03 -07001859 DpmTestUtils.assertRestrictions(
1860 DpmTestUtils.newRestrictions(
1861 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1862 UserManager.DISALLOW_OUTGOING_CALLS
1863 ),
1864 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1865 .ensureUserRestrictions()
1866 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001867 DpmTestUtils.assertRestrictions(
1868 DpmTestUtils.newRestrictions(
1869 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1870 UserManager.DISALLOW_OUTGOING_CALLS
1871 ),
1872 dpm.getUserRestrictions(admin1)
1873 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001874
1875 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001876 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001877 eq(DpmMockContext.CALLER_USER_HANDLE),
1878 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001879 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001880 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001881
1882 DpmTestUtils.assertRestrictions(
1883 DpmTestUtils.newRestrictions(
1884 UserManager.DISALLOW_OUTGOING_CALLS
1885 ),
1886 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1887 .ensureUserRestrictions()
1888 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001889 DpmTestUtils.assertRestrictions(
1890 DpmTestUtils.newRestrictions(
1891 UserManager.DISALLOW_OUTGOING_CALLS
1892 ),
1893 dpm.getUserRestrictions(admin1)
1894 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001895
1896 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001897 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001898 eq(DpmMockContext.CALLER_USER_HANDLE),
1899 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001900 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001901 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001902
Makoto Onuki068c54a2015-10-13 14:34:03 -07001903 DpmTestUtils.assertRestrictions(
1904 DpmTestUtils.newRestrictions(),
1905 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1906 .ensureUserRestrictions()
1907 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001908 DpmTestUtils.assertRestrictions(
1909 DpmTestUtils.newRestrictions(),
1910 dpm.getUserRestrictions(admin1)
1911 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001912
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001913 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1914 // though when DO sets them they'll be applied globally.
1915 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001916 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001917 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001918 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001919 eq(DpmMockContext.CALLER_USER_HANDLE),
1920 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1921 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001922 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001923 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001924
1925 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001926 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001927 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001928 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001929 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001930 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001931 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001932
Makoto Onukia4f11972015-10-01 13:19:58 -07001933 // TODO Make sure restrictions are written to the file.
1934 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001935
Esteban Talavera548a04b2016-12-20 15:22:30 +00001936
1937 public void testDefaultEnabledUserRestrictions() throws Exception {
1938 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1939 mContext.callerPermissions.add(permission.MANAGE_USERS);
1940 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1941 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1942
1943 // First, set DO.
1944
1945 // Call from a process on the system user.
1946 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1947
1948 // Make sure admin1 is installed on system user.
1949 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1950
1951 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1952 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1953 UserHandle.USER_SYSTEM));
1954
1955 // Check that the user restrictions that are enabled by default are set. Then unset them.
1956 String[] defaultRestrictions = UserRestrictionsUtils
1957 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1958 assertTrue(defaultRestrictions.length > 0);
1959 DpmTestUtils.assertRestrictions(
1960 DpmTestUtils.newRestrictions(defaultRestrictions),
1961 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1962 );
1963 DpmTestUtils.assertRestrictions(
1964 DpmTestUtils.newRestrictions(defaultRestrictions),
1965 dpm.getUserRestrictions(admin1)
1966 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001967 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001968 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001969 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001970 eq(true) /* isDeviceOwner */,
1971 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001972 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001973 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001974
1975 for (String restriction : defaultRestrictions) {
1976 dpm.clearUserRestriction(admin1, restriction);
1977 }
1978
1979 assertNoDeviceOwnerRestrictions();
1980
1981 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001982 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001983 initializeDpms();
1984 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1985 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1986
1987 assertNoDeviceOwnerRestrictions();
1988
1989 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1990 // is set as it wasn't enabled during setDeviceOwner.
1991 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1992 assertFalse(UserRestrictionsUtils
1993 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1994 UserRestrictionsUtils
1995 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1996 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001997 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001998 initializeDpms();
1999 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2000 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2001
2002 DpmTestUtils.assertRestrictions(
2003 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
2004 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2005 );
2006 DpmTestUtils.assertRestrictions(
2007 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
2008 dpm.getUserRestrictions(admin1)
2009 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002010 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00002011 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00002012 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01002013 eq(true) /* isDeviceOwner */,
2014 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00002015 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002016 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002017
2018 // Remove the restriction.
2019 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
2020
2021 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
2022 initializeDpms();
2023 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2024 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2025 assertNoDeviceOwnerRestrictions();
2026 } finally {
2027 UserRestrictionsUtils
2028 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
2029 }
2030 }
2031
2032 private void assertNoDeviceOwnerRestrictions() {
2033 DpmTestUtils.assertRestrictions(
2034 DpmTestUtils.newRestrictions(),
2035 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2036 );
2037 DpmTestUtils.assertRestrictions(
2038 DpmTestUtils.newRestrictions(),
2039 dpm.getUserRestrictions(admin1)
2040 );
2041 }
2042
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002043 public void testGetMacAddress() throws Exception {
2044 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2045 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2046 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2047
2048 // In this test, change the caller user to "system".
2049 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2050
2051 // Make sure admin1 is installed on system user.
2052 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2053
2054 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002055 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
2056 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002057
2058 // DO needs to be an DA.
2059 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2060 assertTrue(dpm.isAdminActive(admin1));
2061
2062 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002063 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2064 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002065
2066 // Test 3. Caller has PO, but not DO.
2067 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002068 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2069 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002070
2071 // Remove PO.
2072 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002073 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002074 // Test 4, Caller is DO now.
2075 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2076
xshu425b9a62018-12-13 14:18:18 -08002077 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002078 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002079
xshu425b9a62018-12-13 14:18:18 -08002080 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2081 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002082 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002083
2084 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002085 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2086 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002087 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002088 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002089
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002090 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002091 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2092 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2093
2094 // In this test, change the caller user to "system".
2095 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2096
2097 // Make sure admin1 is installed on system user.
2098 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2099
2100 // Set admin1 as DA.
2101 dpm.setActiveAdmin(admin1, false);
2102 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002103 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2104 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002105
2106 // Set admin1 as PO.
2107 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002108 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2109 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002110
2111 // Remove PO and add DO.
2112 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002113 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002114 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2115
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002116 // admin1 is DO.
2117 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002118 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002119 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002120 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2121 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002122
2123 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002124 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002125 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002126 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2127 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002128
2129 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002130 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002131 dpm.reboot(admin1);
2132 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002133
2134 public void testSetGetSupportText() {
2135 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2136 dpm.setActiveAdmin(admin1, true);
2137 dpm.setActiveAdmin(admin2, true);
2138 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2139
2140 // Null default support messages.
2141 {
2142 assertNull(dpm.getLongSupportMessage(admin1));
2143 assertNull(dpm.getShortSupportMessage(admin1));
2144 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2145 assertNull(dpm.getShortSupportMessageForUser(admin1,
2146 DpmMockContext.CALLER_USER_HANDLE));
2147 assertNull(dpm.getLongSupportMessageForUser(admin1,
2148 DpmMockContext.CALLER_USER_HANDLE));
2149 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2150 }
2151
2152 // Only system can call the per user versions.
2153 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002154 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2155 () -> dpm.getShortSupportMessageForUser(admin1,
2156 DpmMockContext.CALLER_USER_HANDLE));
2157 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2158 () -> dpm.getLongSupportMessageForUser(admin1,
2159 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002160 }
2161
2162 // Can't set message for admin in another uid.
2163 {
2164 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002165 assertExpectException(SecurityException.class,
2166 /* messageRegex= */ "is not owned by uid",
2167 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002168 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2169 }
2170
2171 // Set/Get short returns what it sets and other admins text isn't changed.
2172 {
2173 final String supportText = "Some text to test with.";
2174 dpm.setShortSupportMessage(admin1, supportText);
2175 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2176 assertNull(dpm.getLongSupportMessage(admin1));
2177 assertNull(dpm.getShortSupportMessage(admin2));
2178
2179 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2180 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2181 DpmMockContext.CALLER_USER_HANDLE));
2182 assertNull(dpm.getShortSupportMessageForUser(admin2,
2183 DpmMockContext.CALLER_USER_HANDLE));
2184 assertNull(dpm.getLongSupportMessageForUser(admin1,
2185 DpmMockContext.CALLER_USER_HANDLE));
2186 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2187
2188 dpm.setShortSupportMessage(admin1, null);
2189 assertNull(dpm.getShortSupportMessage(admin1));
2190 }
2191
2192 // Set/Get long returns what it sets and other admins text isn't changed.
2193 {
2194 final String supportText = "Some text to test with.\nWith more text.";
2195 dpm.setLongSupportMessage(admin1, supportText);
2196 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2197 assertNull(dpm.getShortSupportMessage(admin1));
2198 assertNull(dpm.getLongSupportMessage(admin2));
2199
2200 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2201 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2202 DpmMockContext.CALLER_USER_HANDLE));
2203 assertNull(dpm.getLongSupportMessageForUser(admin2,
2204 DpmMockContext.CALLER_USER_HANDLE));
2205 assertNull(dpm.getShortSupportMessageForUser(admin1,
2206 DpmMockContext.CALLER_USER_HANDLE));
2207 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2208
2209 dpm.setLongSupportMessage(admin1, null);
2210 assertNull(dpm.getLongSupportMessage(admin1));
2211 }
2212 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002213
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002214 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002215 setAsProfileOwner(admin1);
2216
2217 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002218 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002219
2220 // Setup
2221 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2222 final String package1 = "com.example.one";
2223 final String package2 = "com.example.two";
2224 pkgsToRestrict.add(package1);
2225 pkgsToRestrict.add(package2);
2226 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2227 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002228 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002229
2230 // Verify
2231 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002232 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002233 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2234 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2235 eq(DpmMockContext.CALLER_USER_HANDLE));
2236
2237 // Setup
2238 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002239 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002240
2241 // Verify
2242 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002243 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002244 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2245 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2246 eq(DpmMockContext.CALLER_USER_HANDLE));
2247 }
2248
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002249 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002250 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2251 dpm.setActiveAdmin(admin1, true);
2252 assertTrue(dpm.isAdminActive(admin1));
2253 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2254
2255 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002256 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002257 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002258 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002259 }
2260
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002261 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002262 setAsProfileOwner(admin1);
2263
2264 // Setup
2265 final ArrayList<String> emptyList = new ArrayList<>();
2266 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2267 final String package1 = "com.example.one";
2268 final String package2 = "com.example.two";
2269 final String package3 = "com.example.three";
2270 pkgsToRestrict.add(package1);
2271 pkgsToRestrict.add(package2);
2272 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2273 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002274 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002275
2276 // Verify
2277 assertEquals(emptyList, excludedPkgs);
2278 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2279 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002280 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002281 DpmMockContext.CALLER_USER_HANDLE));
2282 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002283 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002284 DpmMockContext.CALLER_USER_HANDLE));
2285 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002286 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002287 DpmMockContext.CALLER_USER_HANDLE));
2288 }
2289
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002290 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002291 setAsProfileOwner(admin1);
2292 assertExpectException(SecurityException.class,
2293 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002294 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002295 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2296 dpm.clearProfileOwner(admin1);
2297
2298 setDeviceOwner();
2299 assertExpectException(SecurityException.class,
2300 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002301 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002302 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2303 clearDeviceOwner();
2304 }
2305
phweiss73145f42017-01-17 19:06:38 +01002306 public void testCreateAdminSupportIntent() throws Exception {
2307 // Setup device owner.
2308 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2309 setupDeviceOwner();
2310
2311 // Nonexisting permission returns null
2312 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2313 assertNull(intent);
2314
2315 // Existing permission that is not set returns null
2316 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2317 assertNull(intent);
2318
2319 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002320 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002321 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2322 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2323 .thenReturn(true);
2324 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2325 assertNull(intent);
2326
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002327 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2328 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2329 new UserManager.EnforcingUser(
2330 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2331 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002332 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002333 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002334 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2335 assertNotNull(intent);
2336 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2337 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2338 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002339 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002340 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2341 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2342
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002343 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2344 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002345
2346 // Camera is not disabled
2347 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2348 assertNull(intent);
2349
2350 // Camera is disabled
2351 dpm.setCameraDisabled(admin1, true);
2352 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2353 assertNotNull(intent);
2354 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2355 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2356
2357 // Screen capture is not disabled
2358 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2359 assertNull(intent);
2360
2361 // Screen capture is disabled
2362 dpm.setScreenCaptureDisabled(admin1, true);
2363 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2364 assertNotNull(intent);
2365 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2366 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2367
2368 // Same checks for different user
2369 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2370 // Camera should be disabled by device owner
2371 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2372 assertNotNull(intent);
2373 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2374 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2375 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2376 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2377 // ScreenCapture should not be disabled by device owner
2378 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2379 assertNull(intent);
2380 }
2381
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002382 /**
2383 * Test for:
2384 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002385 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002386 * {@link DevicePolicyManager#isAffiliatedUser}
2387 */
2388 public void testUserAffiliation() throws Exception {
2389 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2390 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2391 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2392
2393 // Check that the system user is unaffiliated.
2394 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2395 assertFalse(dpm.isAffiliatedUser());
2396
2397 // Set a device owner on the system user. Check that the system user becomes affiliated.
2398 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2399 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2400 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2401 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002402 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002403
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002404 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002405 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2406 setAsProfileOwner(admin2);
2407 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002408 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002409
2410 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2411 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002412 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002413 userAffiliationIds.add("red");
2414 userAffiliationIds.add("green");
2415 userAffiliationIds.add("blue");
2416 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002417 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002418 assertFalse(dpm.isAffiliatedUser());
2419
2420 // Have the device owner specify a set of affiliation ids that do not intersect with those
2421 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002422 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002423 deviceAffiliationIds.add("cyan");
2424 deviceAffiliationIds.add("yellow");
2425 deviceAffiliationIds.add("magenta");
2426 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2427 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002428 MoreAsserts.assertContentsInAnyOrder(
2429 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002430 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2431 assertFalse(dpm.isAffiliatedUser());
2432
2433 // Have the profile owner specify a set of affiliation ids that intersect with those
2434 // specified by the device owner. Check that the test user becomes affiliated.
2435 userAffiliationIds.add("yellow");
2436 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002437 MoreAsserts.assertContentsInAnyOrder(
2438 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002439 assertTrue(dpm.isAffiliatedUser());
2440
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002441 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002442 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002443 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002444 assertFalse(dpm.isAffiliatedUser());
2445
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002446 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2447 dpm.setAffiliationIds(admin2, userAffiliationIds);
2448 assertTrue(dpm.isAffiliatedUser());
2449 dpm.clearProfileOwner(admin2);
2450 assertFalse(dpm.isAffiliatedUser());
2451
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002452 // Check that the system user remains affiliated.
2453 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2454 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002455
2456 // Clear the device owner - the user becomes unaffiliated.
2457 clearDeviceOwner();
2458 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002459 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002460
2461 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002462 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002463 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2464 }
2465
2466 public void testSetUserProvisioningState_permission() throws Exception {
2467 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002468
2469 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2470 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2471 }
2472
2473 public void testSetUserProvisioningState_unprivileged() throws Exception {
2474 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002475 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2476 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2477 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002478 }
2479
2480 public void testSetUserProvisioningState_noManagement() {
2481 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002482 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002483 assertExpectException(IllegalStateException.class,
2484 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2485 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2486 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002487 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2488 }
2489
2490 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2491 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2492 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002493
2494 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2495 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2496 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2497 }
2498
2499 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2500 throws Exception {
2501 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2502 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002503
2504 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2505 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2506 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2507 }
2508
2509 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2510 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2511 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002512
2513 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2514 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2515 }
2516
2517 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2518 throws Exception {
2519 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002520
2521 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2522 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2523 DevicePolicyManager.STATE_USER_UNMANAGED);
2524 }
2525
2526 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2527 throws Exception {
2528 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002529
2530 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2531 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2532 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2533 }
2534
2535 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2536 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002537
2538 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2539 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2540 }
2541
2542 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2543 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002544
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002545 assertExpectException(IllegalStateException.class,
2546 /* messageRegex= */ "Cannot move to user provisioning state",
2547 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2548 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2549 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002550 }
2551
2552 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2553 throws Exception {
2554 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002555
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002556 assertExpectException(IllegalStateException.class,
2557 /* messageRegex= */ "Cannot move to user provisioning state",
2558 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2559 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2560 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002561 }
2562
2563 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002564 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2565 mContext.callerPermissions.add(permission.MANAGE_USERS);
2566
Alan Treadwayafad8782016-01-19 15:15:08 +00002567 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2568 for (int state : states) {
2569 dpm.setUserProvisioningState(state, userId);
2570 assertEquals(state, dpm.getUserProvisioningState());
2571 }
2572 }
2573
2574 private void setupProfileOwner() throws Exception {
2575 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2576
2577 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2578 dpm.setActiveAdmin(admin1, false);
2579 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2580
2581 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2582 }
2583
2584 private void setupDeviceOwner() throws Exception {
2585 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2586
2587 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2588 dpm.setActiveAdmin(admin1, false);
2589 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2590
2591 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2592 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002593
2594 public void testSetMaximumTimeToLock() {
2595 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2596
2597 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2598 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2599
Pavel Grafov75c0a892017-05-18 17:28:27 +01002600 reset(getServices().powerManagerInternal);
2601 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002602
2603 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002604 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2605 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002606 reset(getServices().powerManagerInternal);
2607 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002608
2609 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002610 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2611 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002612 reset(getServices().powerManagerInternal);
2613 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002614
2615 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002616 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2617 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002618 reset(getServices().powerManagerInternal);
2619 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002620
2621 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002622 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2623 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002624 reset(getServices().powerManagerInternal);
2625 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002626
2627 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002628 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2629 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002630 reset(getServices().powerManagerInternal);
2631 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002632
2633 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002634 reset(getServices().powerManagerInternal);
2635 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002636
Pavel Grafov28939982017-10-03 15:11:52 +01002637 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2638 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2639 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002640 reset(getServices().powerManagerInternal);
2641 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002642
2643 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002644 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2645 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002646 reset(getServices().powerManagerInternal);
2647 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002648
Pavel Grafov28939982017-10-03 15:11:52 +01002649 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002650 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002651 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2652 verifyStayOnWhilePluggedCleared(false);
2653 }
2654
Varun Shahb472b8f2019-09-23 23:01:06 -07002655 public void testIsActiveSupervisionApp() throws Exception {
2656 when(mServiceContext.resources
2657 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
2658 .thenReturn(admin1.flattenToString());
2659
2660 final int PROFILE_USER = 15;
2661 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2662 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2663 mContext.binder.callingUid = PROFILE_ADMIN;
2664
2665 final DevicePolicyManagerInternal dpmi =
2666 LocalServices.getService(DevicePolicyManagerInternal.class);
2667 assertTrue(dpmi.isActiveSupervisionApp(PROFILE_ADMIN));
2668 }
2669
Pavel Grafov28939982017-10-03 15:11:52 +01002670 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2671 // uses separate challenge.
2672 public void testSetMaximumTimeToLockProfile() throws Exception {
2673 final int PROFILE_USER = 15;
2674 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2675 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2676 mContext.binder.callingUid = PROFILE_ADMIN;
2677 final DevicePolicyManagerInternal dpmi =
2678 LocalServices.getService(DevicePolicyManagerInternal.class);
2679
2680 dpm.setMaximumTimeToLock(admin1, 0);
2681
2682 reset(getServices().powerManagerInternal);
2683 reset(getServices().settings);
2684
2685 // First add timeout for the profile.
2686 dpm.setMaximumTimeToLock(admin1, 10);
2687 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2688
2689 reset(getServices().powerManagerInternal);
2690 reset(getServices().settings);
2691
2692 // Add separate challenge
2693 when(getServices().lockPatternUtils
2694 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2695 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2696
2697 verifyScreenTimeoutCall(10L, PROFILE_USER);
2698 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2699
2700 reset(getServices().powerManagerInternal);
2701 reset(getServices().settings);
2702
2703 // Remove the timeout.
2704 dpm.setMaximumTimeToLock(admin1, 0);
2705 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2706 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2707
2708 reset(getServices().powerManagerInternal);
2709 reset(getServices().settings);
2710
2711 // Add it back.
2712 dpm.setMaximumTimeToLock(admin1, 10);
2713 verifyScreenTimeoutCall(10L, PROFILE_USER);
2714 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2715
2716 reset(getServices().powerManagerInternal);
2717 reset(getServices().settings);
2718
2719 // Remove separate challenge.
2720 reset(getServices().lockPatternUtils);
2721 when(getServices().lockPatternUtils
2722 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2723 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002724 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002725
2726 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2727 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2728
2729 reset(getServices().powerManagerInternal);
2730 reset(getServices().settings);
2731
2732 // Remove the timeout.
2733 dpm.setMaximumTimeToLock(admin1, 0);
2734 verifyScreenTimeoutCall(null, PROFILE_USER);
2735 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002736 }
2737
Michal Karpinski943aabd2016-10-06 11:09:25 +01002738 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2739 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2740 setupDeviceOwner();
2741 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2742
Michal Karpinskid084ca52017-01-18 15:54:18 +00002743 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2744 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2745 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2746 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2747 - ONE_MINUTE;
2748
2749 // verify that the minimum timeout cannot be modified on user builds (system property is
2750 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002751 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002752
2753 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2754 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2755 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2756
Pavel Grafov75c0a892017-05-18 17:28:27 +01002757 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002758
2759 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002760 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002761
Michal Karpinskid084ca52017-01-18 15:54:18 +00002762 // reset to default (0 means the admin is not participating, so default should be returned)
2763 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002764
2765 // aggregation should be the default if unset by any admin
2766 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2767 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2768
2769 // admin not participating by default
2770 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2771
2772 //clamping from the top
2773 dpm.setRequiredStrongAuthTimeout(admin1,
2774 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2775 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2776 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2777 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2778 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2779
Michal Karpinskid084ca52017-01-18 15:54:18 +00002780 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002781 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2782 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2783 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2784 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2785
2786 // clamping from the bottom
2787 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2788 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2789 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2790
Michal Karpinskid084ca52017-01-18 15:54:18 +00002791 // values within range
2792 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2793 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2794 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2795
2796 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2797 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2798 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002799
2800 // reset to default
2801 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2802 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2803 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2804 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2805
2806 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002807 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2808 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002809 }
2810
Pavel Grafov28939982017-10-03 15:11:52 +01002811 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002812 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002813 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002814 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002815 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002816 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002817 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002818 }
Pavel Grafov28939982017-10-03 15:11:52 +01002819 }
2820
2821 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002822 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2823 // UnfinishedVerificationException.
2824 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002825
Esteban Talavera01576862016-12-15 11:16:44 +00002826 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002827 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002828 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002829 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002830 .thenReturn(false);
2831 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002832 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2833 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002834 .thenReturn(true);
2835 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2836
2837 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002838 }
Victor Chang3e794af2016-03-04 13:48:17 +00002839
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002840 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2841 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002842 mContext.packageName = admin1.getPackageName();
2843 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002844 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2845 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2846 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2847 false);
2848 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2849 }
2850
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002851 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2852 setup_DeviceAdminFeatureOff();
2853 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2854 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2855 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2856 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2857 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2858 assertCheckProvisioningPreCondition(
2859 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2860 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2861 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2862 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2863 }
2864
Esteban Talavera01576862016-12-15 11:16:44 +00002865 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002866 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002867 .thenReturn(false);
2868 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002869 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2870 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002871 .thenReturn(true);
2872 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2873
2874 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002875 }
Victor Chang3e794af2016-03-04 13:48:17 +00002876
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002877 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2878 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002879 mContext.packageName = admin1.getPackageName();
2880 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002881 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2882 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2883 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2884 false);
2885 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2886
2887 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002888 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002889 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2890 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2891 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2892 true);
2893 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2894 }
2895
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002896 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2897 setup_ManagedProfileFeatureOff();
2898 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2899 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2900 DevicePolicyManager.CODE_OK);
2901 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2902 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2903 assertCheckProvisioningPreCondition(
2904 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2905 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2906 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2907 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2908
2909 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002910 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002911 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2912 DevicePolicyManager.CODE_OK);
2913 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2914 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2915 assertCheckProvisioningPreCondition(
2916 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2917 DevicePolicyManager.CODE_OK);
2918 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2919 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2920 }
2921
Esteban Talavera01576862016-12-15 11:16:44 +00002922 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002923 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002924 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002925 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2926 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002927 .thenReturn(true);
2928 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2929
2930 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002931 }
Victor Chang3e794af2016-03-04 13:48:17 +00002932
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002933 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2934 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002935 mContext.packageName = admin1.getPackageName();
2936 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002937 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2938 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2939 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2940 false /* because of non-split user */);
2941 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2942 false /* because of non-split user */);
2943 }
2944
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002945 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002946 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002947 setup_nonSplitUser_firstBoot_primaryUser();
2948 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2949 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2950 DevicePolicyManager.CODE_OK);
2951 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2952 DevicePolicyManager.CODE_OK);
2953 assertCheckProvisioningPreCondition(
2954 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2955 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2956 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2957 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2958 }
2959
Esteban Talavera01576862016-12-15 11:16:44 +00002960 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002961 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002962 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002963 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2964 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002965 .thenReturn(true);
2966 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2967
2968 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002969 }
Victor Chang3e794af2016-03-04 13:48:17 +00002970
Nicolas Prevot45d29072017-01-18 16:11:19 +00002971 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2972 setDeviceOwner();
2973 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2974 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2975 }
2976
2977 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2978 setup_nonSplitUser_withDo_primaryUser();
2979 final int MANAGED_PROFILE_USER_ID = 18;
2980 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2981 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002982 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002983 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002984 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002985 true)).thenReturn(true);
2986 }
2987
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002988 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2989 throws Exception {
2990 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002991 mContext.packageName = admin1.getPackageName();
2992 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002993 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2994 false/* because of completed device setup */);
2995 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2996 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2997 false/* because of non-split user */);
2998 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2999 false/* because of non-split user */);
3000 }
3001
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003002 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
3003 throws Exception {
3004 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3005 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3006 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3007 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3008 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3009 DevicePolicyManager.CODE_OK);
3010 assertCheckProvisioningPreCondition(
3011 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3012 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3013 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3014 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3015 }
3016
Nicolas Prevot45d29072017-01-18 16:11:19 +00003017 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
3018 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003019 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00003020 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3021
3022 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3023 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003024 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003025
3026 // COMP mode is allowed.
3027 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3028 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003029 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003030
Nicolas Prevot45d29072017-01-18 16:11:19 +00003031 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00003032 assertCheckProvisioningPreCondition(
3033 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003034 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003035 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003036 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3037 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3038 }
Esteban Talavera01576862016-12-15 11:16:44 +00003039
Nicolas Prevot45d29072017-01-18 16:11:19 +00003040 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
3041 setup_nonSplitUser_withDo_primaryUser();
3042 mContext.packageName = admin1.getPackageName();
3043 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3044 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
3045 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003046 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003047 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3048 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3049 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003050 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003051 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3052 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3053 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3054 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3055 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003056 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003057 assertCheckProvisioningPreCondition(
3058 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003059 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003060 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003061 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3062 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3063 }
Esteban Talavera01576862016-12-15 11:16:44 +00003064
Nicolas Prevot45d29072017-01-18 16:11:19 +00003065 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
3066 throws Exception {
3067 setup_nonSplitUser_withDo_primaryUser();
3068 mContext.packageName = admin1.getPackageName();
3069 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003070 // The DO should not be allowed to initiate provisioning if the restriction is set by
3071 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003072 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003073 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3074 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3075 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003076 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003077 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3078 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3079 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3080 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3081 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003082 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3083
3084 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003085 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003086 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003087 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003088 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3089 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3090 }
3091
3092 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
3093 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3094 mContext.packageName = admin1.getPackageName();
3095 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3096
3097 // We can delete the managed profile to create a new one, so provisioning is allowed.
3098 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3099 DevicePolicyManager.CODE_OK);
3100 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3101 assertCheckProvisioningPreCondition(
3102 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3103 DpmMockContext.ANOTHER_PACKAGE_NAME,
3104 DevicePolicyManager.CODE_OK);
3105 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3106 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3107 }
3108
3109 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3110 throws Exception {
3111 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3112 mContext.packageName = admin1.getPackageName();
3113 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003114 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003115 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3116 eq(UserHandle.SYSTEM)))
3117 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003118 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003119 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3120 eq(UserHandle.SYSTEM)))
3121 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003122
3123 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003124 assertCheckProvisioningPreCondition(
3125 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3126 DpmMockContext.ANOTHER_PACKAGE_NAME,
3127 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3128 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3129 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003130
3131 // But the device owner can still do it because it has set the restriction itself.
3132 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3133 DevicePolicyManager.CODE_OK);
3134 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003135 }
3136
3137 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003138 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003139 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003140 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3141 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003142 .thenReturn(false);
3143 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3144
3145 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003146 }
Victor Chang3e794af2016-03-04 13:48:17 +00003147
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003148 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3149 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003150 mContext.packageName = admin1.getPackageName();
3151 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003152 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3153 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3154 false /* because canAddMoreManagedProfiles returns false */);
3155 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3156 true);
3157 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3158 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003159 }
3160
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003161 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3162 throws Exception {
3163 setup_splitUser_firstBoot_systemUser();
3164 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3165 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3166 DevicePolicyManager.CODE_OK);
3167 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003168 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003169 assertCheckProvisioningPreCondition(
3170 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3171 DevicePolicyManager.CODE_OK);
3172 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3173 DevicePolicyManager.CODE_SYSTEM_USER);
3174 }
3175
Esteban Talavera01576862016-12-15 11:16:44 +00003176 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003177 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003178 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003179 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3180 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003181 .thenReturn(false);
3182 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3183
3184 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003185 }
Victor Chang3e794af2016-03-04 13:48:17 +00003186
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003187 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3188 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003189 mContext.packageName = admin1.getPackageName();
3190 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003191 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3192 true/* it's undefined behavior. Can be changed into false in the future */);
3193 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3194 false /* because canAddMoreManagedProfiles returns false */);
3195 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3196 true/* it's undefined behavior. Can be changed into false in the future */);
3197 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3198 false/* because calling uid is system user */);
3199 }
3200
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003201 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3202 throws Exception {
3203 setup_splitUser_afterDeviceSetup_systemUser();
3204 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3205 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3206 DevicePolicyManager.CODE_OK);
3207 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003208 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003209 assertCheckProvisioningPreCondition(
3210 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3211 DevicePolicyManager.CODE_OK);
3212 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3213 DevicePolicyManager.CODE_SYSTEM_USER);
3214 }
3215
Esteban Talavera01576862016-12-15 11:16:44 +00003216 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003217 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003218 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003219 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3220 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003221 true)).thenReturn(true);
3222 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3223
3224 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003225 }
Victor Chang3e794af2016-03-04 13:48:17 +00003226
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003227 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3228 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003229 mContext.packageName = admin1.getPackageName();
3230 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003231 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3232 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3233 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3234 true);
3235 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003236 }
3237
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003238 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003239 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003240 setup_splitUser_firstBoot_primaryUser();
3241 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3242 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3243 DevicePolicyManager.CODE_OK);
3244 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3245 DevicePolicyManager.CODE_OK);
3246 assertCheckProvisioningPreCondition(
3247 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3248 DevicePolicyManager.CODE_OK);
3249 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3250 DevicePolicyManager.CODE_OK);
3251 }
3252
Esteban Talavera01576862016-12-15 11:16:44 +00003253 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003254 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003255 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003256 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3257 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003258 true)).thenReturn(true);
3259 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3260
3261 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003262 }
Victor Chang3e794af2016-03-04 13:48:17 +00003263
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003264 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3265 throws Exception {
3266 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003267 mContext.packageName = admin1.getPackageName();
3268 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003269 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3270 true/* it's undefined behavior. Can be changed into false in the future */);
3271 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3272 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3273 true/* it's undefined behavior. Can be changed into false in the future */);
3274 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3275 false/* because user setup completed */);
3276 }
3277
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003278 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003279 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003280 setup_splitUser_afterDeviceSetup_primaryUser();
3281 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3282 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3283 DevicePolicyManager.CODE_OK);
3284 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3285 DevicePolicyManager.CODE_OK);
3286 assertCheckProvisioningPreCondition(
3287 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3288 DevicePolicyManager.CODE_OK);
3289 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3290 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3291 }
3292
Esteban Talavera01576862016-12-15 11:16:44 +00003293 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003294 setDeviceOwner();
3295
Pavel Grafov75c0a892017-05-18 17:28:27 +01003296 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003297 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003298 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3299 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003300 .thenReturn(false);
3301 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3302
3303 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003304 }
Victor Chang3e794af2016-03-04 13:48:17 +00003305
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003306 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3307 throws Exception {
3308 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003309 mContext.packageName = admin1.getPackageName();
3310 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003311 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3312 false /* can't provision managed profile on system user */);
3313 }
3314
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003315 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003316 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003317 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3318 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3319 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3320 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3321 }
3322
3323 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003324 setDeviceOwner();
3325
Pavel Grafov75c0a892017-05-18 17:28:27 +01003326 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003327 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003328 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3329 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003330 true)).thenReturn(true);
3331 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3332
3333 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003334 }
Victor Chang3e794af2016-03-04 13:48:17 +00003335
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003336 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3337 throws Exception {
3338 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003339 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3340 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003341 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3342 }
3343
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003344 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003345 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003346 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3347 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003348
3349 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003350 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3351 DevicePolicyManager.CODE_OK);
3352 }
3353
3354 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003355 setDeviceOwner();
3356
Pavel Grafov75c0a892017-05-18 17:28:27 +01003357 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003358 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003359 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3360 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003361 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3362 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003363 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003364 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003365 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003366 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003367 true)).thenReturn(true);
3368 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3369
3370 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003371 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003372
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003373 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3374 throws Exception {
3375 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003376 mContext.packageName = admin1.getPackageName();
3377 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003378 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3379 }
3380
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003381 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3382 throws Exception {
3383 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3384 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3385 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3386 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3387 }
3388
3389 public void testCheckProvisioningPreCondition_permission() {
3390 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003391 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3392 () -> dpm.checkProvisioningPreCondition(
3393 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003394 }
3395
Victor Chang3577ed22016-08-25 18:49:26 +01003396 public void testForceUpdateUserSetupComplete_permission() {
3397 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003398 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3399 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003400 }
3401
3402 public void testForceUpdateUserSetupComplete_systemUser() {
3403 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3404 // GIVEN calling from user 20
3405 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003406 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3407 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003408 }
3409
3410 public void testForceUpdateUserSetupComplete_userbuild() {
3411 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3412 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3413
3414 final int userId = UserHandle.USER_SYSTEM;
3415 // GIVEN userComplete is false in SettingsProvider
3416 setUserSetupCompleteForUser(false, userId);
3417
3418 // GIVEN userComplete is true in DPM
3419 DevicePolicyManagerService.DevicePolicyData userData =
3420 new DevicePolicyManagerService.DevicePolicyData(userId);
3421 userData.mUserSetupComplete = true;
3422 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3423
3424 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003425 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003426
3427 assertTrue(dpms.hasUserSetupCompleted());
3428
3429 dpm.forceUpdateUserSetupComplete();
3430
3431 // THEN the state in dpms is not changed
3432 assertTrue(dpms.hasUserSetupCompleted());
3433 }
3434
3435 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3436 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3437 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3438
3439 final int userId = UserHandle.USER_SYSTEM;
3440 // GIVEN userComplete is false in SettingsProvider
3441 setUserSetupCompleteForUser(false, userId);
3442
3443 // GIVEN userComplete is true in DPM
3444 DevicePolicyManagerService.DevicePolicyData userData =
3445 new DevicePolicyManagerService.DevicePolicyData(userId);
3446 userData.mUserSetupComplete = true;
3447 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3448
3449 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003450 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003451
3452 assertTrue(dpms.hasUserSetupCompleted());
3453
3454 dpm.forceUpdateUserSetupComplete();
3455
3456 // THEN the state in dpms is not changed
3457 assertFalse(dpms.hasUserSetupCompleted());
3458 }
3459
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003460 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003461 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003462 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003463
3464 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3465 runAsCaller(mAdmin1Context, dpms, dpm -> {
3466 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3467 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003468 }
3469
3470 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3471 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3472 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003473
3474 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3475 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003476 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003477 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3478 .thenReturn(true);
3479
3480 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003481 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003482
3483 // Enabling logging should not change the timestamp.
3484 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003485 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003486 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003487 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003488 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003489 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003490
3491 // Retrieving the logs should update the timestamp.
3492 final long beforeRetrieval = System.currentTimeMillis();
3493 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003494 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003495 final long afterRetrieval = System.currentTimeMillis();
3496 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3497 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3498
3499 // Retrieving the pre-boot logs should update the timestamp.
3500 Thread.sleep(2);
3501 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003502 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003503 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3504
3505 // Checking the timestamp again should not change it.
3506 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003507 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003508
3509 // Retrieving the logs again should update the timestamp.
3510 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003511 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003512 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3513
3514 // Disabling logging should not change the timestamp.
3515 Thread.sleep(2);
3516 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003517 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003518
3519 // Restarting the DPMS should not lose the timestamp.
3520 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003521 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003522
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003523 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3524 mContext.binder.callingUid = 1234567;
3525 mContext.callerPermissions.add(permission.MANAGE_USERS);
3526 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3527 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3528
3529 // System can retrieve the timestamp.
3530 mContext.binder.clearCallingIdentity();
3531 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3532
3533 // Removing the device owner should clear the timestamp.
3534 clearDeviceOwner();
3535 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003536 }
3537
yuemingw0de748d2017-11-15 19:22:27 +00003538 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3539 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3540 setupDeviceOwner();
3541 assertExpectException(SecurityException.class, null, () ->
3542 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3543 }
3544
yuemingwc0281f12018-03-28 15:58:49 +01003545 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003546 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3547 setupDeviceOwner();
3548 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003549 verify(getServices().settings).settingsSystemPutStringForUser(
3550 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3551 }
3552
3553 public void testSetSystemSettingWithPO() throws Exception {
3554 setupProfileOwner();
3555 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3556 verify(getServices().settings).settingsSystemPutStringForUser(
3557 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003558 }
3559
yuemingwe43cdf72017-10-12 16:52:11 +01003560 public void testSetTime() throws Exception {
3561 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3562 setupDeviceOwner();
3563 dpm.setTime(admin1, 0);
3564 verify(getServices().alarmManager).setTime(0);
3565 }
3566
3567 public void testSetTimeFailWithPO() throws Exception {
3568 setupProfileOwner();
3569 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3570 }
3571
3572 public void testSetTimeWithAutoTimeOn() throws Exception {
3573 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3574 setupDeviceOwner();
3575 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3576 .thenReturn(1);
3577 assertFalse(dpm.setTime(admin1, 0));
3578 }
3579
3580 public void testSetTimeZone() throws Exception {
3581 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3582 setupDeviceOwner();
3583 dpm.setTimeZone(admin1, "Asia/Shanghai");
3584 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3585 }
3586
3587 public void testSetTimeZoneFailWithPO() throws Exception {
3588 setupProfileOwner();
3589 assertExpectException(SecurityException.class, null,
3590 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3591 }
3592
3593 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3594 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3595 setupDeviceOwner();
3596 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3597 .thenReturn(1);
3598 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3599 }
3600
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003601 public void testGetLastBugReportRequestTime() throws Exception {
3602 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3603 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003604
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003605 mContext.packageName = admin1.getPackageName();
3606 mContext.applicationInfo = new ApplicationInfo();
3607 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3608 .thenReturn(Color.WHITE);
3609 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3610 anyObject())).thenReturn(Color.WHITE);
3611
Esteban Talaverad36dd152016-12-15 08:51:45 +00003612 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3613 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003614 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003615
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003616 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003617 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003618
3619 // Requesting a bug report should update the timestamp.
3620 final long beforeRequest = System.currentTimeMillis();
3621 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003622 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003623 final long afterRequest = System.currentTimeMillis();
3624 assertTrue(bugReportRequestTime >= beforeRequest);
3625 assertTrue(bugReportRequestTime <= afterRequest);
3626
3627 // Checking the timestamp again should not change it.
3628 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003629 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003630
3631 // Restarting the DPMS should not lose the timestamp.
3632 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003633 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003634
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003635 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3636 mContext.binder.callingUid = 1234567;
3637 mContext.callerPermissions.add(permission.MANAGE_USERS);
3638 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3639 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3640
3641 // System can retrieve the timestamp.
3642 mContext.binder.clearCallingIdentity();
3643 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3644
3645 // Removing the device owner should clear the timestamp.
3646 clearDeviceOwner();
3647 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003648 }
3649
3650 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3651 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3652 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003653 mContext.packageName = admin1.getPackageName();
3654 mContext.applicationInfo = new ApplicationInfo();
3655 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3656 .thenReturn(Color.WHITE);
3657 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3658 anyObject())).thenReturn(Color.WHITE);
3659
3660 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3661 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003662 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003663 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003664 .thenReturn(true);
3665
3666 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003667 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003668
3669 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3670 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003671 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003672
3673 // Enabling logging should not change the timestamp.
3674 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003675 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003676
3677 // Retrieving the logs should update the timestamp.
3678 final long beforeRetrieval = System.currentTimeMillis();
3679 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003680 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003681 final long afterRetrieval = System.currentTimeMillis();
3682 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3683 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3684
3685 // Checking the timestamp again should not change it.
3686 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003687 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003688
3689 // Retrieving the logs again should update the timestamp.
3690 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003691 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003692 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3693
3694 // Disabling logging should not change the timestamp.
3695 Thread.sleep(2);
3696 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003697 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003698
3699 // Restarting the DPMS should not lose the timestamp.
3700 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003701 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3702
3703 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3704 mContext.binder.callingUid = 1234567;
3705 mContext.callerPermissions.add(permission.MANAGE_USERS);
3706 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3707 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3708
3709 // System can retrieve the timestamp.
3710 mContext.binder.clearCallingIdentity();
3711 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3712
3713 // Removing the device owner should clear the timestamp.
3714 clearDeviceOwner();
3715 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003716 }
3717
Tony Mak2f26b792016-11-28 17:54:51 +00003718 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3719 // Setup device owner.
3720 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3721 setupDeviceOwner();
3722
3723 // Only device owner is setup, the result list should be empty.
3724 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3725 MoreAsserts.assertEmpty(targetUsers);
3726
3727 // Setup a managed profile managed by the same admin.
3728 final int MANAGED_PROFILE_USER_ID = 15;
3729 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3730 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3731
3732 // Add a secondary user, it should never talk with.
3733 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003734 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003735
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003736 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3737 // other.
3738 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3739 MoreAsserts.assertEmpty(targetUsers);
3740
3741 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3742 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3743 MoreAsserts.assertEmpty(targetUsers);
3744
3745 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003746 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003747 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3748 dpm.setAffiliationIds(admin1, userAffiliationIds);
3749
3750 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3751 dpm.setAffiliationIds(admin1, userAffiliationIds);
3752
Tony Mak2f26b792016-11-28 17:54:51 +00003753 // Calling from device owner admin, the result list should just contain the managed
3754 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003755 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003756 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3757 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3758
3759 // Calling from managed profile admin, the result list should just contain the system
3760 // user id.
3761 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3762 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3763 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003764
3765 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003766 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003767
3768 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3769 // to each other.
3770 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3771 MoreAsserts.assertEmpty(targetUsers);
3772
3773 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3774 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3775 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003776 }
3777
3778 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3779 // Setup a device owner.
3780 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3781 setupDeviceOwner();
3782
3783 // Set up a managed profile managed by different package.
3784 final int MANAGED_PROFILE_USER_ID = 15;
3785 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3786 final ComponentName adminDifferentPackage =
3787 new ComponentName("another.package", "whatever.class");
3788 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3789
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003790 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003791 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003792 dpm.setAffiliationIds(admin1, userAffiliationIds);
3793
3794 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3795 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3796
Tony Mak2f26b792016-11-28 17:54:51 +00003797 // Calling from device owner admin, we should get zero bind device admin target users as
3798 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003799 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003800 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3801 MoreAsserts.assertEmpty(targetUsers);
3802
3803 // Calling from managed profile admin, we should still get zero target users for the same
3804 // reason.
3805 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3806 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3807 MoreAsserts.assertEmpty(targetUsers);
3808 }
3809
Jason Parks3c13b642017-11-28 15:39:43 -06003810 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003811 verifyLockTaskState(userId, new String[0],
3812 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003813 }
3814
3815 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3816 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003817 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003818 }
3819
3820 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3821 int flags) throws Exception {
3822 mContext.binder.callingUid = uid;
3823 dpm.setLockTaskPackages(who, packages);
3824 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3825 for (String p : packages) {
3826 assertTrue(dpm.isLockTaskPermitted(p));
3827 }
3828 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3829 // Test to see if set lock task features can be set
3830 dpm.setLockTaskFeatures(who, flags);
3831 verifyLockTaskState(userId, packages, flags);
3832 }
3833
3834 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3835 int flags) throws Exception {
3836 mContext.binder.callingUid = uid;
3837 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3838 () -> dpm.setLockTaskPackages(who, packages));
3839 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3840 () -> dpm.getLockTaskPackages(who));
3841 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3842 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3843 () -> dpm.setLockTaskFeatures(who, flags));
3844 }
3845
Charles Hee078db72017-10-19 18:03:20 +01003846 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003847 // Setup a device owner.
3848 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3849 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003850 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003851 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003852
3853 // Set up a managed profile managed by different package (package name shouldn't matter)
3854 final int MANAGED_PROFILE_USER_ID = 15;
3855 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3856 final ComponentName adminDifferentPackage =
3857 new ComponentName("another.package", "whatever.class");
3858 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003859 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3860
3861 // Setup a PO on the secondary user
3862 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3863 setAsProfileOwner(admin3);
3864 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003865
3866 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003867 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003868 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003869 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3870 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003871 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3872
3873 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3874 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003875 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3876 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003877 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003878
3879 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3880 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3881 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003882 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003883 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3884 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003885 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003886
3887 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003888 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003889 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3890 dpm.setAffiliationIds(admin1, userAffiliationIds);
3891
3892 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3893 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3894
3895 // Now the managed profile can set lock task packages.
3896 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3897 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3898 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3899 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003900 // And it can set lock task features.
3901 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003902 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003903
3904 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003905 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003906 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3907 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003908 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3909 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003910 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003911 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003912
Jason Parks3c13b642017-11-28 15:39:43 -06003913 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003914 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3915 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003916
3917 }
3918
3919 public void testLockTaskPolicyForProfileOwner() throws Exception {
3920 // Setup a PO
3921 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3922 setAsProfileOwner(admin1);
3923 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3924
3925 final String[] poPackages = {"poPackage1", "poPackage2"};
3926 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003927 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3928 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003929 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3930 poPackages, poFlags);
3931
3932 // Set up a managed profile managed by different package (package name shouldn't matter)
3933 final int MANAGED_PROFILE_USER_ID = 15;
3934 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3935 final ComponentName adminDifferentPackage =
3936 new ComponentName("another.package", "whatever.class");
3937 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3938 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3939
3940 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3941 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3942 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3943 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003944 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3945 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003946 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003947 }
3948
Benjamin Franzcaffa772018-02-05 16:36:10 +00003949 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3950 // Setup a device owner.
3951 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3952 setupDeviceOwner();
3953 // Lock task policy is updated when loading user data.
3954 verifyLockTaskState(UserHandle.USER_SYSTEM);
3955
3956 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3957 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3958 assertExpectException(IllegalArgumentException.class,
3959 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3960 () -> dpm.setLockTaskFeatures(admin1, flags));
3961 }
3962
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003963 public void testIsDeviceManaged() throws Exception {
3964 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3965 setupDeviceOwner();
3966
3967 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3968 // find out that the device has a device owner.
3969 assertTrue(dpm.isDeviceManaged());
3970 mContext.binder.callingUid = 1234567;
3971 mContext.callerPermissions.add(permission.MANAGE_USERS);
3972 assertTrue(dpm.isDeviceManaged());
3973 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3974 mContext.binder.clearCallingIdentity();
3975 assertTrue(dpm.isDeviceManaged());
3976
3977 clearDeviceOwner();
3978
3979 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3980 // not have a device owner.
3981 mContext.binder.callingUid = 1234567;
3982 mContext.callerPermissions.add(permission.MANAGE_USERS);
3983 assertFalse(dpm.isDeviceManaged());
3984 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3985 mContext.binder.clearCallingIdentity();
3986 assertFalse(dpm.isDeviceManaged());
3987 }
3988
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003989 public void testDeviceOwnerOrganizationName() throws Exception {
3990 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3991 setupDeviceOwner();
3992
3993 dpm.setOrganizationName(admin1, "organization");
3994
3995 // Device owner can retrieve organization managing the device.
3996 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3997
3998 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3999 mContext.binder.callingUid = 1234567;
4000 mContext.callerPermissions.add(permission.MANAGE_USERS);
4001 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4002 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4003
4004 // System can retrieve organization managing the device.
4005 mContext.binder.clearCallingIdentity();
4006 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4007
4008 // Removing the device owner clears the organization managing the device.
4009 clearDeviceOwner();
4010 assertNull(dpm.getDeviceOwnerOrganizationName());
4011 }
4012
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004013 public void testWipeDataManagedProfile() throws Exception {
4014 final int MANAGED_PROFILE_USER_ID = 15;
4015 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4016 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4017 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4018
4019 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004020 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004021 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01004022 // Get mock reason string since we throw an IAE with empty string input.
4023 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4024 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004025
4026 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004027 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004028 MANAGED_PROFILE_USER_ID);
4029 }
4030
4031 public void testWipeDataManagedProfileDisallowed() throws Exception {
4032 final int MANAGED_PROFILE_USER_ID = 15;
4033 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4034 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4035
4036 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004037 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004038 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4039
Pavel Grafov75c0a892017-05-18 17:28:27 +01004040 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004041 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4042 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4043 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004044 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4045 thenReturn("Just a test string.");
4046
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004047 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004048 // The PO is not allowed to remove the profile if the user restriction was set on the
4049 // profile by the system
4050 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4051 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004052 }
4053
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004054 public void testWipeDataDeviceOwner() throws Exception {
4055 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004056 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004057 UserManager.DISALLOW_FACTORY_RESET,
4058 UserHandle.SYSTEM))
4059 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004060 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4061 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004062
4063 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004064 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004065 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4066 /*wipeEuicc=*/ eq(false));
4067 }
4068
4069 public void testWipeEuiccDataEnabled() throws Exception {
4070 setDeviceOwner();
4071 when(getServices().userManager.getUserRestrictionSource(
4072 UserManager.DISALLOW_FACTORY_RESET,
4073 UserHandle.SYSTEM))
4074 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004075 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4076 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07004077
4078 dpm.wipeData(WIPE_EUICC);
4079 verify(getServices().recoverySystem).rebootWipeUserData(
4080 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4081 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004082 }
4083
4084 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
4085 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004086 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004087 UserManager.DISALLOW_FACTORY_RESET,
4088 UserHandle.SYSTEM))
4089 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004090 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4091 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004092 // The DO is not allowed to wipe the device if the user restriction was set
4093 // by the system
4094 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4095 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004096 }
4097
4098 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4099 final int MANAGED_PROFILE_USER_ID = 15;
4100 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4101 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4102
4103 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004104 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004105 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4106
Pavel Grafov75c0a892017-05-18 17:28:27 +01004107 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004108 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4109 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4110 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4111
4112 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4113 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4114
4115 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4116 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4117 // Failed password attempts on the parent user are taken into account, as there isn't a
4118 // separate work challenge.
4119 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4120 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4121 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4122
4123 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4124 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004125 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004126 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004127 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004128 }
4129
4130 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4131 throws Exception {
4132 final int MANAGED_PROFILE_USER_ID = 15;
4133 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4134 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4135
4136 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004137 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004138 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4139
Pavel Grafov75c0a892017-05-18 17:28:27 +01004140 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004141 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4142 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4143 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4144
4145 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4146 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4147
4148 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4149 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4150 // Failed password attempts on the parent user are taken into account, as there isn't a
4151 // separate work challenge.
4152 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4153 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4154 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4155
4156 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4157 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004158 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004159 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004160 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004161 }
4162
4163 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4164 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004165 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004166 UserManager.DISALLOW_FACTORY_RESET,
4167 UserHandle.SYSTEM))
4168 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4169
4170 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4171
4172 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4173 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4174 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4175 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4176 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4177
4178 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4179 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004180 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004181 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4182 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004183 }
4184
4185 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4186 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004187 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004188 UserManager.DISALLOW_FACTORY_RESET,
4189 UserHandle.SYSTEM))
4190 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4191
4192 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4193
4194 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4195 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4196 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4197 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4198 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4199
4200 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004201 verifyZeroInteractions(getServices().recoverySystem);
4202 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004203 .removeUserEvenWhenDisallowed(anyInt());
4204 }
4205
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004206 public void testGetPermissionGrantState() throws Exception {
4207 final String permission = "some.permission";
4208 final String app1 = "com.example.app1";
4209 final String app2 = "com.example.app2";
4210
Pavel Grafov75c0a892017-05-18 17:28:27 +01004211 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004212 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004213 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004214 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004215 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004216 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4217 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004218 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004219 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004220 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004221 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004222 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004223 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4224
4225 // System can retrieve permission grant state.
4226 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004227 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004228 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4229 dpm.getPermissionGrantState(null, app1, permission));
4230 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4231 dpm.getPermissionGrantState(null, app2, permission));
4232
4233 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004234 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4235 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004236 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4237 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004238
4239 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004240 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4241 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004242 setAsProfileOwner(admin1);
4243 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4244 dpm.getPermissionGrantState(admin1, app1, permission));
4245 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4246 dpm.getPermissionGrantState(admin1, app2, permission));
4247 }
4248
Rubin Xuaab7a412016-12-30 21:13:29 +00004249 public void testResetPasswordWithToken() throws Exception {
4250 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4251 setupDeviceOwner();
4252 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004253 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4254 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4255
Rubin Xuaab7a412016-12-30 21:13:29 +00004256 // test adding a token
4257 final byte[] token = new byte[32];
4258 final long handle = 123456;
4259 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004260 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4261 nullable(EscrowTokenStateChangeCallback.class)))
4262 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004263 assertTrue(dpm.setResetPasswordToken(admin1, token));
4264
4265 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004266 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004267 .thenReturn(true);
4268 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4269
4270 // test reset password with token
Rubin Xua58125d2019-09-06 20:11:48 +01004271 when(getServices().lockPatternUtils.setLockCredentialWithToken(
4272 eq(LockscreenCredential.createPassword(password)),
4273 eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004274 eq(UserHandle.USER_SYSTEM)))
4275 .thenReturn(true);
4276 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4277
4278 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004279 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004280 .thenReturn(true);
4281 assertTrue(dpm.clearResetPasswordToken(admin1));
4282 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004283
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004284 public void testIsActivePasswordSufficient() throws Exception {
4285 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4286 mContext.packageName = admin1.getPackageName();
4287 setupDeviceOwner();
4288
4289 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4290 dpm.setPasswordMinimumLength(admin1, 8);
4291 dpm.setPasswordMinimumLetters(admin1, 6);
4292 dpm.setPasswordMinimumLowerCase(admin1, 3);
4293 dpm.setPasswordMinimumUpperCase(admin1, 1);
4294 dpm.setPasswordMinimumNonLetter(admin1, 1);
4295 dpm.setPasswordMinimumNumeric(admin1, 1);
4296 dpm.setPasswordMinimumSymbols(admin1, 0);
4297
Rubin Xucc391c22018-01-02 20:37:35 +00004298 reset(mContext.spiedContext);
4299
Pavel Grafov6f334842019-08-06 14:37:06 +01004300 PasswordMetrics passwordMetricsNoSymbols = computeForPassword("abcdXYZ5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004301
4302 setActivePasswordState(passwordMetricsNoSymbols);
4303 assertTrue(dpm.isActivePasswordSufficient());
4304
4305 initializeDpms();
4306 reset(mContext.spiedContext);
4307 assertTrue(dpm.isActivePasswordSufficient());
4308
4309 // This call simulates the user entering the password for the first time after a reboot.
4310 // This causes password metrics to be reloaded into memory. Until this happens,
4311 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4312 // even if the DPC changes password requirements so that the password no longer meets the
4313 // requirements. This is a known limitation of the current implementation of
4314 // isActivePasswordSufficient() - see b/34218769.
4315 setActivePasswordState(passwordMetricsNoSymbols);
4316 assertTrue(dpm.isActivePasswordSufficient());
4317
4318 dpm.setPasswordMinimumSymbols(admin1, 1);
4319 // This assertion would fail if we had not called setActivePasswordState() again after
4320 // initializeDpms() - see previous comment.
4321 assertFalse(dpm.isActivePasswordSufficient());
4322
4323 initializeDpms();
4324 reset(mContext.spiedContext);
4325 assertFalse(dpm.isActivePasswordSufficient());
4326
Pavel Grafov6f334842019-08-06 14:37:06 +01004327 PasswordMetrics passwordMetricsWithSymbols = computeForPassword("abcd.XY5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004328
4329 setActivePasswordState(passwordMetricsWithSymbols);
4330 assertTrue(dpm.isActivePasswordSufficient());
4331 }
4332
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004333 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4334 // If there is no lock screen, the password is considered empty no matter what, because
4335 // it provides no security.
4336 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4337
4338 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4339 mContext.packageName = admin1.getPackageName();
4340 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004341 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4342 // When there is no lockscreen, user password metrics is always empty.
4343 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
Pavel Grafov6f334842019-08-06 14:37:06 +01004344 .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE));
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004345
4346 // If no password requirements are set, isActivePasswordSufficient should succeed.
4347 assertTrue(dpm.isActivePasswordSufficient());
4348
4349 // Now set some password quality requirements.
4350 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4351
4352 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004353 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004354 dpm.reportPasswordChanged(userHandle);
4355
4356 // No broadcast should be sent.
4357 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4358 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4359 MockUtils.checkUserHandle(userHandle));
4360
4361 // The active (nonexistent) password doesn't comply with the requirements.
4362 assertFalse(dpm.isActivePasswordSufficient());
4363 }
4364
Pavel Grafov75c0a892017-05-18 17:28:27 +01004365 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4366 throws Exception {
4367 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004368 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004369
Rubin Xu19854862019-08-15 16:37:23 +01004370 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4371 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004372 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004373
Rubin Xucc391c22018-01-02 20:37:35 +00004374 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4375 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004376 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004377 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4378 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004379 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004380 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4381 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004382 // userId, if the password checkpoint value changes.
4383 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4384 MockUtils.checkIntentAction(
4385 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4386 MockUtils.checkUserHandle(userHandle));
4387 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004388 MockUtils.checkIntentAction(
4389 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4390 MockUtils.checkUserHandle(userHandle));
4391
Pavel Grafov75c0a892017-05-18 17:28:27 +01004392 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4393 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004394 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004395
4396 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4397 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004398 MockUtils.checkUserHandle(userHandle),
4399 eq(null),
4400 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004401
4402 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4403 // let it finish with system uid, otherwise it will throw and crash.
4404 flushTasks();
4405
4406 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004407 }
4408
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004409 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4410 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4411 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4412 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4413 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4414 DpmMockContext.SYSTEM_UID);
4415 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4416 DpmMockContext.SYSTEM_UID);
4417
4418 // Set up a device owner.
4419 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004420 setupDeviceOwner();
4421
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004422 // First and second user set IMEs manually.
4423 mContext.binder.callingUid = firstUserSystemUid;
4424 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4425 mContext.binder.callingUid = secondUserSystemUid;
4426 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004427
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004428 // Device owner changes IME for first user.
4429 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004430 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004431 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004432 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004433 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004434 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004435 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004436 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4437 mContext.binder.callingUid = firstUserSystemUid;
4438 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4439 mContext.binder.callingUid = secondUserSystemUid;
4440 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004441
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004442 // Second user changes IME manually.
4443 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4444 mContext.binder.callingUid = firstUserSystemUid;
4445 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4446 mContext.binder.callingUid = secondUserSystemUid;
4447 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004448
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004449 // First user changes IME manually.
4450 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4451 mContext.binder.callingUid = firstUserSystemUid;
4452 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4453 mContext.binder.callingUid = secondUserSystemUid;
4454 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004455
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004456 // Device owner changes IME for first user again.
4457 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004458 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004459 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004460 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004461 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004462 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004463 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4464 mContext.binder.callingUid = firstUserSystemUid;
4465 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4466 mContext.binder.callingUid = secondUserSystemUid;
4467 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004468
4469 // Restarting the DPMS should not lose information.
4470 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004471 mContext.binder.callingUid = firstUserSystemUid;
4472 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4473 mContext.binder.callingUid = secondUserSystemUid;
4474 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004475
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004476 // Device owner can find out whether it set the current IME itself.
4477 mContext.binder.callingUid = deviceOwnerUid;
4478 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004479
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004480 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004481 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004482 mContext.binder.callingUid = firstUserSystemUid;
4483 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4484 mContext.binder.callingUid = secondUserSystemUid;
4485 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004486 }
4487
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004488 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4489 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4490 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4491 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4492 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4493 DpmMockContext.SYSTEM_UID);
4494 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4495 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004496
4497 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004498 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004499 setupProfileOwner();
4500
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004501 // First and second user set IMEs manually.
4502 mContext.binder.callingUid = firstUserSystemUid;
4503 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4504 mContext.binder.callingUid = secondUserSystemUid;
4505 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004506
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004507 // Profile owner changes IME for second user.
4508 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004509 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004510 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004511 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004512 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004513 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004514 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004515 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4516 mContext.binder.callingUid = firstUserSystemUid;
4517 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4518 mContext.binder.callingUid = secondUserSystemUid;
4519 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004520
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004521 // First user changes IME manually.
4522 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4523 mContext.binder.callingUid = firstUserSystemUid;
4524 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4525 mContext.binder.callingUid = secondUserSystemUid;
4526 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004527
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004528 // Second user changes IME manually.
4529 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4530 mContext.binder.callingUid = firstUserSystemUid;
4531 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4532 mContext.binder.callingUid = secondUserSystemUid;
4533 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004534
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004535 // Profile owner changes IME for second user again.
4536 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004537 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004538 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004539 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004540 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004541 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004542 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4543 mContext.binder.callingUid = firstUserSystemUid;
4544 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4545 mContext.binder.callingUid = secondUserSystemUid;
4546 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004547
4548 // Restarting the DPMS should not lose information.
4549 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004550 mContext.binder.callingUid = firstUserSystemUid;
4551 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4552 mContext.binder.callingUid = secondUserSystemUid;
4553 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004554
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004555 // Profile owner can find out whether it set the current IME itself.
4556 mContext.binder.callingUid = profileOwnerUid;
4557 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004558
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004559 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004560 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004561 mContext.binder.callingUid = firstUserSystemUid;
4562 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4563 mContext.binder.callingUid = secondUserSystemUid;
4564 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004565 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004566
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004567 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4568 throws Exception {
4569 // Set up a device owner.
4570 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4571 setupDeviceOwner();
4572 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4573 }
4574
4575 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4576 throws Exception {
4577 // Set up a profile owner.
4578 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4579 setupProfileOwner();
4580 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4581 }
4582
4583 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4584 int adminUid) throws Exception {
4585 mContext.binder.callingUid = adminUid;
4586 final int userId = UserHandle.getUserId(adminUid);
4587
4588 final String packageName = "some.package";
4589 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4590 admin1, Collections.singletonList(packageName)));
4591 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4592
4593 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4594 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4595
4596 // Attempt to set to empty list (which means no listener is whitelisted)
4597 mContext.binder.callingUid = adminUid;
4598 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004599 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004600 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4601
4602 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4603 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4604 }
4605
4606 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4607 // Set up a managed profile
4608 final int MANAGED_PROFILE_USER_ID = 15;
4609 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4610 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4611 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4612
4613 final String permittedListener = "some.package";
4614 setupPackageInPackageManager(
4615 permittedListener,
4616 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4617 /*appId=*/ 12345, /*flags=*/ 0);
4618
4619 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4620 admin1, Collections.singletonList(permittedListener)));
4621
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004622 // isNotificationListenerServicePermitted should throw if not called from System.
4623 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4624 () -> dpms.isNotificationListenerServicePermitted(
4625 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004626
4627 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4628 assertTrue(dpms.isNotificationListenerServicePermitted(
4629 permittedListener, MANAGED_PROFILE_USER_ID));
4630 }
4631
4632 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4633 throws Exception {
4634 // Set up a managed profile
4635 final int MANAGED_PROFILE_USER_ID = 15;
4636 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4637 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4638 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4639
4640 final String permittedListener = "permitted.package";
4641 int appId = 12345;
4642 setupPackageInPackageManager(
4643 permittedListener,
4644 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4645 appId, /*flags=*/ 0);
4646
4647 final String notPermittedListener = "not.permitted.package";
4648 setupPackageInPackageManager(
4649 notPermittedListener,
4650 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4651 ++appId, /*flags=*/ 0);
4652
4653 final String systemListener = "system.package";
4654 setupPackageInPackageManager(
4655 systemListener,
4656 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4657 ++appId, ApplicationInfo.FLAG_SYSTEM);
4658
4659 // By default all packages are allowed
4660 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4661
4662 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4663 assertTrue(dpms.isNotificationListenerServicePermitted(
4664 permittedListener, MANAGED_PROFILE_USER_ID));
4665 assertTrue(dpms.isNotificationListenerServicePermitted(
4666 notPermittedListener, MANAGED_PROFILE_USER_ID));
4667 assertTrue(dpms.isNotificationListenerServicePermitted(
4668 systemListener, MANAGED_PROFILE_USER_ID));
4669
4670 // Setting only one package in the whitelist
4671 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4672 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4673 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004674 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004675 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4676 assertEquals(1, permittedListeners.size());
4677 assertEquals(permittedListener, permittedListeners.get(0));
4678
4679 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4680 assertTrue(dpms.isNotificationListenerServicePermitted(
4681 permittedListener, MANAGED_PROFILE_USER_ID));
4682 assertFalse(dpms.isNotificationListenerServicePermitted(
4683 notPermittedListener, MANAGED_PROFILE_USER_ID));
4684 // System packages are always allowed (even if not in the whitelist)
4685 assertTrue(dpms.isNotificationListenerServicePermitted(
4686 systemListener, MANAGED_PROFILE_USER_ID));
4687
4688 // Setting an empty whitelist - only system listeners allowed
4689 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4690 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004691 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004692 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4693
4694 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4695 assertFalse(dpms.isNotificationListenerServicePermitted(
4696 permittedListener, MANAGED_PROFILE_USER_ID));
4697 assertFalse(dpms.isNotificationListenerServicePermitted(
4698 notPermittedListener, MANAGED_PROFILE_USER_ID));
4699 // System packages are always allowed (even if not in the whitelist)
4700 assertTrue(dpms.isNotificationListenerServicePermitted(
4701 systemListener, MANAGED_PROFILE_USER_ID));
4702
4703 // Setting a null whitelist - all listeners allowed
4704 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4705 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4706 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4707
4708 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4709 assertTrue(dpms.isNotificationListenerServicePermitted(
4710 permittedListener, MANAGED_PROFILE_USER_ID));
4711 assertTrue(dpms.isNotificationListenerServicePermitted(
4712 notPermittedListener, MANAGED_PROFILE_USER_ID));
4713 assertTrue(dpms.isNotificationListenerServicePermitted(
4714 systemListener, MANAGED_PROFILE_USER_ID));
4715 }
4716
4717 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4718 throws Exception {
4719 // Set up a managed profile
4720 final int MANAGED_PROFILE_USER_ID = 15;
4721 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4722 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4723 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4724
4725 final String nonSystemPackage = "non.system.package";
4726 int appId = 12345;
4727 setupPackageInPackageManager(
4728 nonSystemPackage,
4729 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4730 appId, /*flags=*/ 0);
4731
4732 final String systemListener = "system.package";
4733 setupPackageInPackageManager(
4734 systemListener,
4735 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4736 ++appId, ApplicationInfo.FLAG_SYSTEM);
4737
4738 // By default all packages are allowed (for all profiles)
4739 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4740
4741 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4742 assertTrue(dpms.isNotificationListenerServicePermitted(
4743 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4744 assertTrue(dpms.isNotificationListenerServicePermitted(
4745 systemListener, MANAGED_PROFILE_USER_ID));
4746 assertTrue(dpms.isNotificationListenerServicePermitted(
4747 nonSystemPackage, UserHandle.USER_SYSTEM));
4748 assertTrue(dpms.isNotificationListenerServicePermitted(
4749 systemListener, UserHandle.USER_SYSTEM));
4750
4751 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4752 // all allowed in primary profile
4753 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4754 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004755 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004756 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4757
4758 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4759 assertFalse(dpms.isNotificationListenerServicePermitted(
4760 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4761 assertTrue(dpms.isNotificationListenerServicePermitted(
4762 systemListener, MANAGED_PROFILE_USER_ID));
4763 assertTrue(dpms.isNotificationListenerServicePermitted(
4764 nonSystemPackage, UserHandle.USER_SYSTEM));
4765 assertTrue(dpms.isNotificationListenerServicePermitted(
4766 systemListener, UserHandle.USER_SYSTEM));
4767 }
4768
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004769 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004770 mServiceContext.packageName = mRealTestContext.getPackageName();
4771 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4772 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004773 setDeviceOwner();
4774
Pavel Grafov75c0a892017-05-18 17:28:27 +01004775 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004776 }
4777
4778 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004779 mServiceContext.packageName = mRealTestContext.getPackageName();
4780 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4781 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004782 setAsProfileOwner(admin1);
4783
Pavel Grafov75c0a892017-05-18 17:28:27 +01004784 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4785 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004786 }
4787
4788 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004789 mServiceContext.packageName = mRealTestContext.getPackageName();
4790 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4791 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004792 setAsProfileOwner(admin1);
4793
Pavel Grafov75c0a892017-05-18 17:28:27 +01004794 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4795 caller.packageName = "com.example.delegate";
4796 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4797 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004798
Pavel Grafov75c0a892017-05-18 17:28:27 +01004799 // Make caller a delegated cert installer.
4800 runAsCaller(mAdmin1Context, dpms,
4801 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004802
4803 verifyCanGetOwnerInstalledCaCerts(null, caller);
4804 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004805 }
4806
Rubin Xucc391c22018-01-02 20:37:35 +00004807 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004808 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4809 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004810 Bundle restriction = new Bundle();
4811 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4812
4813 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4814 RestrictionsListener listener = new RestrictionsListener(mContext);
4815 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4816 new Bundle());
4817 verifyDataSharingChangedBroadcast();
4818 }
4819
4820 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004821 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4822 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004823 Bundle restriction = new Bundle();
4824 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4825
4826 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4827 RestrictionsListener listener = new RestrictionsListener(mContext);
4828 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4829 restriction);
4830 verifyDataSharingChangedBroadcast();
4831 }
4832
4833 public void testDisallowSharingIntoProfileUnchanged() {
4834 RestrictionsListener listener = new RestrictionsListener(mContext);
4835 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4836 new Bundle());
4837 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4838 }
4839
4840 private void verifyDataSharingChangedBroadcast() {
4841 Intent expectedIntent = new Intent(
4842 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4843 expectedIntent.setPackage("com.android.managedprovisioning");
4844 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4845 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4846 MockUtils.checkIntent(expectedIntent),
4847 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4848 }
4849
yuemingwe3d9c092018-01-11 12:11:44 +00004850 public void testOverrideApnAPIsFailWithPO() throws Exception {
4851 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004852 ApnSetting apn = (new ApnSetting.Builder())
4853 .setApnName("test")
4854 .setEntryName("test")
4855 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4856 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004857 assertExpectException(SecurityException.class, null, () ->
4858 dpm.addOverrideApn(admin1, apn));
4859 assertExpectException(SecurityException.class, null, () ->
4860 dpm.updateOverrideApn(admin1, 0, apn));
4861 assertExpectException(SecurityException.class, null, () ->
4862 dpm.removeOverrideApn(admin1, 0));
4863 assertExpectException(SecurityException.class, null, () ->
4864 dpm.getOverrideApns(admin1));
4865 assertExpectException(SecurityException.class, null, () ->
4866 dpm.setOverrideApnsEnabled(admin1, false));
4867 assertExpectException(SecurityException.class, null, () ->
4868 dpm.isOverrideApnEnabled(admin1));
4869 }
4870
Robin Lee2c68dad2017-03-17 12:50:24 +00004871 private void verifyCanGetOwnerInstalledCaCerts(
4872 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004873 final String alias = "cert";
4874 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004875
4876 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004877 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004878 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4879 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004880 }
4881 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4882
4883 // caller: device admin or delegated certificate installer
4884 callerContext.applicationInfo = new ApplicationInfo();
4885 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4886
4887 // system_server
4888 final DpmMockContext serviceContext = mContext;
4889 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004890 getServices().addPackageContext(callerUser, admin1Context);
4891 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004892
4893 // Install a CA cert.
4894 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004895 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004896 .thenReturn(alias);
4897 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004898 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004899 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004900 });
4901
Pavel Grafov75c0a892017-05-18 17:28:27 +01004902 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4903 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4904 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004905 flushTasks();
4906
Robin Lee2c68dad2017-03-17 12:50:24 +00004907 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4908
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004909 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004910 runAsCaller(admin1Context, dpms, (dpm) -> {
4911 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004912 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004913 ownerInstalledCaCerts.addAll(installedCaCerts);
4914 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004915
4916 // Restarting the DPMS should not lose information.
4917 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004918 runAsCaller(admin1Context, dpms, (dpm) ->
4919 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004920
4921 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004922 runAsCaller(serviceContext, dpms, (dpm) -> {
4923 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004924
Robin Lee2c68dad2017-03-17 12:50:24 +00004925 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004926 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004927 });
4928
Pavel Grafov75c0a892017-05-18 17:28:27 +01004929 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4930 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4931 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004932 flushTasks();
4933
4934 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4935 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004936 runAsCaller(admin1Context, dpms, (dpm) -> {
4937 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4938 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004939 }
4940
Robin Lee2c68dad2017-03-17 12:50:24 +00004941 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4942 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004943 final String alias = "cert";
4944 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004945
4946 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004947 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004948 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4949 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004950 }
4951 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4952
4953 // caller: device admin or delegated certificate installer
4954 callerContext.applicationInfo = new ApplicationInfo();
4955 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4956
4957 // system_server
4958 final DpmMockContext serviceContext = mContext;
4959 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004960 getServices().addPackageContext(callerUser, admin1Context);
4961 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004962
4963 // Install a CA cert as caller
4964 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004965 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004966 .thenReturn(alias);
4967 assertTrue(dpm.installCaCert(callerName, caCert));
4968 });
4969
4970 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004971 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004972 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004973 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4974 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4975 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004976 flushTasks();
4977
Robin Lee2c68dad2017-03-17 12:50:24 +00004978 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004979 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004980
4981 runAsCaller(serviceContext, dpms, (dpm) -> {
4982 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4983 assertNotNull(ownerInstalledCaCerts);
4984 assertTrue(ownerInstalledCaCerts.isEmpty());
4985 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004986 }
4987
Eran Messeri94d56762017-12-21 20:50:54 +00004988 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4989 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4990 Arrays.sort(gotFlags);
4991 Arrays.sort(expectedFlags);
4992 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4993 }
4994
4995 public void testTranslationOfIdAttestationFlag() {
4996 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4997 int[] correspondingAttUtilsTypes = new int[]{
4998 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4999 AttestationUtils.ID_TYPE_MEID};
5000
5001 // Test translation of zero flags
5002 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
5003
5004 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
5005 // non-null array
5006 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
5007
5008 // Test translation of a single flag
5009 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
5010 new int[] {AttestationUtils.ID_TYPE_SERIAL});
5011 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
5012
5013 // Test translation of two flags
5014 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
5015 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
5016 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
5017 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
5018
5019 // Test translation of all three flags
5020 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
5021 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5022 AttestationUtils.ID_TYPE_MEID});
5023 // Test translation of all three flags
5024 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
5025 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5026 AttestationUtils.ID_TYPE_MEID});
5027 }
5028
arangelov08d534b2018-01-22 15:20:53 +00005029 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
5030 setDeviceOwner();
5031 initializeDpms();
5032 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5033 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
5034 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
5035 }
5036
5037 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
5038 DpmTestUtils.writeInputStreamToFile(
5039 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5040 getDeviceOwnerPoliciesFile());
5041 DpmTestUtils.writeInputStreamToFile(
5042 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
5043 getDeviceOwnerFile());
5044 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5045 }
5046
5047 public void testRevertDeviceOwnership_deviceNotMigrated()
5048 throws Exception {
5049 DpmTestUtils.writeInputStreamToFile(
5050 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5051 getDeviceOwnerPoliciesFile());
5052 DpmTestUtils.writeInputStreamToFile(
5053 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5054 getDeviceOwnerFile());
5055 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5056 }
5057
5058 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
5059 throws Exception {
5060 DpmTestUtils.writeInputStreamToFile(
5061 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5062 getDeviceOwnerPoliciesFile());
5063 DpmTestUtils.writeInputStreamToFile(
5064 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5065 getDeviceOwnerFile());
5066 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5067 }
5068
5069 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
5070 setupProfileOwner();
5071 initializeDpms();
5072 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5073 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
5074 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
5075 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
5076 }
5077
5078 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
5079 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5080 UserHandle.USER_SYSTEM);
5081 DpmTestUtils.writeInputStreamToFile(
5082 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5083 getProfileOwnerPoliciesFile());
5084 DpmTestUtils.writeInputStreamToFile(
5085 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5086 getProfileOwnerFile());
5087 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5088 }
5089
5090 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
5091 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5092 UserHandle.USER_SYSTEM);
5093 DpmTestUtils.writeInputStreamToFile(
5094 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5095 getProfileOwnerPoliciesFile());
5096 DpmTestUtils.writeInputStreamToFile(
5097 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5098 getProfileOwnerFile());
5099 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5100 }
5101
5102 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5103 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5104 UserHandle.USER_SYSTEM);
5105 DpmTestUtils.writeInputStreamToFile(
5106 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5107 getProfileOwnerPoliciesFile());
5108 DpmTestUtils.writeInputStreamToFile(
5109 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5110 getProfileOwnerFile());
5111 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5112 }
5113
Eran Messeribb271892018-10-17 18:27:50 +01005114 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5115 setupProfileOwner();
5116 configureContextForAccess(mContext, false);
5117
5118 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005119 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005120 }
5121
5122 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5123 setupProfileOwner();
5124 configureContextForAccess(mContext, false);
5125
5126 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005127 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005128 }
5129
5130 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5131 setupProfileOwner();
5132
5133 // This method will throw if the system context could not call
5134 // setProfileOwnerCanAccessDeviceIds successfully.
5135 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5136 }
5137
5138 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5139 when(context.spiedContext.checkCallingPermission(
5140 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5141 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5142 : PackageManager.PERMISSION_DENIED);
5143 }
5144
5145 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5146 setupProfileOwner();
5147
5148 final long ident = mServiceContext.binder.clearCallingIdentity();
5149 configureContextForAccess(mServiceContext, true);
5150
5151 mServiceContext.binder.callingUid =
5152 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5153 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5154 try {
5155 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005156 dpm.setProfileOwnerCanAccessDeviceIds(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005157 });
5158 } finally {
5159 mServiceContext.binder.restoreCallingIdentity(ident);
5160 }
5161 }
5162
5163 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5164 throws Exception {
5165 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5166 setupDeviceOwner();
5167 configureContextForAccess(mContext, false);
5168
5169 // Device owner should be allowed to request Device ID attestation.
5170 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5171 DpmMockContext.CALLER_SYSTEM_USER_UID);
5172
5173 // Another package must not be allowed to request Device ID attestation.
5174 assertExpectException(SecurityException.class, null,
5175 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5176 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5177 // Another component that is not the admin must not be allowed to request Device ID
5178 // attestation.
5179 assertExpectException(SecurityException.class, null,
5180 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5181 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5182 }
5183
5184 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5185 throws Exception {
5186 configureContextForAccess(mContext, false);
5187
5188 // Make sure a security exception is thrown if the device has no profile owner.
5189 assertExpectException(SecurityException.class, null,
5190 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5191 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5192
5193 setupProfileOwner();
5194 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5195
5196 // The profile owner is allowed to request Device ID attestation.
5197 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5198 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5199 DpmMockContext.CALLER_UID);
5200 // But not another package.
5201 assertExpectException(SecurityException.class, null,
5202 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5203 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5204 // Or another component which is not the admin.
5205 assertExpectException(SecurityException.class, null,
5206 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5207 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5208 }
5209
5210 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5211 final long ident = mServiceContext.binder.clearCallingIdentity();
5212
5213 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5214 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5215 try {
5216 runAsCaller(mServiceContext, dpms, action);
5217 } finally {
5218 mServiceContext.binder.restoreCallingIdentity(ident);
5219 }
5220 }
5221
5222 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5223 setupProfileOwner();
5224 markDelegatedCertInstallerAsInstalled();
5225
5226 // Configure a delegated cert installer.
5227 runAsCaller(mServiceContext, dpms,
5228 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5229 Arrays.asList(DELEGATION_CERT_INSTALL)));
5230
5231 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5232
5233 // Make sure that the profile owner can still request Device ID attestation.
5234 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5235 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5236 DpmMockContext.CALLER_UID);
5237
5238 runAsDelegatedCertInstaller(dpm -> {
5239 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5240 DpmMockContext.DELEGATE_PACKAGE_NAME,
5241 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5242 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5243 });
5244 }
5245
5246 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5247 throws Exception {
5248 setupProfileOwner();
5249 markDelegatedCertInstallerAsInstalled();
5250
5251 // Configure a delegated cert installer.
5252 runAsCaller(mServiceContext, dpms,
5253 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5254 Arrays.asList(DELEGATION_CERT_INSTALL)));
5255
5256
5257 assertExpectException(SecurityException.class, null,
5258 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5259 admin1.getPackageName(),
5260 DpmMockContext.CALLER_UID));
5261
5262 runAsDelegatedCertInstaller(dpm -> {
5263 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5264 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5265 DpmMockContext.DELEGATE_PACKAGE_NAME,
5266 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5267 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5268 });
5269 }
5270
Bernard Chaue9586552018-11-29 10:59:31 +00005271 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5272 assertThrows(SecurityException.class,
5273 () -> new DevicePolicyManagerTestable(
5274 mServiceContext,
5275 dpms,
5276 /* parentInstance= */ true)
5277 .getPasswordComplexity());
5278 }
5279
5280 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5281 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5282 .thenReturn(false);
5283 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5284 }
5285
5286 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5287 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5288 .thenReturn(true);
5289 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5290 }
5291
5292
5293 public void testGetPasswordComplexity_currentUserNoPassword() {
5294 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5295 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005296 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005297 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5298 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5299
5300 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5301 }
5302
5303 public void testGetPasswordComplexity_currentUserHasPassword() {
5304 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5305 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005306 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005307 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5308 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005309 when(getServices().lockSettingsInternal
5310 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005311 .thenReturn(computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005312
5313 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5314 }
5315
5316 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5317 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5318 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005319 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005320
5321 UserInfo parentUser = new UserInfo();
5322 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5323 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5324 .thenReturn(parentUser.id);
5325
Rubin Xu19854862019-08-15 16:37:23 +01005326 when(getServices().lockSettingsInternal
5327 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005328 .thenReturn(computeForPassword("asdf".getBytes()));
Rubin Xu19854862019-08-15 16:37:23 +01005329 when(getServices().lockSettingsInternal
5330 .getUserPasswordMetrics(parentUser.id))
Pavel Grafov6f334842019-08-06 14:37:06 +01005331 .thenReturn(computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005332
5333 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5334 }
5335
yuemingwd2bfbc82019-01-02 11:42:25 +00005336 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5337 setAsProfileOwner(admin1);
5338 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5339 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5340 }
5341
5342 public void testCrossProfileCalendarPackages_reopenDpms() {
5343 setAsProfileOwner(admin1);
5344 dpm.setCrossProfileCalendarPackages(admin1, null);
5345 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5346 assertTrue(packages == null);
5347 initializeDpms();
5348 packages = dpm.getCrossProfileCalendarPackages(admin1);
5349 assertTrue(packages == null);
5350
5351 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5352 packages = dpm.getCrossProfileCalendarPackages(admin1);
5353 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5354 initializeDpms();
5355 packages = dpm.getCrossProfileCalendarPackages(admin1);
5356 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5357
5358 final String dummyPackageName = "test";
5359 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5360 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5361 packages = dpm.getCrossProfileCalendarPackages(admin1);
5362 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5363 initializeDpms();
5364 packages = dpm.getCrossProfileCalendarPackages(admin1);
5365 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5366 }
5367
5368 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5369 assertTrue(expected != null);
5370 assertTrue(actual != null);
5371 assertTrue(expected.containsAll(actual));
5372 assertTrue(actual.containsAll(expected));
5373 }
5374
yuemingwdded98f2019-01-30 17:08:12 +00005375 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5376 setAsProfileOwner(admin1);
5377 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5378 when(getServices().settings.settingsSecureGetIntForUser(
5379 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5380 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5381 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5382 }
5383
5384 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5385 final String testPackage = "TEST_PACKAGE";
5386 setAsProfileOwner(admin1);
5387 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5388 when(getServices().settings.settingsSecureGetIntForUser(
5389 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5390 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5391 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5392 }
5393
5394 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5395 final String testPackage = "TEST_PACKAGE";
5396 setAsProfileOwner(admin1);
5397 dpm.setCrossProfileCalendarPackages(admin1, null);
5398 when(getServices().settings.settingsSecureGetIntForUser(
5399 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5400 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5401 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5402 }
5403
Eran Messeribb271892018-10-17 18:27:50 +01005404 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5405 final long ident = mServiceContext.binder.clearCallingIdentity();
5406 mServiceContext.binder.callingUid =
5407 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5408 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005409 dpm.setProfileOwnerCanAccessDeviceIds(who);
Eran Messeribb271892018-10-17 18:27:50 +01005410 });
5411 mServiceContext.binder.restoreCallingIdentity(ident);
5412 }
5413
arangelov08d534b2018-01-22 15:20:53 +00005414 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5415 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5416 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5417 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5418
5419 final long ident = mServiceContext.binder.clearCallingIdentity();
5420 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5421 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5422 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5423 // To simulate a reboot, we just reinitialize dpms and call systemReady
5424 initializeDpms();
5425
5426 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5427 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5428 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5429 assertTrue(dpm.isAdminActive(admin1));
5430 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5431 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5432
5433 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5434 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5435 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5436 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5437
5438 mServiceContext.binder.restoreCallingIdentity(ident);
5439 }
5440
5441 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5442 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5443 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5444 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5445
5446 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5447 DpmMockContext.CALLER_SYSTEM_USER_UID);
5448 setUpPackageManagerForAdmin(admin1, uid);
5449 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5450 // To simulate a reboot, we just reinitialize dpms and call systemReady
5451 initializeDpms();
5452
5453 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5454 assertTrue(dpm.isAdminActive(admin1));
5455 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5456 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5457 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5458 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5459 }
5460
5461 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5462 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5463 metadataManager.deleteMetadataFile();
5464
5465 final TransferOwnershipMetadataManager.Metadata metadata =
5466 new TransferOwnershipMetadataManager.Metadata(
5467 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5468 callerUserHandle,
5469 adminType);
5470 metadataManager.saveMetadataFile(metadata);
5471 }
5472
5473 private File getDeviceOwnerFile() {
5474 return dpms.mOwners.getDeviceOwnerFile();
5475 }
5476
5477 private File getProfileOwnerFile() {
5478 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5479 }
5480
5481 private File getProfileOwnerPoliciesFile() {
5482 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5483 DpmMockContext.CALLER_USER_HANDLE);
5484 return getPoliciesFile(parentDir);
5485 }
5486
5487 private File getDeviceOwnerPoliciesFile() {
5488 return getPoliciesFile(getServices().systemUserDataDir);
5489 }
5490
5491 private File getPoliciesFile(File parentDir) {
5492 return new File(parentDir, "device_policies.xml");
5493 }
5494
5495 private InputStream getRawStream(@RawRes int id) {
5496 return mRealTestContext.getResources().openRawResource(id);
5497 }
5498
Victor Chang3e794af2016-03-04 13:48:17 +00005499 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005500 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005501 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5502 dpms.notifyChangeToContentObserver(
5503 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5504 }
5505
5506 private void assertProvisioningAllowed(String action, boolean expected) {
5507 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5508 dpm.isProvisioningAllowed(action));
5509 }
Tony Mak2f26b792016-11-28 17:54:51 +00005510
Nicolas Prevot45d29072017-01-18 16:11:19 +00005511 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5512 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005513 final String previousPackageName = mContext.packageName;
5514 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005515
5516 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5517 mContext.packageName = packageName;
5518 mMockContext.binder.callingUid = uid;
5519 assertProvisioningAllowed(action, expected);
5520
5521 // Set the previous package name / calling uid to go back to the initial state.
5522 mContext.packageName = previousPackageName;
5523 mMockContext.binder.callingUid = previousUid;
5524 }
5525
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005526 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005527 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5528 }
5529
5530 private void assertCheckProvisioningPreCondition(
5531 String action, String packageName, int provisioningCondition) {
5532 assertEquals("checkProvisioningPreCondition("
5533 + action + ", " + packageName + ") returning unexpected result",
5534 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005535 }
5536
Tony Mak2f26b792016-11-28 17:54:51 +00005537 /**
5538 * Setup a managed profile with the specified admin and its uid.
5539 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5540 * @param adminUid uid of the admin package.
5541 * @param copyFromAdmin package information for {@code admin} will be built based on this
5542 * component's information.
5543 */
5544 private void addManagedProfile(
5545 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5546 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005547 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005548 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5549 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5550 dpm.setActiveAdmin(admin, false, userId);
5551 assertTrue(dpm.setProfileOwner(admin, null, userId));
5552 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5553 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005554
5555 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005556 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005557 */
Robin Leeabaa0692017-02-20 20:54:22 +00005558 private static StringParceledListSlice asSlice(String[] s) {
5559 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005560 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005561
5562 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005563 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5564 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005565
Robin Lee2c68dad2017-03-17 12:50:24 +00005566 // We can't let exceptions happen on the background thread. Throw them here if they happen
5567 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005568 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005569 }
Victor Chang3e794af2016-03-04 13:48:17 +00005570}