blob: f270724cca0c69acbc9fdcb74805c71077c6d05a [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 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
947 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
948 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
949
Makoto Onukic8a5a552015-11-19 14:29:12 -0800950 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700951 }
952
Makoto Onukic8a5a552015-11-19 14:29:12 -0800953 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
954 final int origCallingUser = mContext.binder.callingUid;
955 final List origPermissions = new ArrayList(mContext.callerPermissions);
956 mContext.callerPermissions.clear();
957
958 mContext.callerPermissions.add(permission.MANAGE_USERS);
959
960 mContext.binder.callingUid = Process.SYSTEM_UID;
961
962 // TODO Test getDeviceOwnerName() too. To do so, we need to change
963 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
964 if (hasDeviceOwner) {
965 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
966 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
967 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
968
969 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
970 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
971 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
972 } else {
973 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
974 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
975 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
976
977 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
978 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
979 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
980 }
981
982 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
983 if (hasDeviceOwner) {
984 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
985 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
986 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
987
988 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
989 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
990 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
991 } else {
992 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
993 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
994 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
995
996 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
997 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
998 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
999 }
1000
1001 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1002 // Still with MANAGE_USERS.
1003 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1004 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1005 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1006
1007 if (hasDeviceOwner) {
1008 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1009 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1010 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1011 } else {
1012 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1013 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1014 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1015 }
1016
1017 mContext.binder.callingUid = Process.SYSTEM_UID;
1018 mContext.callerPermissions.remove(permission.MANAGE_USERS);
1019 // System can still call "OnAnyUser" without MANAGE_USERS.
1020 if (hasDeviceOwner) {
1021 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1022 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1023 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1024
1025 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1026 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1027 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1028 } else {
1029 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1030 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1031 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1032
1033 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1034 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1035 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1036 }
1037
1038 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1039 // Still no MANAGE_USERS.
1040 if (hasDeviceOwner) {
1041 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1042 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1043 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1044 } else {
1045 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1046 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1047 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1048 }
1049
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001050 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1051 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1052 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1053 dpm::getDeviceOwnerComponentOnAnyUser);
1054 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1055 dpm::getDeviceOwnerUserId);
1056 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1057 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001058
1059 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1060 // Still no MANAGE_USERS.
1061 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1062 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1063 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1064
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001065 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1066 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1067 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1068 dpm::getDeviceOwnerComponentOnAnyUser);
1069 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1070 dpm::getDeviceOwnerUserId);
1071 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1072 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001073
1074 // Restore.
1075 mContext.binder.callingUid = origCallingUser;
1076 mContext.callerPermissions.addAll(origPermissions);
1077 }
1078
1079
Makoto Onukib643fb02015-09-22 15:03:44 -07001080 /**
1081 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1082 */
1083 public void testSetDeviceOwner_noSuchPackage() {
1084 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001085 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001086 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1087 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1088
1089 // Call from a process on the system user.
1090 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1091
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001092 assertExpectException(IllegalArgumentException.class,
1093 /* messageRegex= */ "Invalid component",
1094 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001095 }
1096
1097 public void testSetDeviceOwner_failures() throws Exception {
1098 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1099 }
1100
Makoto Onukia52562c2015-10-01 16:12:31 -07001101 public void testClearDeviceOwner() throws Exception {
1102 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001103 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001104 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1105 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1106
1107 // Set admin1 as a DA to the secondary user.
1108 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1109
1110 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1111
1112 // Set admin 1 as the DO to the system user.
1113
1114 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1115 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1116 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1117 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1118
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001119 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001120 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001121 eq(admin1.getPackageName()));
1122
Makoto Onukic8a5a552015-11-19 14:29:12 -08001123 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001124
Makoto Onuki90b89652016-01-28 14:44:18 -08001125 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001126 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001127 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001128
1129 assertTrue(dpm.isAdminActive(admin1));
1130 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1131
Makoto Onukia52562c2015-10-01 16:12:31 -07001132 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001133 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001134
1135 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001136 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1137 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001138
1139 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001140 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001141 assertExpectException(IllegalStateException.class,
1142 /* messageRegex= */ "User must be running and unlocked",
1143 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001144
Pavel Grafov75c0a892017-05-18 17:28:27 +01001145 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1146 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001147 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1148
1149 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001150 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001151
Pavel Grafov75c0a892017-05-18 17:28:27 +01001152 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001153 eq(false),
1154 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1155
Pavel Grafov75c0a892017-05-18 17:28:27 +01001156 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001157 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001158 eq(null),
1159 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001160
Sudheer Shanka101c3532018-01-08 16:28:42 -08001161 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1162 null, UserHandle.USER_SYSTEM);
1163
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001164 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001165
1166 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1167 // and once for clearing it.
1168 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1169 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1170 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001171 // TODO Check other calls.
1172 }
1173
Pavel Grafov775b26d82019-10-30 13:29:01 +00001174 public void testDeviceOwnerBackupActivateDeactivate() throws Exception {
1175 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1176 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1177
1178 // Set admin1 as a DA to the secondary user.
1179 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1180 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1181 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1182 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1183
1184 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1185 eq(UserHandle.USER_SYSTEM), eq(false));
1186
1187 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1188
1189 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1190 eq(UserHandle.USER_SYSTEM), eq(true));
1191 }
1192
1193 public void testProfileOwnerBackupActivateDeactivate() throws Exception {
1194 setAsProfileOwner(admin1);
1195
1196 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1197 eq(DpmMockContext.CALLER_USER_HANDLE), eq(false));
1198
1199 dpm.clearProfileOwner(admin1);
1200
1201 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1202 eq(DpmMockContext.CALLER_USER_HANDLE), eq(true));
1203 }
1204
Makoto Onukia52562c2015-10-01 16:12:31 -07001205 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1206 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001207 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001208 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1209 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1210
1211 // Set admin1 as a DA to the secondary user.
1212 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1213
1214 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1215
1216 // Set admin 1 as the DO to the system user.
1217
1218 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1219 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1220 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1221 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1222
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001223 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001224 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001225 eq(admin1.getPackageName()));
1226
Makoto Onukic8a5a552015-11-19 14:29:12 -08001227 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001228
1229 // Now call clear from the secondary user, which should throw.
1230 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1231
1232 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001233 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001234 eq(admin1.getPackageName()),
1235 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001236 assertExpectException(SecurityException.class,
1237 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1238 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001239
Makoto Onukic8a5a552015-11-19 14:29:12 -08001240 // DO shouldn't be removed.
1241 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001242 }
1243
Alex Johnston63220932019-09-26 10:10:51 +01001244 /**
1245 * Test for: {@link DevicePolicyManager#clearDeviceOwnerApp(String)}
1246 *
1247 * Validates that when the device owner is removed, the reset password token is cleared
1248 */
1249 public void testClearDeviceOwner_clearResetPasswordToken() throws Exception {
1250 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1251 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1252 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1253
1254 // Install admin1 on system user
1255 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1256
1257 // Set admin1 to active admin and device owner
1258 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1259 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
1260
1261 // Add reset password token
1262 final long handle = 12000;
1263 final byte[] token = new byte[32];
1264 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
1265 nullable(EscrowTokenStateChangeCallback.class)))
1266 .thenReturn(handle);
1267 assertTrue(dpm.setResetPasswordToken(admin1, token));
1268
1269 // Assert reset password token is active
1270 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle),
1271 eq(UserHandle.USER_SYSTEM)))
1272 .thenReturn(true);
1273 assertTrue(dpm.isResetPasswordTokenActive(admin1));
1274
1275 // Remove the device owner
1276 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1277
1278 // Verify password reset password token was removed
1279 verify(getServices().lockPatternUtils).removeEscrowToken(eq(handle),
1280 eq(UserHandle.USER_SYSTEM));
1281 }
1282
Makoto Onukib643fb02015-09-22 15:03:44 -07001283 public void testSetProfileOwner() throws Exception {
1284 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001285
Makoto Onuki90b89652016-01-28 14:44:18 -08001286 // PO admin can't be deactivated.
1287 dpm.removeActiveAdmin(admin1);
1288 assertTrue(dpm.isAdminActive(admin1));
1289
Makoto Onuki803d6752015-10-30 12:58:39 -07001290 // Try setting DO on the same user, which should fail.
1291 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001292 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1293 runAsCaller(mServiceContext, dpms, dpm -> {
1294 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001295 assertExpectException(IllegalStateException.class,
1296 /* messageRegex= */ "already has a profile owner",
1297 () -> dpm.setDeviceOwner(admin2, "owner-name",
1298 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001299 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001300 }
1301
Makoto Onuki90b89652016-01-28 14:44:18 -08001302 public void testClearProfileOwner() throws Exception {
1303 setAsProfileOwner(admin1);
1304
1305 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1306
1307 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1308 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1309
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001310 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001311 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001312 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001313 assertExpectException(IllegalStateException.class,
1314 /* messageRegex= */ "User must be running and unlocked",
1315 () -> dpm.clearProfileOwner(admin1));
1316
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001317 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001318 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001319 dpm.clearProfileOwner(admin1);
1320
1321 // Check
1322 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001323 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001324 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1325 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001326 }
1327
Makoto Onukib643fb02015-09-22 15:03:44 -07001328 public void testSetProfileOwner_failures() throws Exception {
1329 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1330 }
1331
Makoto Onukia52562c2015-10-01 16:12:31 -07001332 public void testGetDeviceOwnerAdminLocked() throws Exception {
1333 checkDeviceOwnerWithMultipleDeviceAdmins();
1334 }
1335
1336 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1337 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1338 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1339 // make sure it gets the right component from the right user.
1340
1341 final int ANOTHER_USER_ID = 100;
1342 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1343
Pavel Grafov75c0a892017-05-18 17:28:27 +01001344 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001345
1346 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001347 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001348 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1349 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1350
1351 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1352
Pavel Grafov75c0a892017-05-18 17:28:27 +01001353 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001354
Makoto Onukia52562c2015-10-01 16:12:31 -07001355 // Make sure the admin packge is installed to each user.
1356 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1357 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1358
1359 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1360 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1361
1362 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1363
1364
1365 // Set active admins to the users.
1366 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1367 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1368
1369 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1370 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1371
1372 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1373
1374 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001375 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001376 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1377
Makoto Onukic8a5a552015-11-19 14:29:12 -08001378 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001379
1380 // Then check getDeviceOwnerAdminLocked().
1381 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1382 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1383 }
1384
1385 /**
1386 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001387 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1388 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001389 *
1390 * We didn't use to persist the DO component class name, but now we do, and the above method
1391 * finds the right component from a package name upon migration.
1392 */
1393 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001394 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001395 checkDeviceOwnerWithMultipleDeviceAdmins();
1396
1397 // Overwrite the device owner setting and clears the clas name.
1398 dpms.mOwners.setDeviceOwner(
1399 new ComponentName(admin2.getPackageName(), ""),
1400 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1401 dpms.mOwners.writeDeviceOwner();
1402
1403 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001404 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001405
1406 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001407 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001408 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001409 initializeDpms();
1410
1411 // Now the DO component name is a full name.
1412 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1413 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001414 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001415 }
1416
Makoto Onukib643fb02015-09-22 15:03:44 -07001417 public void testSetGetApplicationRestriction() {
1418 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001419 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001420
1421 {
1422 Bundle rest = new Bundle();
1423 rest.putString("KEY_STRING", "Foo1");
1424 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1425 }
1426
1427 {
1428 Bundle rest = new Bundle();
1429 rest.putString("KEY_STRING", "Foo2");
1430 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1431 }
1432
1433 {
1434 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1435 assertNotNull(returned);
1436 assertEquals(returned.size(), 1);
1437 assertEquals(returned.get("KEY_STRING"), "Foo1");
1438 }
1439
1440 {
1441 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1442 assertNotNull(returned);
1443 assertEquals(returned.size(), 1);
1444 assertEquals(returned.get("KEY_STRING"), "Foo2");
1445 }
1446
1447 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1448 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1449 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001450
Edman Anjosf9946772016-11-28 16:35:15 +01001451 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001452 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1453 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001454 *
1455 * @param packageName the name of the package to be setup
1456 * @param appId the application ID to be given to the package
1457 * @return the UID of the package as known by the mock package manager
1458 */
1459 private int setupPackageInPackageManager(final String packageName, final int appId)
1460 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001461 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001462 ApplicationInfo.FLAG_HAS_CODE);
1463 }
1464
1465 /**
1466 * Setup a package in the package manager mock. Useful for faking installed applications.
1467 *
1468 * @param packageName the name of the package to be setup
1469 * @param userId the user id where the package will be "installed"
1470 * @param appId the application ID to be given to the package
1471 * @param flags flags to set in the ApplicationInfo for this package
1472 * @return the UID of the package as known by the mock package manager
1473 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001474 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1475 int flags) throws Exception {
1476 final int uid = UserHandle.getUid(userId, appId);
1477 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001478 final PackageInfo pi = new PackageInfo();
1479 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001480 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001481 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001482 eq(packageName),
1483 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001484 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001485 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001486 eq(packageName),
1487 anyInt(),
1488 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001489 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001490 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001491 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001492 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001493 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001494 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001495 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001496 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001497 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001498 return uid;
1499 }
1500
Robin Lee7f5c91c2017-02-08 21:27:02 +00001501 public void testCertificateDisclosure() throws Exception {
1502 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1503 final UserHandle user = UserHandle.of(userId);
1504
1505 mContext.applicationInfo = new ApplicationInfo();
1506 mContext.callerPermissions.add(permission.MANAGE_USERS);
1507 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001508 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001509 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1510
Robin Leeabaa0692017-02-20 20:54:22 +00001511 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1512 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001513
1514 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1515 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1516
1517 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001518 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001519 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001520 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001521 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001522 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001523 .cancelAsUser(anyString(), anyInt(), eq(user));
1524
1525 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001526 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001527 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001528 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1529 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001530 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001531 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001532 .notifyAsUser(anyString(), anyInt(), argThat(
1533 new BaseMatcher<Notification>() {
1534 @Override
1535 public boolean matches(Object item) {
1536 final Notification noti = (Notification) item;
1537 return TEST_STRING.equals(
1538 noti.extras.getString(Notification.EXTRA_TITLE));
1539 }
1540 @Override
1541 public void describeTo(Description description) {
1542 description.appendText(
1543 "Notification{title=\"" + TEST_STRING + "\"}");
1544 }
1545 }), eq(user));
1546 }
1547
Edman Anjosf9946772016-11-28 16:35:15 +01001548 /**
1549 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1550 * privileges can acually be exercised by a delegate are not covered here.
1551 */
1552 public void testDelegation() throws Exception {
1553 setAsProfileOwner(admin1);
1554
1555 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1556
1557 // Given two packages
1558 final String CERT_DELEGATE = "com.delegate.certs";
1559 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1560 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1561 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1562 20989);
1563
1564 // On delegation
1565 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1566 mContext.packageName = admin1.getPackageName();
1567 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1568 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1569
1570 // DPMS correctly stores and retrieves the delegates
1571 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1572 assertEquals(2, policy.mDelegationMap.size());
1573 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1574 DELEGATION_CERT_INSTALL);
1575 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1576 DELEGATION_CERT_INSTALL);
1577 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1578 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1579 DELEGATION_APP_RESTRICTIONS);
1580 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1581 DELEGATION_APP_RESTRICTIONS);
1582 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1583
1584 // On calling install certificate APIs from an unauthorized process
1585 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1586 mContext.packageName = RESTRICTIONS_DELEGATE;
1587
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001588 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1589 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001590
1591 // On calling install certificate APIs from an authorized process
1592 mContext.binder.callingUid = CERT_DELEGATE_UID;
1593 mContext.packageName = CERT_DELEGATE;
1594
1595 // DPMS executes without a SecurityException
1596 try {
1597 dpm.installCaCert(null, null);
1598 } catch (SecurityException unexpected) {
1599 fail("Threw SecurityException on authorized access");
1600 } catch (NullPointerException expected) {
1601 }
1602
1603 // On removing a delegate
1604 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1605 mContext.packageName = admin1.getPackageName();
1606 dpm.setCertInstallerPackage(admin1, null);
1607
1608 // DPMS does not allow access to ex-delegate
1609 mContext.binder.callingUid = CERT_DELEGATE_UID;
1610 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001611 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1612 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001613
1614 // But still allows access to other existing delegates
1615 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1616 mContext.packageName = RESTRICTIONS_DELEGATE;
1617 try {
1618 dpm.getApplicationRestrictions(null, "pkg");
1619 } catch (SecurityException expected) {
1620 fail("Threw SecurityException on authorized access");
1621 }
1622 }
1623
Esteban Talaverabf60f722015-12-10 16:26:44 +00001624 public void testApplicationRestrictionsManagingApp() throws Exception {
1625 setAsProfileOwner(admin1);
1626
Rubin Xued1928a2016-02-11 17:23:06 +00001627 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001628 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001629 final String nonDelegateExceptionMessageRegex =
1630 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001631 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001632 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1633 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001634
Esteban Talaverabf60f722015-12-10 16:26:44 +00001635 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1636 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001637 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1638 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001639 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001640 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001641 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001642 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1643 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001644
1645 // Check via the profile owner that no restrictions were set.
1646 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001647 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001648 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1649
Rubin Xued1928a2016-02-11 17:23:06 +00001650 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001651 assertExpectException(PackageManager.NameNotFoundException.class,
1652 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1653 () -> dpm.setApplicationRestrictionsManagingPackage(
1654 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001655
Esteban Talaverabf60f722015-12-10 16:26:44 +00001656 // Let appRestrictionsManagerPackage manage app restrictions
1657 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1658 assertEquals(appRestrictionsManagerPackage,
1659 dpm.getApplicationRestrictionsManagingPackage(admin1));
1660
1661 // Now that package should be able to set and retrieve app restrictions.
1662 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001663 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001664 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1665 dpm.setApplicationRestrictions(null, "pkg1", rest);
1666 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1667 assertEquals(1, returned.size(), 1);
1668 assertEquals("Foo1", returned.get("KEY_STRING"));
1669
1670 // The same app running on a separate user shouldn't be able to manage app restrictions.
1671 mContext.binder.callingUid = UserHandle.getUid(
1672 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1673 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001674 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1675 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001676
1677 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1678 // too.
1679 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001680 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001681 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1682 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1683 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1684
1685 // Removing the ability for the package to manage app restrictions.
1686 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1687 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1688 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001689 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001690 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001691 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1692 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001693 }
1694
Makoto Onukia4f11972015-10-01 13:19:58 -07001695 public void testSetUserRestriction_asDo() throws Exception {
1696 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001697 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001698 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1699 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1700
1701 // First, set DO.
1702
1703 // Call from a process on the system user.
1704 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1705
1706 // Make sure admin1 is installed on system user.
1707 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001708
1709 // Call.
1710 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001711 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001712 UserHandle.USER_SYSTEM));
1713
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001714 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001715 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001716 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001717 DpmTestUtils.assertRestrictions(
1718 DpmTestUtils.newRestrictions(defaultRestrictions),
1719 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1720 );
1721 DpmTestUtils.assertRestrictions(
1722 DpmTestUtils.newRestrictions(defaultRestrictions),
1723 dpm.getUserRestrictions(admin1)
1724 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001725 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001726 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001727 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001728 eq(true) /* isDeviceOwner */,
1729 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001730 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001731 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001732
1733 for (String restriction : defaultRestrictions) {
1734 dpm.clearUserRestriction(admin1, restriction);
1735 }
1736
Esteban Talavera548a04b2016-12-20 15:22:30 +00001737 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001738 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739
1740 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001741 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001742 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001743 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1744 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001745 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001746
Makoto Onukia4f11972015-10-01 13:19:58 -07001747 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001748 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001749 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001750 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1751 UserManager.DISALLOW_ADD_USER),
1752 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001753 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001754
Makoto Onuki068c54a2015-10-13 14:34:03 -07001755 DpmTestUtils.assertRestrictions(
1756 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001757 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001758 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1759 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001760 DpmTestUtils.assertRestrictions(
1761 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001762 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001763 dpm.getUserRestrictions(admin1)
1764 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001765
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001766 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001767 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001768 eq(UserHandle.USER_SYSTEM),
1769 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001770 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001771 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001772
Makoto Onuki068c54a2015-10-13 14:34:03 -07001773 DpmTestUtils.assertRestrictions(
1774 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1775 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1776 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001777 DpmTestUtils.assertRestrictions(
1778 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1779 dpm.getUserRestrictions(admin1)
1780 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001781
1782 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001783 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001784 eq(UserHandle.USER_SYSTEM),
1785 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001786 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001787 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001788
Esteban Talavera548a04b2016-12-20 15:22:30 +00001789 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001790
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001791 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1792 // DO sets them, the scope is global.
1793 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001794 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001795 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001796 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001797 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001798 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001799 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1800 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001801 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001802
1803 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1804 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001805 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001806
1807 // More tests.
1808 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001809 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001810 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001811 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1812 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001813 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001814
1815 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001816 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001817 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001818 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001819 UserManager.DISALLOW_ADD_USER),
1820 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001821 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001822
1823 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001824 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001825 eq(UserHandle.USER_SYSTEM),
1826 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001827 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001828 UserManager.DISALLOW_ADD_USER),
1829 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001830 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001831 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001832
Eric Sandnessca5969d2018-08-10 13:28:46 +01001833 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1834 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1835 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001836
Eric Sandnessca5969d2018-08-10 13:28:46 +01001837 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1838 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001839
Eric Sandnessca5969d2018-08-10 13:28:46 +01001840 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1841 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1842 () -> dpm.setCameraDisabled(admin1, true));
1843 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1844
1845 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1846 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1847 () -> dpm.setKeyguardDisabledFeatures(admin1,
1848 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1849 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1850
1851 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1852 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1853 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1854 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1855
1856 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1857 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1858 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1859 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001860 }
1861
1862 public void testSetUserRestriction_asPo() {
1863 setAsProfileOwner(admin1);
1864
Makoto Onuki068c54a2015-10-13 14:34:03 -07001865 DpmTestUtils.assertRestrictions(
1866 DpmTestUtils.newRestrictions(),
1867 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1868 .ensureUserRestrictions()
1869 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001870
1871 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001872 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001873 eq(DpmMockContext.CALLER_USER_HANDLE),
1874 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001875 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001876 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001877
Makoto Onukia4f11972015-10-01 13:19:58 -07001878 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001879 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001880 eq(DpmMockContext.CALLER_USER_HANDLE),
1881 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1882 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001883 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001884 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001885
Makoto Onuki068c54a2015-10-13 14:34:03 -07001886 DpmTestUtils.assertRestrictions(
1887 DpmTestUtils.newRestrictions(
1888 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1889 UserManager.DISALLOW_OUTGOING_CALLS
1890 ),
1891 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1892 .ensureUserRestrictions()
1893 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001894 DpmTestUtils.assertRestrictions(
1895 DpmTestUtils.newRestrictions(
1896 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1897 UserManager.DISALLOW_OUTGOING_CALLS
1898 ),
1899 dpm.getUserRestrictions(admin1)
1900 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001901
1902 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001903 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001904 eq(DpmMockContext.CALLER_USER_HANDLE),
1905 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001906 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001907 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001908
1909 DpmTestUtils.assertRestrictions(
1910 DpmTestUtils.newRestrictions(
1911 UserManager.DISALLOW_OUTGOING_CALLS
1912 ),
1913 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1914 .ensureUserRestrictions()
1915 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001916 DpmTestUtils.assertRestrictions(
1917 DpmTestUtils.newRestrictions(
1918 UserManager.DISALLOW_OUTGOING_CALLS
1919 ),
1920 dpm.getUserRestrictions(admin1)
1921 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001922
1923 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001924 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001925 eq(DpmMockContext.CALLER_USER_HANDLE),
1926 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001927 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001928 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001929
Makoto Onuki068c54a2015-10-13 14:34:03 -07001930 DpmTestUtils.assertRestrictions(
1931 DpmTestUtils.newRestrictions(),
1932 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1933 .ensureUserRestrictions()
1934 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001935 DpmTestUtils.assertRestrictions(
1936 DpmTestUtils.newRestrictions(),
1937 dpm.getUserRestrictions(admin1)
1938 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001939
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001940 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1941 // though when DO sets them they'll be applied globally.
1942 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001943 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001944 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001945 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001946 eq(DpmMockContext.CALLER_USER_HANDLE),
1947 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1948 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001949 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001950 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001951
1952 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001953 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001954 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001955 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001956 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001957 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001958 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001959
Makoto Onukia4f11972015-10-01 13:19:58 -07001960 // TODO Make sure restrictions are written to the file.
1961 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001962
Esteban Talavera548a04b2016-12-20 15:22:30 +00001963
1964 public void testDefaultEnabledUserRestrictions() throws Exception {
1965 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1966 mContext.callerPermissions.add(permission.MANAGE_USERS);
1967 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1968 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1969
1970 // First, set DO.
1971
1972 // Call from a process on the system user.
1973 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1974
1975 // Make sure admin1 is installed on system user.
1976 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1977
1978 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1979 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1980 UserHandle.USER_SYSTEM));
1981
1982 // Check that the user restrictions that are enabled by default are set. Then unset them.
1983 String[] defaultRestrictions = UserRestrictionsUtils
1984 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1985 assertTrue(defaultRestrictions.length > 0);
1986 DpmTestUtils.assertRestrictions(
1987 DpmTestUtils.newRestrictions(defaultRestrictions),
1988 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1989 );
1990 DpmTestUtils.assertRestrictions(
1991 DpmTestUtils.newRestrictions(defaultRestrictions),
1992 dpm.getUserRestrictions(admin1)
1993 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001994 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001995 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001996 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001997 eq(true) /* isDeviceOwner */,
1998 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001999 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002000 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002001
2002 for (String restriction : defaultRestrictions) {
2003 dpm.clearUserRestriction(admin1, restriction);
2004 }
2005
2006 assertNoDeviceOwnerRestrictions();
2007
2008 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002009 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002010 initializeDpms();
2011 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2012 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2013
2014 assertNoDeviceOwnerRestrictions();
2015
2016 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
2017 // is set as it wasn't enabled during setDeviceOwner.
2018 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
2019 assertFalse(UserRestrictionsUtils
2020 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
2021 UserRestrictionsUtils
2022 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
2023 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002024 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002025 initializeDpms();
2026 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2027 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2028
2029 DpmTestUtils.assertRestrictions(
2030 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
2031 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2032 );
2033 DpmTestUtils.assertRestrictions(
2034 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
2035 dpm.getUserRestrictions(admin1)
2036 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002037 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00002038 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00002039 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01002040 eq(true) /* isDeviceOwner */,
2041 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00002042 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002043 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002044
2045 // Remove the restriction.
2046 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
2047
2048 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
2049 initializeDpms();
2050 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2051 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2052 assertNoDeviceOwnerRestrictions();
2053 } finally {
2054 UserRestrictionsUtils
2055 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
2056 }
2057 }
2058
2059 private void assertNoDeviceOwnerRestrictions() {
2060 DpmTestUtils.assertRestrictions(
2061 DpmTestUtils.newRestrictions(),
2062 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2063 );
2064 DpmTestUtils.assertRestrictions(
2065 DpmTestUtils.newRestrictions(),
2066 dpm.getUserRestrictions(admin1)
2067 );
2068 }
2069
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002070 public void testGetMacAddress() throws Exception {
2071 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2072 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2073 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2074
2075 // In this test, change the caller user to "system".
2076 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2077
2078 // Make sure admin1 is installed on system user.
2079 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2080
2081 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002082 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
2083 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002084
2085 // DO needs to be an DA.
2086 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2087 assertTrue(dpm.isAdminActive(admin1));
2088
2089 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002090 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2091 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002092
2093 // Test 3. Caller has PO, but not DO.
2094 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002095 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2096 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002097
2098 // Remove PO.
2099 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002100 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002101 // Test 4, Caller is DO now.
2102 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2103
xshu425b9a62018-12-13 14:18:18 -08002104 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002105 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002106
xshu425b9a62018-12-13 14:18:18 -08002107 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2108 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002109 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002110
2111 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002112 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2113 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002114 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002115 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002116
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002117 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002118 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2119 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2120
2121 // In this test, change the caller user to "system".
2122 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2123
2124 // Make sure admin1 is installed on system user.
2125 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2126
2127 // Set admin1 as DA.
2128 dpm.setActiveAdmin(admin1, false);
2129 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002130 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2131 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002132
2133 // Set admin1 as PO.
2134 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002135 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2136 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002137
2138 // Remove PO and add DO.
2139 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002140 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002141 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2142
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002143 // admin1 is DO.
2144 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002145 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002146 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002147 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2148 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002149
2150 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002151 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002152 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002153 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2154 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002155
2156 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002157 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002158 dpm.reboot(admin1);
2159 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002160
2161 public void testSetGetSupportText() {
2162 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2163 dpm.setActiveAdmin(admin1, true);
2164 dpm.setActiveAdmin(admin2, true);
2165 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2166
2167 // Null default support messages.
2168 {
2169 assertNull(dpm.getLongSupportMessage(admin1));
2170 assertNull(dpm.getShortSupportMessage(admin1));
2171 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2172 assertNull(dpm.getShortSupportMessageForUser(admin1,
2173 DpmMockContext.CALLER_USER_HANDLE));
2174 assertNull(dpm.getLongSupportMessageForUser(admin1,
2175 DpmMockContext.CALLER_USER_HANDLE));
2176 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2177 }
2178
2179 // Only system can call the per user versions.
2180 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002181 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2182 () -> dpm.getShortSupportMessageForUser(admin1,
2183 DpmMockContext.CALLER_USER_HANDLE));
2184 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2185 () -> dpm.getLongSupportMessageForUser(admin1,
2186 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002187 }
2188
2189 // Can't set message for admin in another uid.
2190 {
2191 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002192 assertExpectException(SecurityException.class,
2193 /* messageRegex= */ "is not owned by uid",
2194 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002195 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2196 }
2197
2198 // Set/Get short returns what it sets and other admins text isn't changed.
2199 {
2200 final String supportText = "Some text to test with.";
2201 dpm.setShortSupportMessage(admin1, supportText);
2202 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2203 assertNull(dpm.getLongSupportMessage(admin1));
2204 assertNull(dpm.getShortSupportMessage(admin2));
2205
2206 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2207 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2208 DpmMockContext.CALLER_USER_HANDLE));
2209 assertNull(dpm.getShortSupportMessageForUser(admin2,
2210 DpmMockContext.CALLER_USER_HANDLE));
2211 assertNull(dpm.getLongSupportMessageForUser(admin1,
2212 DpmMockContext.CALLER_USER_HANDLE));
2213 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2214
2215 dpm.setShortSupportMessage(admin1, null);
2216 assertNull(dpm.getShortSupportMessage(admin1));
2217 }
2218
2219 // Set/Get long returns what it sets and other admins text isn't changed.
2220 {
2221 final String supportText = "Some text to test with.\nWith more text.";
2222 dpm.setLongSupportMessage(admin1, supportText);
2223 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2224 assertNull(dpm.getShortSupportMessage(admin1));
2225 assertNull(dpm.getLongSupportMessage(admin2));
2226
2227 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2228 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2229 DpmMockContext.CALLER_USER_HANDLE));
2230 assertNull(dpm.getLongSupportMessageForUser(admin2,
2231 DpmMockContext.CALLER_USER_HANDLE));
2232 assertNull(dpm.getShortSupportMessageForUser(admin1,
2233 DpmMockContext.CALLER_USER_HANDLE));
2234 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2235
2236 dpm.setLongSupportMessage(admin1, null);
2237 assertNull(dpm.getLongSupportMessage(admin1));
2238 }
2239 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002240
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002241 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002242 setAsProfileOwner(admin1);
2243
2244 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002245 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002246
2247 // Setup
2248 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2249 final String package1 = "com.example.one";
2250 final String package2 = "com.example.two";
2251 pkgsToRestrict.add(package1);
2252 pkgsToRestrict.add(package2);
2253 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2254 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002255 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002256
2257 // Verify
2258 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002259 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002260 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2261 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2262 eq(DpmMockContext.CALLER_USER_HANDLE));
2263
2264 // Setup
2265 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002266 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002267
2268 // Verify
2269 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002270 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002271 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2272 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2273 eq(DpmMockContext.CALLER_USER_HANDLE));
2274 }
2275
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002276 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002277 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2278 dpm.setActiveAdmin(admin1, true);
2279 assertTrue(dpm.isAdminActive(admin1));
2280 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2281
2282 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002283 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002284 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002285 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002286 }
2287
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002288 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002289 setAsProfileOwner(admin1);
2290
2291 // Setup
2292 final ArrayList<String> emptyList = new ArrayList<>();
2293 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2294 final String package1 = "com.example.one";
2295 final String package2 = "com.example.two";
2296 final String package3 = "com.example.three";
2297 pkgsToRestrict.add(package1);
2298 pkgsToRestrict.add(package2);
2299 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2300 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002301 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002302
2303 // Verify
2304 assertEquals(emptyList, excludedPkgs);
2305 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2306 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002307 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002308 DpmMockContext.CALLER_USER_HANDLE));
2309 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002310 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002311 DpmMockContext.CALLER_USER_HANDLE));
2312 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002313 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002314 DpmMockContext.CALLER_USER_HANDLE));
2315 }
2316
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002317 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002318 setAsProfileOwner(admin1);
2319 assertExpectException(SecurityException.class,
2320 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002321 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002322 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2323 dpm.clearProfileOwner(admin1);
2324
2325 setDeviceOwner();
2326 assertExpectException(SecurityException.class,
2327 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002328 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002329 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2330 clearDeviceOwner();
2331 }
2332
phweiss73145f42017-01-17 19:06:38 +01002333 public void testCreateAdminSupportIntent() throws Exception {
2334 // Setup device owner.
2335 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2336 setupDeviceOwner();
2337
2338 // Nonexisting permission returns null
2339 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2340 assertNull(intent);
2341
2342 // Existing permission that is not set returns null
2343 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2344 assertNull(intent);
2345
2346 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002347 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002348 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2349 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2350 .thenReturn(true);
2351 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2352 assertNull(intent);
2353
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002354 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2355 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2356 new UserManager.EnforcingUser(
2357 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2358 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002359 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002360 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002361 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2362 assertNotNull(intent);
2363 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2364 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2365 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002366 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002367 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2368 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2369
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002370 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2371 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002372
2373 // Camera is not disabled
2374 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2375 assertNull(intent);
2376
2377 // Camera is disabled
2378 dpm.setCameraDisabled(admin1, true);
2379 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2380 assertNotNull(intent);
2381 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2382 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2383
2384 // Screen capture is not disabled
2385 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2386 assertNull(intent);
2387
2388 // Screen capture is disabled
2389 dpm.setScreenCaptureDisabled(admin1, true);
2390 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2391 assertNotNull(intent);
2392 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2393 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2394
2395 // Same checks for different user
2396 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2397 // Camera should be disabled by device owner
2398 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2399 assertNotNull(intent);
2400 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2401 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2402 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2403 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2404 // ScreenCapture should not be disabled by device owner
2405 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2406 assertNull(intent);
2407 }
2408
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002409 /**
2410 * Test for:
2411 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002412 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002413 * {@link DevicePolicyManager#isAffiliatedUser}
2414 */
2415 public void testUserAffiliation() throws Exception {
2416 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2417 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2418 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2419
2420 // Check that the system user is unaffiliated.
2421 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2422 assertFalse(dpm.isAffiliatedUser());
2423
2424 // Set a device owner on the system user. Check that the system user becomes affiliated.
2425 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2426 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2427 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2428 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002429 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002430
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002431 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002432 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2433 setAsProfileOwner(admin2);
2434 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002435 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002436
2437 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2438 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002439 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002440 userAffiliationIds.add("red");
2441 userAffiliationIds.add("green");
2442 userAffiliationIds.add("blue");
2443 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002444 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002445 assertFalse(dpm.isAffiliatedUser());
2446
2447 // Have the device owner specify a set of affiliation ids that do not intersect with those
2448 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002449 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002450 deviceAffiliationIds.add("cyan");
2451 deviceAffiliationIds.add("yellow");
2452 deviceAffiliationIds.add("magenta");
2453 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2454 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002455 MoreAsserts.assertContentsInAnyOrder(
2456 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002457 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2458 assertFalse(dpm.isAffiliatedUser());
2459
2460 // Have the profile owner specify a set of affiliation ids that intersect with those
2461 // specified by the device owner. Check that the test user becomes affiliated.
2462 userAffiliationIds.add("yellow");
2463 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002464 MoreAsserts.assertContentsInAnyOrder(
2465 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002466 assertTrue(dpm.isAffiliatedUser());
2467
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002468 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002469 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002470 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002471 assertFalse(dpm.isAffiliatedUser());
2472
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002473 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2474 dpm.setAffiliationIds(admin2, userAffiliationIds);
2475 assertTrue(dpm.isAffiliatedUser());
2476 dpm.clearProfileOwner(admin2);
2477 assertFalse(dpm.isAffiliatedUser());
2478
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002479 // Check that the system user remains affiliated.
2480 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2481 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002482
2483 // Clear the device owner - the user becomes unaffiliated.
2484 clearDeviceOwner();
2485 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002486 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002487
2488 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002489 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002490 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2491 }
2492
2493 public void testSetUserProvisioningState_permission() throws Exception {
2494 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002495
2496 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2497 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2498 }
2499
2500 public void testSetUserProvisioningState_unprivileged() throws Exception {
2501 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002502 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2503 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2504 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002505 }
2506
2507 public void testSetUserProvisioningState_noManagement() {
2508 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002509 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002510 assertExpectException(IllegalStateException.class,
2511 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2512 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2513 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002514 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2515 }
2516
2517 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2518 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2519 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002520
2521 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2522 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2523 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2524 }
2525
2526 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2527 throws Exception {
2528 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2529 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002530
2531 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2532 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2533 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2534 }
2535
2536 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2537 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2538 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002539
2540 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2541 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2542 }
2543
2544 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2545 throws Exception {
2546 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002547
2548 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2549 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2550 DevicePolicyManager.STATE_USER_UNMANAGED);
2551 }
2552
2553 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2554 throws Exception {
2555 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002556
2557 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2558 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2559 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2560 }
2561
2562 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2563 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002564
2565 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2566 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2567 }
2568
2569 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2570 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002571
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002572 assertExpectException(IllegalStateException.class,
2573 /* messageRegex= */ "Cannot move to user provisioning state",
2574 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2575 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2576 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002577 }
2578
2579 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2580 throws Exception {
2581 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002582
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002583 assertExpectException(IllegalStateException.class,
2584 /* messageRegex= */ "Cannot move to user provisioning state",
2585 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2586 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2587 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002588 }
2589
2590 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002591 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2592 mContext.callerPermissions.add(permission.MANAGE_USERS);
2593
Alan Treadwayafad8782016-01-19 15:15:08 +00002594 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2595 for (int state : states) {
2596 dpm.setUserProvisioningState(state, userId);
2597 assertEquals(state, dpm.getUserProvisioningState());
2598 }
2599 }
2600
2601 private void setupProfileOwner() throws Exception {
2602 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2603
2604 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2605 dpm.setActiveAdmin(admin1, false);
2606 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2607
2608 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2609 }
2610
2611 private void setupDeviceOwner() throws Exception {
2612 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2613
2614 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2615 dpm.setActiveAdmin(admin1, false);
2616 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2617
2618 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2619 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002620
2621 public void testSetMaximumTimeToLock() {
2622 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2623
2624 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2625 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2626
Pavel Grafov75c0a892017-05-18 17:28:27 +01002627 reset(getServices().powerManagerInternal);
2628 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002629
2630 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002631 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2632 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002633 reset(getServices().powerManagerInternal);
2634 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002635
2636 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002637 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2638 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002639 reset(getServices().powerManagerInternal);
2640 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002641
2642 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002643 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2644 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002645 reset(getServices().powerManagerInternal);
2646 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002647
2648 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002649 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2650 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002651 reset(getServices().powerManagerInternal);
2652 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002653
2654 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002655 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2656 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002657 reset(getServices().powerManagerInternal);
2658 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002659
2660 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002661 reset(getServices().powerManagerInternal);
2662 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002663
Pavel Grafov28939982017-10-03 15:11:52 +01002664 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2665 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2666 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002667 reset(getServices().powerManagerInternal);
2668 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002669
2670 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002671 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2672 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002673 reset(getServices().powerManagerInternal);
2674 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002675
Pavel Grafov28939982017-10-03 15:11:52 +01002676 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002677 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002678 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2679 verifyStayOnWhilePluggedCleared(false);
2680 }
2681
Varun Shahb472b8f2019-09-23 23:01:06 -07002682 public void testIsActiveSupervisionApp() throws Exception {
2683 when(mServiceContext.resources
2684 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
2685 .thenReturn(admin1.flattenToString());
2686
2687 final int PROFILE_USER = 15;
2688 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2689 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2690 mContext.binder.callingUid = PROFILE_ADMIN;
2691
2692 final DevicePolicyManagerInternal dpmi =
2693 LocalServices.getService(DevicePolicyManagerInternal.class);
2694 assertTrue(dpmi.isActiveSupervisionApp(PROFILE_ADMIN));
2695 }
2696
Pavel Grafov28939982017-10-03 15:11:52 +01002697 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2698 // uses separate challenge.
2699 public void testSetMaximumTimeToLockProfile() throws Exception {
2700 final int PROFILE_USER = 15;
2701 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2702 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2703 mContext.binder.callingUid = PROFILE_ADMIN;
2704 final DevicePolicyManagerInternal dpmi =
2705 LocalServices.getService(DevicePolicyManagerInternal.class);
2706
2707 dpm.setMaximumTimeToLock(admin1, 0);
2708
2709 reset(getServices().powerManagerInternal);
2710 reset(getServices().settings);
2711
2712 // First add timeout for the profile.
2713 dpm.setMaximumTimeToLock(admin1, 10);
2714 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2715
2716 reset(getServices().powerManagerInternal);
2717 reset(getServices().settings);
2718
2719 // Add separate challenge
2720 when(getServices().lockPatternUtils
2721 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2722 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2723
2724 verifyScreenTimeoutCall(10L, PROFILE_USER);
2725 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2726
2727 reset(getServices().powerManagerInternal);
2728 reset(getServices().settings);
2729
2730 // Remove the timeout.
2731 dpm.setMaximumTimeToLock(admin1, 0);
2732 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2733 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2734
2735 reset(getServices().powerManagerInternal);
2736 reset(getServices().settings);
2737
2738 // Add it back.
2739 dpm.setMaximumTimeToLock(admin1, 10);
2740 verifyScreenTimeoutCall(10L, PROFILE_USER);
2741 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2742
2743 reset(getServices().powerManagerInternal);
2744 reset(getServices().settings);
2745
2746 // Remove separate challenge.
2747 reset(getServices().lockPatternUtils);
2748 when(getServices().lockPatternUtils
2749 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2750 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002751 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002752
2753 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2754 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2755
2756 reset(getServices().powerManagerInternal);
2757 reset(getServices().settings);
2758
2759 // Remove the timeout.
2760 dpm.setMaximumTimeToLock(admin1, 0);
2761 verifyScreenTimeoutCall(null, PROFILE_USER);
2762 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002763 }
2764
Michal Karpinski943aabd2016-10-06 11:09:25 +01002765 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2766 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2767 setupDeviceOwner();
2768 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2769
Michal Karpinskid084ca52017-01-18 15:54:18 +00002770 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2771 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2772 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2773 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2774 - ONE_MINUTE;
2775
2776 // verify that the minimum timeout cannot be modified on user builds (system property is
2777 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002778 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002779
2780 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2781 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2782 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2783
Pavel Grafov75c0a892017-05-18 17:28:27 +01002784 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002785
2786 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002787 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002788
Michal Karpinskid084ca52017-01-18 15:54:18 +00002789 // reset to default (0 means the admin is not participating, so default should be returned)
2790 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002791
2792 // aggregation should be the default if unset by any admin
2793 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2794 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2795
2796 // admin not participating by default
2797 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2798
2799 //clamping from the top
2800 dpm.setRequiredStrongAuthTimeout(admin1,
2801 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2802 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2803 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2804 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2805 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2806
Michal Karpinskid084ca52017-01-18 15:54:18 +00002807 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002808 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2809 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2810 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2811 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2812
2813 // clamping from the bottom
2814 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2815 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2816 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2817
Michal Karpinskid084ca52017-01-18 15:54:18 +00002818 // values within range
2819 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2820 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2821 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2822
2823 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2824 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2825 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002826
2827 // reset to default
2828 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2829 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2830 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2831 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2832
2833 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002834 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2835 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002836 }
2837
Pavel Grafov28939982017-10-03 15:11:52 +01002838 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002839 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002840 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002841 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002842 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002843 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002844 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002845 }
Pavel Grafov28939982017-10-03 15:11:52 +01002846 }
2847
2848 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002849 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2850 // UnfinishedVerificationException.
2851 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002852
Esteban Talavera01576862016-12-15 11:16:44 +00002853 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002854 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002855 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002856 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002857 .thenReturn(false);
2858 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002859 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2860 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002861 .thenReturn(true);
2862 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2863
2864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002865 }
Victor Chang3e794af2016-03-04 13:48:17 +00002866
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002867 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2868 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002869 mContext.packageName = admin1.getPackageName();
2870 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002871 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2872 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2873 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2874 false);
2875 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2876 }
2877
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002878 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2879 setup_DeviceAdminFeatureOff();
2880 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2881 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2882 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2883 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2884 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2885 assertCheckProvisioningPreCondition(
2886 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2887 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2888 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2889 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2890 }
2891
Esteban Talavera01576862016-12-15 11:16:44 +00002892 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002893 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002894 .thenReturn(false);
2895 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002896 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2897 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002898 .thenReturn(true);
2899 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2900
2901 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002902 }
Victor Chang3e794af2016-03-04 13:48:17 +00002903
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002904 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2905 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002906 mContext.packageName = admin1.getPackageName();
2907 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002908 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2909 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2910 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2911 false);
2912 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2913
2914 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002915 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002916 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2917 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2918 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2919 true);
2920 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2921 }
2922
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002923 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2924 setup_ManagedProfileFeatureOff();
2925 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2926 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2927 DevicePolicyManager.CODE_OK);
2928 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2929 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2930 assertCheckProvisioningPreCondition(
2931 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2932 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2933 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2934 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2935
2936 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002937 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002938 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2939 DevicePolicyManager.CODE_OK);
2940 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2941 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2942 assertCheckProvisioningPreCondition(
2943 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2944 DevicePolicyManager.CODE_OK);
2945 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2946 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2947 }
2948
Esteban Talavera01576862016-12-15 11:16:44 +00002949 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002950 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002951 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002952 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2953 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002954 .thenReturn(true);
2955 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2956
2957 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002958 }
Victor Chang3e794af2016-03-04 13:48:17 +00002959
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002960 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2961 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002962 mContext.packageName = admin1.getPackageName();
2963 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002964 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2965 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2966 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2967 false /* because of non-split user */);
2968 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2969 false /* because of non-split user */);
2970 }
2971
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002972 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002973 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002974 setup_nonSplitUser_firstBoot_primaryUser();
2975 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2976 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2977 DevicePolicyManager.CODE_OK);
2978 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2979 DevicePolicyManager.CODE_OK);
2980 assertCheckProvisioningPreCondition(
2981 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2982 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2983 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2984 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2985 }
2986
Esteban Talavera01576862016-12-15 11:16:44 +00002987 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002988 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002989 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002990 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2991 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002992 .thenReturn(true);
2993 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2994
2995 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002996 }
Victor Chang3e794af2016-03-04 13:48:17 +00002997
Nicolas Prevot45d29072017-01-18 16:11:19 +00002998 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2999 setDeviceOwner();
3000 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3001 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
3002 }
3003
3004 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
3005 setup_nonSplitUser_withDo_primaryUser();
3006 final int MANAGED_PROFILE_USER_ID = 18;
3007 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
3008 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003009 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003010 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003011 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003012 true)).thenReturn(true);
3013 }
3014
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003015 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
3016 throws Exception {
3017 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003018 mContext.packageName = admin1.getPackageName();
3019 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003020 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3021 false/* because of completed device setup */);
3022 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3023 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3024 false/* because of non-split user */);
3025 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3026 false/* because of non-split user */);
3027 }
3028
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003029 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
3030 throws Exception {
3031 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3032 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3033 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3034 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3035 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3036 DevicePolicyManager.CODE_OK);
3037 assertCheckProvisioningPreCondition(
3038 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3039 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3040 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3041 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3042 }
3043
Nicolas Prevot45d29072017-01-18 16:11:19 +00003044 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
3045 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003046 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00003047 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3048
3049 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3050 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003051 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003052
3053 // COMP mode is allowed.
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
Nicolas Prevot45d29072017-01-18 16:11:19 +00003058 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00003059 assertCheckProvisioningPreCondition(
3060 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003061 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003062 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003063 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3064 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3065 }
Esteban Talavera01576862016-12-15 11:16:44 +00003066
Nicolas Prevot45d29072017-01-18 16:11:19 +00003067 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
3068 setup_nonSplitUser_withDo_primaryUser();
3069 mContext.packageName = admin1.getPackageName();
3070 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3071 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
3072 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003073 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003074 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3075 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3076 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003077 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003078 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3079 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3080 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3081 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3082 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003083 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003084 assertCheckProvisioningPreCondition(
3085 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 }
Esteban Talavera01576862016-12-15 11:16:44 +00003091
Nicolas Prevot45d29072017-01-18 16:11:19 +00003092 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
3093 throws Exception {
3094 setup_nonSplitUser_withDo_primaryUser();
3095 mContext.packageName = admin1.getPackageName();
3096 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003097 // The DO should not be allowed to initiate provisioning if the restriction is set by
3098 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003099 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003100 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3101 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3102 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003103 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003104 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3105 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3106 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3107 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3108 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003109 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3110
3111 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003112 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003113 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003114 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003115 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3116 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3117 }
3118
3119 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
3120 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3121 mContext.packageName = admin1.getPackageName();
3122 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3123
3124 // We can delete the managed profile to create a new one, so provisioning is allowed.
3125 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3126 DevicePolicyManager.CODE_OK);
3127 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3128 assertCheckProvisioningPreCondition(
3129 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3130 DpmMockContext.ANOTHER_PACKAGE_NAME,
3131 DevicePolicyManager.CODE_OK);
3132 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3133 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3134 }
3135
3136 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3137 throws Exception {
3138 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3139 mContext.packageName = admin1.getPackageName();
3140 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003141 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003142 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3143 eq(UserHandle.SYSTEM)))
3144 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003145 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003146 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3147 eq(UserHandle.SYSTEM)))
3148 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003149
3150 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003151 assertCheckProvisioningPreCondition(
3152 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3153 DpmMockContext.ANOTHER_PACKAGE_NAME,
3154 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3155 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3156 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003157
3158 // But the device owner can still do it because it has set the restriction itself.
3159 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3160 DevicePolicyManager.CODE_OK);
3161 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003162 }
3163
3164 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003165 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003166 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003167 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3168 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003169 .thenReturn(false);
3170 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3171
3172 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003173 }
Victor Chang3e794af2016-03-04 13:48:17 +00003174
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003175 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3176 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003177 mContext.packageName = admin1.getPackageName();
3178 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003179 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3180 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3181 false /* because canAddMoreManagedProfiles returns false */);
3182 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3183 true);
3184 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3185 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003186 }
3187
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003188 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3189 throws Exception {
3190 setup_splitUser_firstBoot_systemUser();
3191 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3192 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3193 DevicePolicyManager.CODE_OK);
3194 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003195 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003196 assertCheckProvisioningPreCondition(
3197 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3198 DevicePolicyManager.CODE_OK);
3199 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3200 DevicePolicyManager.CODE_SYSTEM_USER);
3201 }
3202
Esteban Talavera01576862016-12-15 11:16:44 +00003203 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003204 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003205 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003206 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3207 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003208 .thenReturn(false);
3209 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3210
3211 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003212 }
Victor Chang3e794af2016-03-04 13:48:17 +00003213
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003214 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3215 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003216 mContext.packageName = admin1.getPackageName();
3217 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003218 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3219 true/* it's undefined behavior. Can be changed into false in the future */);
3220 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3221 false /* because canAddMoreManagedProfiles returns false */);
3222 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3223 true/* it's undefined behavior. Can be changed into false in the future */);
3224 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3225 false/* because calling uid is system user */);
3226 }
3227
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003228 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3229 throws Exception {
3230 setup_splitUser_afterDeviceSetup_systemUser();
3231 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3232 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3233 DevicePolicyManager.CODE_OK);
3234 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003235 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003236 assertCheckProvisioningPreCondition(
3237 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3238 DevicePolicyManager.CODE_OK);
3239 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3240 DevicePolicyManager.CODE_SYSTEM_USER);
3241 }
3242
Esteban Talavera01576862016-12-15 11:16:44 +00003243 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003244 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003245 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003246 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3247 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003248 true)).thenReturn(true);
3249 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3250
3251 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003252 }
Victor Chang3e794af2016-03-04 13:48:17 +00003253
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003254 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3255 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003256 mContext.packageName = admin1.getPackageName();
3257 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003258 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3259 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3260 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3261 true);
3262 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003263 }
3264
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003265 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003266 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003267 setup_splitUser_firstBoot_primaryUser();
3268 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3269 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3270 DevicePolicyManager.CODE_OK);
3271 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3272 DevicePolicyManager.CODE_OK);
3273 assertCheckProvisioningPreCondition(
3274 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3275 DevicePolicyManager.CODE_OK);
3276 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3277 DevicePolicyManager.CODE_OK);
3278 }
3279
Esteban Talavera01576862016-12-15 11:16:44 +00003280 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003281 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003282 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003283 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3284 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003285 true)).thenReturn(true);
3286 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3287
3288 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003289 }
Victor Chang3e794af2016-03-04 13:48:17 +00003290
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003291 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3292 throws Exception {
3293 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003294 mContext.packageName = admin1.getPackageName();
3295 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003296 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3297 true/* it's undefined behavior. Can be changed into false in the future */);
3298 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3299 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3300 true/* it's undefined behavior. Can be changed into false in the future */);
3301 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3302 false/* because user setup completed */);
3303 }
3304
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003305 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003306 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003307 setup_splitUser_afterDeviceSetup_primaryUser();
3308 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3309 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3310 DevicePolicyManager.CODE_OK);
3311 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3312 DevicePolicyManager.CODE_OK);
3313 assertCheckProvisioningPreCondition(
3314 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3315 DevicePolicyManager.CODE_OK);
3316 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3317 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3318 }
3319
Esteban Talavera01576862016-12-15 11:16:44 +00003320 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003321 setDeviceOwner();
3322
Pavel Grafov75c0a892017-05-18 17:28:27 +01003323 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003324 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003325 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3326 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003327 .thenReturn(false);
3328 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3329
3330 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003331 }
Victor Chang3e794af2016-03-04 13:48:17 +00003332
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003333 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3334 throws Exception {
3335 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003336 mContext.packageName = admin1.getPackageName();
3337 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003338 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3339 false /* can't provision managed profile on system user */);
3340 }
3341
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003342 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003343 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003344 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3345 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3346 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3347 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3348 }
3349
3350 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003351 setDeviceOwner();
3352
Pavel Grafov75c0a892017-05-18 17:28:27 +01003353 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003354 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003355 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3356 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003357 true)).thenReturn(true);
3358 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3359
3360 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003361 }
Victor Chang3e794af2016-03-04 13:48:17 +00003362
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003363 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3364 throws Exception {
3365 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003366 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3367 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003368 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3369 }
3370
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003371 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003372 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003373 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3374 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003375
3376 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003377 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3378 DevicePolicyManager.CODE_OK);
3379 }
3380
3381 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003382 setDeviceOwner();
3383
Pavel Grafov75c0a892017-05-18 17:28:27 +01003384 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003385 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003386 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3387 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003388 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3389 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003390 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003391 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003392 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003393 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003394 true)).thenReturn(true);
3395 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3396
3397 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003398 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003399
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003400 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3401 throws Exception {
3402 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003403 mContext.packageName = admin1.getPackageName();
3404 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003405 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3406 }
3407
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003408 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3409 throws Exception {
3410 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3411 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3412 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3413 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3414 }
3415
3416 public void testCheckProvisioningPreCondition_permission() {
3417 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003418 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3419 () -> dpm.checkProvisioningPreCondition(
3420 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003421 }
3422
Victor Chang3577ed22016-08-25 18:49:26 +01003423 public void testForceUpdateUserSetupComplete_permission() {
3424 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003425 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3426 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003427 }
3428
3429 public void testForceUpdateUserSetupComplete_systemUser() {
3430 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3431 // GIVEN calling from user 20
3432 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003433 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3434 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003435 }
3436
3437 public void testForceUpdateUserSetupComplete_userbuild() {
3438 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3439 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3440
3441 final int userId = UserHandle.USER_SYSTEM;
3442 // GIVEN userComplete is false in SettingsProvider
3443 setUserSetupCompleteForUser(false, userId);
3444
3445 // GIVEN userComplete is true in DPM
3446 DevicePolicyManagerService.DevicePolicyData userData =
3447 new DevicePolicyManagerService.DevicePolicyData(userId);
3448 userData.mUserSetupComplete = true;
3449 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3450
3451 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003452 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003453
3454 assertTrue(dpms.hasUserSetupCompleted());
3455
3456 dpm.forceUpdateUserSetupComplete();
3457
3458 // THEN the state in dpms is not changed
3459 assertTrue(dpms.hasUserSetupCompleted());
3460 }
3461
3462 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3463 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3464 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3465
3466 final int userId = UserHandle.USER_SYSTEM;
3467 // GIVEN userComplete is false in SettingsProvider
3468 setUserSetupCompleteForUser(false, userId);
3469
3470 // GIVEN userComplete is true in DPM
3471 DevicePolicyManagerService.DevicePolicyData userData =
3472 new DevicePolicyManagerService.DevicePolicyData(userId);
3473 userData.mUserSetupComplete = true;
3474 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3475
3476 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003477 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003478
3479 assertTrue(dpms.hasUserSetupCompleted());
3480
3481 dpm.forceUpdateUserSetupComplete();
3482
3483 // THEN the state in dpms is not changed
3484 assertFalse(dpms.hasUserSetupCompleted());
3485 }
3486
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003487 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003488 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003489 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003490
3491 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3492 runAsCaller(mAdmin1Context, dpms, dpm -> {
3493 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3494 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003495 }
3496
3497 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3498 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3499 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003500
3501 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3502 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003503 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003504 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3505 .thenReturn(true);
3506
3507 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003508 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003509
3510 // Enabling logging should not change the timestamp.
3511 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003512 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003513 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003514 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003515 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003516 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003517
3518 // Retrieving the logs should update the timestamp.
3519 final long beforeRetrieval = System.currentTimeMillis();
3520 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003521 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003522 final long afterRetrieval = System.currentTimeMillis();
3523 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3524 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3525
3526 // Retrieving the pre-boot logs should update the timestamp.
3527 Thread.sleep(2);
3528 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003529 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003530 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3531
3532 // Checking the timestamp again should not change it.
3533 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003534 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003535
3536 // Retrieving the logs again should update the timestamp.
3537 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003538 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003539 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3540
3541 // Disabling logging should not change the timestamp.
3542 Thread.sleep(2);
3543 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003544 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003545
3546 // Restarting the DPMS should not lose the timestamp.
3547 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003548 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003549
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003550 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3551 mContext.binder.callingUid = 1234567;
3552 mContext.callerPermissions.add(permission.MANAGE_USERS);
3553 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3554 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3555
3556 // System can retrieve the timestamp.
3557 mContext.binder.clearCallingIdentity();
3558 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3559
3560 // Removing the device owner should clear the timestamp.
3561 clearDeviceOwner();
3562 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003563 }
3564
yuemingw0de748d2017-11-15 19:22:27 +00003565 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3566 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3567 setupDeviceOwner();
3568 assertExpectException(SecurityException.class, null, () ->
3569 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3570 }
3571
yuemingwc0281f12018-03-28 15:58:49 +01003572 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003573 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3574 setupDeviceOwner();
3575 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003576 verify(getServices().settings).settingsSystemPutStringForUser(
3577 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3578 }
3579
3580 public void testSetSystemSettingWithPO() throws Exception {
3581 setupProfileOwner();
3582 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3583 verify(getServices().settings).settingsSystemPutStringForUser(
3584 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003585 }
3586
yuemingwe43cdf72017-10-12 16:52:11 +01003587 public void testSetTime() throws Exception {
3588 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3589 setupDeviceOwner();
3590 dpm.setTime(admin1, 0);
3591 verify(getServices().alarmManager).setTime(0);
3592 }
3593
3594 public void testSetTimeFailWithPO() throws Exception {
3595 setupProfileOwner();
3596 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3597 }
3598
3599 public void testSetTimeWithAutoTimeOn() throws Exception {
3600 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3601 setupDeviceOwner();
3602 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3603 .thenReturn(1);
3604 assertFalse(dpm.setTime(admin1, 0));
3605 }
3606
3607 public void testSetTimeZone() throws Exception {
3608 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3609 setupDeviceOwner();
3610 dpm.setTimeZone(admin1, "Asia/Shanghai");
3611 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3612 }
3613
3614 public void testSetTimeZoneFailWithPO() throws Exception {
3615 setupProfileOwner();
3616 assertExpectException(SecurityException.class, null,
3617 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3618 }
3619
3620 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3621 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3622 setupDeviceOwner();
3623 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3624 .thenReturn(1);
3625 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3626 }
3627
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003628 public void testGetLastBugReportRequestTime() throws Exception {
3629 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3630 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003631
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003632 mContext.packageName = admin1.getPackageName();
3633 mContext.applicationInfo = new ApplicationInfo();
3634 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3635 .thenReturn(Color.WHITE);
3636 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3637 anyObject())).thenReturn(Color.WHITE);
3638
Esteban Talaverad36dd152016-12-15 08:51:45 +00003639 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3640 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003641 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003642
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003643 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003644 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003645
3646 // Requesting a bug report should update the timestamp.
3647 final long beforeRequest = System.currentTimeMillis();
3648 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003649 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003650 final long afterRequest = System.currentTimeMillis();
3651 assertTrue(bugReportRequestTime >= beforeRequest);
3652 assertTrue(bugReportRequestTime <= afterRequest);
3653
3654 // Checking the timestamp again should not change it.
3655 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003656 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003657
3658 // Restarting the DPMS should not lose the timestamp.
3659 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003660 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003661
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003662 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3663 mContext.binder.callingUid = 1234567;
3664 mContext.callerPermissions.add(permission.MANAGE_USERS);
3665 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3666 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3667
3668 // System can retrieve the timestamp.
3669 mContext.binder.clearCallingIdentity();
3670 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3671
3672 // Removing the device owner should clear the timestamp.
3673 clearDeviceOwner();
3674 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003675 }
3676
3677 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3678 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3679 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003680 mContext.packageName = admin1.getPackageName();
3681 mContext.applicationInfo = new ApplicationInfo();
3682 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3683 .thenReturn(Color.WHITE);
3684 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3685 anyObject())).thenReturn(Color.WHITE);
3686
3687 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3688 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003689 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003690 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003691 .thenReturn(true);
3692
3693 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003694 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003695
3696 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3697 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003698 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003699
3700 // Enabling logging should not change the timestamp.
3701 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003702 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003703
3704 // Retrieving the logs should update the timestamp.
3705 final long beforeRetrieval = System.currentTimeMillis();
3706 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003707 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003708 final long afterRetrieval = System.currentTimeMillis();
3709 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3710 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3711
3712 // Checking the timestamp again should not change it.
3713 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003714 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003715
3716 // Retrieving the logs again should update the timestamp.
3717 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003718 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003719 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3720
3721 // Disabling logging should not change the timestamp.
3722 Thread.sleep(2);
3723 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003724 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003725
3726 // Restarting the DPMS should not lose the timestamp.
3727 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003728 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3729
3730 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3731 mContext.binder.callingUid = 1234567;
3732 mContext.callerPermissions.add(permission.MANAGE_USERS);
3733 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3734 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3735
3736 // System can retrieve the timestamp.
3737 mContext.binder.clearCallingIdentity();
3738 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3739
3740 // Removing the device owner should clear the timestamp.
3741 clearDeviceOwner();
3742 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003743 }
3744
Tony Mak2f26b792016-11-28 17:54:51 +00003745 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3746 // Setup device owner.
3747 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3748 setupDeviceOwner();
3749
3750 // Only device owner is setup, the result list should be empty.
3751 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3752 MoreAsserts.assertEmpty(targetUsers);
3753
3754 // Setup a managed profile managed by the same admin.
3755 final int MANAGED_PROFILE_USER_ID = 15;
3756 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3757 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3758
3759 // Add a secondary user, it should never talk with.
3760 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003761 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003762
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003763 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3764 // other.
3765 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3766 MoreAsserts.assertEmpty(targetUsers);
3767
3768 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3769 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3770 MoreAsserts.assertEmpty(targetUsers);
3771
3772 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003773 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003774 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3775 dpm.setAffiliationIds(admin1, userAffiliationIds);
3776
3777 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3778 dpm.setAffiliationIds(admin1, userAffiliationIds);
3779
Tony Mak2f26b792016-11-28 17:54:51 +00003780 // Calling from device owner admin, the result list should just contain the managed
3781 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003782 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003783 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3784 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3785
3786 // Calling from managed profile admin, the result list should just contain the system
3787 // user id.
3788 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3789 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3790 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003791
3792 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003793 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003794
3795 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3796 // to each other.
3797 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3798 MoreAsserts.assertEmpty(targetUsers);
3799
3800 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3801 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3802 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003803 }
3804
3805 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3806 // Setup a device owner.
3807 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3808 setupDeviceOwner();
3809
3810 // Set up a managed profile managed by different package.
3811 final int MANAGED_PROFILE_USER_ID = 15;
3812 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3813 final ComponentName adminDifferentPackage =
3814 new ComponentName("another.package", "whatever.class");
3815 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3816
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003817 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003818 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003819 dpm.setAffiliationIds(admin1, userAffiliationIds);
3820
3821 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3822 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3823
Tony Mak2f26b792016-11-28 17:54:51 +00003824 // Calling from device owner admin, we should get zero bind device admin target users as
3825 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003826 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003827 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3828 MoreAsserts.assertEmpty(targetUsers);
3829
3830 // Calling from managed profile admin, we should still get zero target users for the same
3831 // reason.
3832 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3833 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3834 MoreAsserts.assertEmpty(targetUsers);
3835 }
3836
Jason Parks3c13b642017-11-28 15:39:43 -06003837 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003838 verifyLockTaskState(userId, new String[0],
3839 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003840 }
3841
3842 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3843 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003844 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003845 }
3846
3847 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3848 int flags) throws Exception {
3849 mContext.binder.callingUid = uid;
3850 dpm.setLockTaskPackages(who, packages);
3851 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3852 for (String p : packages) {
3853 assertTrue(dpm.isLockTaskPermitted(p));
3854 }
3855 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3856 // Test to see if set lock task features can be set
3857 dpm.setLockTaskFeatures(who, flags);
3858 verifyLockTaskState(userId, packages, flags);
3859 }
3860
3861 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3862 int flags) throws Exception {
3863 mContext.binder.callingUid = uid;
3864 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3865 () -> dpm.setLockTaskPackages(who, packages));
3866 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3867 () -> dpm.getLockTaskPackages(who));
3868 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3869 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3870 () -> dpm.setLockTaskFeatures(who, flags));
3871 }
3872
Charles Hee078db72017-10-19 18:03:20 +01003873 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003874 // Setup a device owner.
3875 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3876 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003877 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003878 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003879
3880 // Set up a managed profile managed by different package (package name shouldn't matter)
3881 final int MANAGED_PROFILE_USER_ID = 15;
3882 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3883 final ComponentName adminDifferentPackage =
3884 new ComponentName("another.package", "whatever.class");
3885 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003886 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3887
3888 // Setup a PO on the secondary user
3889 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3890 setAsProfileOwner(admin3);
3891 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003892
3893 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003894 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003895 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003896 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3897 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003898 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3899
3900 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3901 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003902 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3903 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003904 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003905
3906 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3907 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3908 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003909 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003910 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3911 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003912 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003913
3914 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003915 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003916 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3917 dpm.setAffiliationIds(admin1, userAffiliationIds);
3918
3919 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3920 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3921
3922 // Now the managed profile can set lock task packages.
3923 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3924 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3925 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3926 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003927 // And it can set lock task features.
3928 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003929 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003930
3931 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003932 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003933 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3934 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003935 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3936 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003937 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003938 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003939
Jason Parks3c13b642017-11-28 15:39:43 -06003940 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003941 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3942 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003943
3944 }
3945
3946 public void testLockTaskPolicyForProfileOwner() throws Exception {
3947 // Setup a PO
3948 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3949 setAsProfileOwner(admin1);
3950 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3951
3952 final String[] poPackages = {"poPackage1", "poPackage2"};
3953 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003954 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3955 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003956 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3957 poPackages, poFlags);
3958
3959 // Set up a managed profile managed by different package (package name shouldn't matter)
3960 final int MANAGED_PROFILE_USER_ID = 15;
3961 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3962 final ComponentName adminDifferentPackage =
3963 new ComponentName("another.package", "whatever.class");
3964 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3965 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3966
3967 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3968 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3969 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3970 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003971 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3972 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003973 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003974 }
3975
Benjamin Franzcaffa772018-02-05 16:36:10 +00003976 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3977 // Setup a device owner.
3978 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3979 setupDeviceOwner();
3980 // Lock task policy is updated when loading user data.
3981 verifyLockTaskState(UserHandle.USER_SYSTEM);
3982
3983 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3984 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3985 assertExpectException(IllegalArgumentException.class,
3986 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3987 () -> dpm.setLockTaskFeatures(admin1, flags));
3988 }
3989
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003990 public void testIsDeviceManaged() throws Exception {
3991 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3992 setupDeviceOwner();
3993
3994 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3995 // find out that the device has a device owner.
3996 assertTrue(dpm.isDeviceManaged());
3997 mContext.binder.callingUid = 1234567;
3998 mContext.callerPermissions.add(permission.MANAGE_USERS);
3999 assertTrue(dpm.isDeviceManaged());
4000 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4001 mContext.binder.clearCallingIdentity();
4002 assertTrue(dpm.isDeviceManaged());
4003
4004 clearDeviceOwner();
4005
4006 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
4007 // not have a device owner.
4008 mContext.binder.callingUid = 1234567;
4009 mContext.callerPermissions.add(permission.MANAGE_USERS);
4010 assertFalse(dpm.isDeviceManaged());
4011 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4012 mContext.binder.clearCallingIdentity();
4013 assertFalse(dpm.isDeviceManaged());
4014 }
4015
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01004016 public void testDeviceOwnerOrganizationName() throws Exception {
4017 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4018 setupDeviceOwner();
4019
4020 dpm.setOrganizationName(admin1, "organization");
4021
4022 // Device owner can retrieve organization managing the device.
4023 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4024
4025 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
4026 mContext.binder.callingUid = 1234567;
4027 mContext.callerPermissions.add(permission.MANAGE_USERS);
4028 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4029 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4030
4031 // System can retrieve organization managing the device.
4032 mContext.binder.clearCallingIdentity();
4033 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4034
4035 // Removing the device owner clears the organization managing the device.
4036 clearDeviceOwner();
4037 assertNull(dpm.getDeviceOwnerOrganizationName());
4038 }
4039
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004040 public void testWipeDataManagedProfile() throws Exception {
4041 final int MANAGED_PROFILE_USER_ID = 15;
4042 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4043 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4044 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4045
4046 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004047 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004048 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01004049 // Get mock reason string since we throw an IAE with empty string input.
4050 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4051 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004052
4053 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004054 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004055 MANAGED_PROFILE_USER_ID);
4056 }
4057
4058 public void testWipeDataManagedProfileDisallowed() throws Exception {
4059 final int MANAGED_PROFILE_USER_ID = 15;
4060 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4061 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4062
4063 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004064 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004065 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4066
Pavel Grafov75c0a892017-05-18 17:28:27 +01004067 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004068 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4069 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4070 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004071 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4072 thenReturn("Just a test string.");
4073
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004074 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004075 // The PO is not allowed to remove the profile if the user restriction was set on the
4076 // profile by the system
4077 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4078 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004079 }
4080
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004081 public void testWipeDataDeviceOwner() throws Exception {
4082 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004083 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004084 UserManager.DISALLOW_FACTORY_RESET,
4085 UserHandle.SYSTEM))
4086 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004087 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4088 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004089
4090 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004091 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004092 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4093 /*wipeEuicc=*/ eq(false));
4094 }
4095
4096 public void testWipeEuiccDataEnabled() throws Exception {
4097 setDeviceOwner();
4098 when(getServices().userManager.getUserRestrictionSource(
4099 UserManager.DISALLOW_FACTORY_RESET,
4100 UserHandle.SYSTEM))
4101 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004102 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4103 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07004104
4105 dpm.wipeData(WIPE_EUICC);
4106 verify(getServices().recoverySystem).rebootWipeUserData(
4107 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4108 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004109 }
4110
4111 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
4112 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004113 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004114 UserManager.DISALLOW_FACTORY_RESET,
4115 UserHandle.SYSTEM))
4116 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004117 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4118 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004119 // The DO is not allowed to wipe the device if the user restriction was set
4120 // by the system
4121 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4122 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004123 }
4124
4125 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4126 final int MANAGED_PROFILE_USER_ID = 15;
4127 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4128 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4129
4130 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004131 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004132 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4133
Pavel Grafov75c0a892017-05-18 17:28:27 +01004134 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004135 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4136 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4137 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4138
4139 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4140 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4141
4142 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4143 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4144 // Failed password attempts on the parent user are taken into account, as there isn't a
4145 // separate work challenge.
4146 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4147 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4148 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4149
4150 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4151 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004152 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004153 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004154 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004155 }
4156
4157 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4158 throws Exception {
4159 final int MANAGED_PROFILE_USER_ID = 15;
4160 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4161 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4162
4163 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004164 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004165 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4166
Pavel Grafov75c0a892017-05-18 17:28:27 +01004167 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004168 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4169 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4170 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4171
4172 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4173 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4174
4175 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4176 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4177 // Failed password attempts on the parent user are taken into account, as there isn't a
4178 // separate work challenge.
4179 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4180 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4181 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4182
4183 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4184 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004185 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004186 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004187 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004188 }
4189
4190 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4191 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004192 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004193 UserManager.DISALLOW_FACTORY_RESET,
4194 UserHandle.SYSTEM))
4195 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4196
4197 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4198
4199 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4200 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4201 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4202 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4203 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4204
4205 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4206 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004207 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004208 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4209 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004210 }
4211
4212 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4213 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004214 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004215 UserManager.DISALLOW_FACTORY_RESET,
4216 UserHandle.SYSTEM))
4217 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4218
4219 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4220
4221 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4222 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4223 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4224 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4225 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4226
4227 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004228 verifyZeroInteractions(getServices().recoverySystem);
4229 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004230 .removeUserEvenWhenDisallowed(anyInt());
4231 }
4232
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004233 public void testGetPermissionGrantState() throws Exception {
4234 final String permission = "some.permission";
4235 final String app1 = "com.example.app1";
4236 final String app2 = "com.example.app2";
4237
Pavel Grafov75c0a892017-05-18 17:28:27 +01004238 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004239 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004240 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004241 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004242 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004243 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4244 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004245 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004246 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004247 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004248 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004249 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004250 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4251
4252 // System can retrieve permission grant state.
4253 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004254 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004255 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4256 dpm.getPermissionGrantState(null, app1, permission));
4257 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4258 dpm.getPermissionGrantState(null, app2, permission));
4259
4260 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004261 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4262 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004263 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4264 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004265
4266 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004267 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4268 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004269 setAsProfileOwner(admin1);
4270 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4271 dpm.getPermissionGrantState(admin1, app1, permission));
4272 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4273 dpm.getPermissionGrantState(admin1, app2, permission));
4274 }
4275
Rubin Xuaab7a412016-12-30 21:13:29 +00004276 public void testResetPasswordWithToken() throws Exception {
4277 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4278 setupDeviceOwner();
4279 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004280 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4281 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4282
Rubin Xuaab7a412016-12-30 21:13:29 +00004283 // test adding a token
4284 final byte[] token = new byte[32];
4285 final long handle = 123456;
4286 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004287 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4288 nullable(EscrowTokenStateChangeCallback.class)))
4289 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004290 assertTrue(dpm.setResetPasswordToken(admin1, token));
4291
4292 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004293 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004294 .thenReturn(true);
4295 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4296
4297 // test reset password with token
Rubin Xua58125d2019-09-06 20:11:48 +01004298 when(getServices().lockPatternUtils.setLockCredentialWithToken(
4299 eq(LockscreenCredential.createPassword(password)),
4300 eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004301 eq(UserHandle.USER_SYSTEM)))
4302 .thenReturn(true);
4303 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4304
4305 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004306 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004307 .thenReturn(true);
4308 assertTrue(dpm.clearResetPasswordToken(admin1));
4309 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004310
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004311 public void testIsActivePasswordSufficient() throws Exception {
4312 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4313 mContext.packageName = admin1.getPackageName();
4314 setupDeviceOwner();
4315
4316 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4317 dpm.setPasswordMinimumLength(admin1, 8);
4318 dpm.setPasswordMinimumLetters(admin1, 6);
4319 dpm.setPasswordMinimumLowerCase(admin1, 3);
4320 dpm.setPasswordMinimumUpperCase(admin1, 1);
4321 dpm.setPasswordMinimumNonLetter(admin1, 1);
4322 dpm.setPasswordMinimumNumeric(admin1, 1);
4323 dpm.setPasswordMinimumSymbols(admin1, 0);
4324
Rubin Xucc391c22018-01-02 20:37:35 +00004325 reset(mContext.spiedContext);
4326
Pavel Grafov6f334842019-08-06 14:37:06 +01004327 PasswordMetrics passwordMetricsNoSymbols = computeForPassword("abcdXYZ5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004328
4329 setActivePasswordState(passwordMetricsNoSymbols);
4330 assertTrue(dpm.isActivePasswordSufficient());
4331
4332 initializeDpms();
4333 reset(mContext.spiedContext);
4334 assertTrue(dpm.isActivePasswordSufficient());
4335
4336 // This call simulates the user entering the password for the first time after a reboot.
4337 // This causes password metrics to be reloaded into memory. Until this happens,
4338 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4339 // even if the DPC changes password requirements so that the password no longer meets the
4340 // requirements. This is a known limitation of the current implementation of
4341 // isActivePasswordSufficient() - see b/34218769.
4342 setActivePasswordState(passwordMetricsNoSymbols);
4343 assertTrue(dpm.isActivePasswordSufficient());
4344
4345 dpm.setPasswordMinimumSymbols(admin1, 1);
4346 // This assertion would fail if we had not called setActivePasswordState() again after
4347 // initializeDpms() - see previous comment.
4348 assertFalse(dpm.isActivePasswordSufficient());
4349
4350 initializeDpms();
4351 reset(mContext.spiedContext);
4352 assertFalse(dpm.isActivePasswordSufficient());
4353
Pavel Grafov6f334842019-08-06 14:37:06 +01004354 PasswordMetrics passwordMetricsWithSymbols = computeForPassword("abcd.XY5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004355
4356 setActivePasswordState(passwordMetricsWithSymbols);
4357 assertTrue(dpm.isActivePasswordSufficient());
4358 }
4359
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004360 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4361 // If there is no lock screen, the password is considered empty no matter what, because
4362 // it provides no security.
4363 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4364
4365 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4366 mContext.packageName = admin1.getPackageName();
4367 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004368 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4369 // When there is no lockscreen, user password metrics is always empty.
4370 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
Pavel Grafov6f334842019-08-06 14:37:06 +01004371 .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE));
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004372
4373 // If no password requirements are set, isActivePasswordSufficient should succeed.
4374 assertTrue(dpm.isActivePasswordSufficient());
4375
4376 // Now set some password quality requirements.
4377 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4378
4379 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004380 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004381 dpm.reportPasswordChanged(userHandle);
4382
4383 // No broadcast should be sent.
4384 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4385 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4386 MockUtils.checkUserHandle(userHandle));
4387
4388 // The active (nonexistent) password doesn't comply with the requirements.
4389 assertFalse(dpm.isActivePasswordSufficient());
4390 }
4391
Pavel Grafov75c0a892017-05-18 17:28:27 +01004392 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4393 throws Exception {
4394 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004395 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004396
Rubin Xu19854862019-08-15 16:37:23 +01004397 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4398 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004399 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004400
Rubin Xucc391c22018-01-02 20:37:35 +00004401 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4402 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004403 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004404 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4405 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004406 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004407 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4408 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004409 // userId, if the password checkpoint value changes.
4410 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4411 MockUtils.checkIntentAction(
4412 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4413 MockUtils.checkUserHandle(userHandle));
4414 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004415 MockUtils.checkIntentAction(
4416 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4417 MockUtils.checkUserHandle(userHandle));
4418
Pavel Grafov75c0a892017-05-18 17:28:27 +01004419 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4420 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004421 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004422
4423 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4424 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004425 MockUtils.checkUserHandle(userHandle),
4426 eq(null),
4427 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004428
4429 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4430 // let it finish with system uid, otherwise it will throw and crash.
4431 flushTasks();
4432
4433 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004434 }
4435
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004436 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4437 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4438 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4439 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4440 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4441 DpmMockContext.SYSTEM_UID);
4442 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4443 DpmMockContext.SYSTEM_UID);
4444
4445 // Set up a device owner.
4446 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004447 setupDeviceOwner();
4448
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004449 // First and second user set IMEs manually.
4450 mContext.binder.callingUid = firstUserSystemUid;
4451 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4452 mContext.binder.callingUid = secondUserSystemUid;
4453 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004454
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004455 // Device owner changes IME for first user.
4456 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004457 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004458 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004459 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004460 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004461 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004462 reset(getServices().settings);
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
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004469 // Second user changes IME manually.
4470 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4471 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 // First user changes IME manually.
4477 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4478 mContext.binder.callingUid = firstUserSystemUid;
4479 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4480 mContext.binder.callingUid = secondUserSystemUid;
4481 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004482
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004483 // Device owner changes IME for first user again.
4484 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004485 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004486 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004487 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004488 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004489 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004490 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4491 mContext.binder.callingUid = firstUserSystemUid;
4492 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4493 mContext.binder.callingUid = secondUserSystemUid;
4494 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004495
4496 // Restarting the DPMS should not lose information.
4497 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004498 mContext.binder.callingUid = firstUserSystemUid;
4499 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4500 mContext.binder.callingUid = secondUserSystemUid;
4501 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004502
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004503 // Device owner can find out whether it set the current IME itself.
4504 mContext.binder.callingUid = deviceOwnerUid;
4505 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004506
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004507 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004508 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004509 mContext.binder.callingUid = firstUserSystemUid;
4510 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4511 mContext.binder.callingUid = secondUserSystemUid;
4512 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004513 }
4514
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004515 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4516 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4517 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4518 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4519 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4520 DpmMockContext.SYSTEM_UID);
4521 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4522 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004523
4524 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004525 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004526 setupProfileOwner();
4527
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004528 // First and second user set IMEs manually.
4529 mContext.binder.callingUid = firstUserSystemUid;
4530 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4531 mContext.binder.callingUid = secondUserSystemUid;
4532 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004533
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004534 // Profile owner changes IME for second user.
4535 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004536 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004537 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004538 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004539 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004540 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004541 reset(getServices().settings);
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
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004548 // First user changes IME manually.
4549 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4550 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 // Second user changes IME manually.
4556 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4557 mContext.binder.callingUid = firstUserSystemUid;
4558 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4559 mContext.binder.callingUid = secondUserSystemUid;
4560 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004561
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004562 // Profile owner changes IME for second user again.
4563 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004564 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004565 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004566 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004567 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004568 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004569 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4570 mContext.binder.callingUid = firstUserSystemUid;
4571 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4572 mContext.binder.callingUid = secondUserSystemUid;
4573 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004574
4575 // Restarting the DPMS should not lose information.
4576 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004577 mContext.binder.callingUid = firstUserSystemUid;
4578 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4579 mContext.binder.callingUid = secondUserSystemUid;
4580 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004581
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004582 // Profile owner can find out whether it set the current IME itself.
4583 mContext.binder.callingUid = profileOwnerUid;
4584 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004585
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004586 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004587 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004588 mContext.binder.callingUid = firstUserSystemUid;
4589 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4590 mContext.binder.callingUid = secondUserSystemUid;
4591 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004592 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004593
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004594 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4595 throws Exception {
4596 // Set up a device owner.
4597 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4598 setupDeviceOwner();
4599 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4600 }
4601
4602 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4603 throws Exception {
4604 // Set up a profile owner.
4605 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4606 setupProfileOwner();
4607 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4608 }
4609
4610 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4611 int adminUid) throws Exception {
4612 mContext.binder.callingUid = adminUid;
4613 final int userId = UserHandle.getUserId(adminUid);
4614
4615 final String packageName = "some.package";
4616 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4617 admin1, Collections.singletonList(packageName)));
4618 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4619
4620 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4621 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4622
4623 // Attempt to set to empty list (which means no listener is whitelisted)
4624 mContext.binder.callingUid = adminUid;
4625 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004626 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004627 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4628
4629 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4630 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4631 }
4632
4633 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() 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 = "some.package";
4641 setupPackageInPackageManager(
4642 permittedListener,
4643 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4644 /*appId=*/ 12345, /*flags=*/ 0);
4645
4646 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4647 admin1, Collections.singletonList(permittedListener)));
4648
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004649 // isNotificationListenerServicePermitted should throw if not called from System.
4650 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4651 () -> dpms.isNotificationListenerServicePermitted(
4652 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004653
4654 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4655 assertTrue(dpms.isNotificationListenerServicePermitted(
4656 permittedListener, MANAGED_PROFILE_USER_ID));
4657 }
4658
4659 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4660 throws Exception {
4661 // Set up a managed profile
4662 final int MANAGED_PROFILE_USER_ID = 15;
4663 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4664 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4665 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4666
4667 final String permittedListener = "permitted.package";
4668 int appId = 12345;
4669 setupPackageInPackageManager(
4670 permittedListener,
4671 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4672 appId, /*flags=*/ 0);
4673
4674 final String notPermittedListener = "not.permitted.package";
4675 setupPackageInPackageManager(
4676 notPermittedListener,
4677 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4678 ++appId, /*flags=*/ 0);
4679
4680 final String systemListener = "system.package";
4681 setupPackageInPackageManager(
4682 systemListener,
4683 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4684 ++appId, ApplicationInfo.FLAG_SYSTEM);
4685
4686 // By default all packages are allowed
4687 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4688
4689 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4690 assertTrue(dpms.isNotificationListenerServicePermitted(
4691 permittedListener, MANAGED_PROFILE_USER_ID));
4692 assertTrue(dpms.isNotificationListenerServicePermitted(
4693 notPermittedListener, MANAGED_PROFILE_USER_ID));
4694 assertTrue(dpms.isNotificationListenerServicePermitted(
4695 systemListener, MANAGED_PROFILE_USER_ID));
4696
4697 // Setting only one package in the whitelist
4698 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4699 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4700 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004701 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004702 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4703 assertEquals(1, permittedListeners.size());
4704 assertEquals(permittedListener, permittedListeners.get(0));
4705
4706 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4707 assertTrue(dpms.isNotificationListenerServicePermitted(
4708 permittedListener, MANAGED_PROFILE_USER_ID));
4709 assertFalse(dpms.isNotificationListenerServicePermitted(
4710 notPermittedListener, MANAGED_PROFILE_USER_ID));
4711 // System packages are always allowed (even if not in the whitelist)
4712 assertTrue(dpms.isNotificationListenerServicePermitted(
4713 systemListener, MANAGED_PROFILE_USER_ID));
4714
4715 // Setting an empty whitelist - only system listeners allowed
4716 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4717 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004718 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004719 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4720
4721 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4722 assertFalse(dpms.isNotificationListenerServicePermitted(
4723 permittedListener, MANAGED_PROFILE_USER_ID));
4724 assertFalse(dpms.isNotificationListenerServicePermitted(
4725 notPermittedListener, MANAGED_PROFILE_USER_ID));
4726 // System packages are always allowed (even if not in the whitelist)
4727 assertTrue(dpms.isNotificationListenerServicePermitted(
4728 systemListener, MANAGED_PROFILE_USER_ID));
4729
4730 // Setting a null whitelist - all listeners allowed
4731 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4732 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4733 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4734
4735 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4736 assertTrue(dpms.isNotificationListenerServicePermitted(
4737 permittedListener, MANAGED_PROFILE_USER_ID));
4738 assertTrue(dpms.isNotificationListenerServicePermitted(
4739 notPermittedListener, MANAGED_PROFILE_USER_ID));
4740 assertTrue(dpms.isNotificationListenerServicePermitted(
4741 systemListener, MANAGED_PROFILE_USER_ID));
4742 }
4743
4744 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4745 throws Exception {
4746 // Set up a managed profile
4747 final int MANAGED_PROFILE_USER_ID = 15;
4748 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4749 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4750 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4751
4752 final String nonSystemPackage = "non.system.package";
4753 int appId = 12345;
4754 setupPackageInPackageManager(
4755 nonSystemPackage,
4756 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4757 appId, /*flags=*/ 0);
4758
4759 final String systemListener = "system.package";
4760 setupPackageInPackageManager(
4761 systemListener,
4762 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4763 ++appId, ApplicationInfo.FLAG_SYSTEM);
4764
4765 // By default all packages are allowed (for all profiles)
4766 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4767
4768 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4769 assertTrue(dpms.isNotificationListenerServicePermitted(
4770 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4771 assertTrue(dpms.isNotificationListenerServicePermitted(
4772 systemListener, MANAGED_PROFILE_USER_ID));
4773 assertTrue(dpms.isNotificationListenerServicePermitted(
4774 nonSystemPackage, UserHandle.USER_SYSTEM));
4775 assertTrue(dpms.isNotificationListenerServicePermitted(
4776 systemListener, UserHandle.USER_SYSTEM));
4777
4778 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4779 // all allowed in primary profile
4780 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4781 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004782 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004783 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4784
4785 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4786 assertFalse(dpms.isNotificationListenerServicePermitted(
4787 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4788 assertTrue(dpms.isNotificationListenerServicePermitted(
4789 systemListener, MANAGED_PROFILE_USER_ID));
4790 assertTrue(dpms.isNotificationListenerServicePermitted(
4791 nonSystemPackage, UserHandle.USER_SYSTEM));
4792 assertTrue(dpms.isNotificationListenerServicePermitted(
4793 systemListener, UserHandle.USER_SYSTEM));
4794 }
4795
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004796 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004797 mServiceContext.packageName = mRealTestContext.getPackageName();
4798 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4799 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004800 setDeviceOwner();
4801
Pavel Grafov75c0a892017-05-18 17:28:27 +01004802 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004803 }
4804
4805 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004806 mServiceContext.packageName = mRealTestContext.getPackageName();
4807 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4808 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004809 setAsProfileOwner(admin1);
4810
Pavel Grafov75c0a892017-05-18 17:28:27 +01004811 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4812 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004813 }
4814
4815 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004816 mServiceContext.packageName = mRealTestContext.getPackageName();
4817 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4818 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004819 setAsProfileOwner(admin1);
4820
Pavel Grafov75c0a892017-05-18 17:28:27 +01004821 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4822 caller.packageName = "com.example.delegate";
4823 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4824 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004825
Pavel Grafov75c0a892017-05-18 17:28:27 +01004826 // Make caller a delegated cert installer.
4827 runAsCaller(mAdmin1Context, dpms,
4828 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004829
4830 verifyCanGetOwnerInstalledCaCerts(null, caller);
4831 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004832 }
4833
Rubin Xucc391c22018-01-02 20:37:35 +00004834 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004835 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4836 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004837 Bundle restriction = new Bundle();
4838 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4839
4840 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4841 RestrictionsListener listener = new RestrictionsListener(mContext);
4842 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4843 new Bundle());
4844 verifyDataSharingChangedBroadcast();
4845 }
4846
4847 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004848 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4849 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004850 Bundle restriction = new Bundle();
4851 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4852
4853 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4854 RestrictionsListener listener = new RestrictionsListener(mContext);
4855 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4856 restriction);
4857 verifyDataSharingChangedBroadcast();
4858 }
4859
4860 public void testDisallowSharingIntoProfileUnchanged() {
4861 RestrictionsListener listener = new RestrictionsListener(mContext);
4862 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4863 new Bundle());
4864 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4865 }
4866
4867 private void verifyDataSharingChangedBroadcast() {
4868 Intent expectedIntent = new Intent(
4869 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4870 expectedIntent.setPackage("com.android.managedprovisioning");
4871 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4872 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4873 MockUtils.checkIntent(expectedIntent),
4874 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4875 }
4876
yuemingwe3d9c092018-01-11 12:11:44 +00004877 public void testOverrideApnAPIsFailWithPO() throws Exception {
4878 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004879 ApnSetting apn = (new ApnSetting.Builder())
4880 .setApnName("test")
4881 .setEntryName("test")
4882 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4883 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004884 assertExpectException(SecurityException.class, null, () ->
4885 dpm.addOverrideApn(admin1, apn));
4886 assertExpectException(SecurityException.class, null, () ->
4887 dpm.updateOverrideApn(admin1, 0, apn));
4888 assertExpectException(SecurityException.class, null, () ->
4889 dpm.removeOverrideApn(admin1, 0));
4890 assertExpectException(SecurityException.class, null, () ->
4891 dpm.getOverrideApns(admin1));
4892 assertExpectException(SecurityException.class, null, () ->
4893 dpm.setOverrideApnsEnabled(admin1, false));
4894 assertExpectException(SecurityException.class, null, () ->
4895 dpm.isOverrideApnEnabled(admin1));
4896 }
4897
Robin Lee2c68dad2017-03-17 12:50:24 +00004898 private void verifyCanGetOwnerInstalledCaCerts(
4899 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004900 final String alias = "cert";
4901 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004902
4903 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004904 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004905 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4906 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004907 }
4908 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4909
4910 // caller: device admin or delegated certificate installer
4911 callerContext.applicationInfo = new ApplicationInfo();
4912 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4913
4914 // system_server
4915 final DpmMockContext serviceContext = mContext;
4916 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004917 getServices().addPackageContext(callerUser, admin1Context);
4918 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004919
4920 // Install a CA cert.
4921 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004922 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004923 .thenReturn(alias);
4924 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004925 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004926 .thenReturn(asSlice(new String[] {alias}));
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
Robin Lee2c68dad2017-03-17 12:50:24 +00004934 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4935
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004936 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004937 runAsCaller(admin1Context, dpms, (dpm) -> {
4938 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004939 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004940 ownerInstalledCaCerts.addAll(installedCaCerts);
4941 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004942
4943 // Restarting the DPMS should not lose information.
4944 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004945 runAsCaller(admin1Context, dpms, (dpm) ->
4946 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004947
4948 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004949 runAsCaller(serviceContext, dpms, (dpm) -> {
4950 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004951
Robin Lee2c68dad2017-03-17 12:50:24 +00004952 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004953 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004954 });
4955
Pavel Grafov75c0a892017-05-18 17:28:27 +01004956 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4957 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4958 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004959 flushTasks();
4960
4961 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4962 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004963 runAsCaller(admin1Context, dpms, (dpm) -> {
4964 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4965 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004966 }
4967
Robin Lee2c68dad2017-03-17 12:50:24 +00004968 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4969 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004970 final String alias = "cert";
4971 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004972
4973 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004974 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004975 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4976 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004977 }
4978 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4979
4980 // caller: device admin or delegated certificate installer
4981 callerContext.applicationInfo = new ApplicationInfo();
4982 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4983
4984 // system_server
4985 final DpmMockContext serviceContext = mContext;
4986 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004987 getServices().addPackageContext(callerUser, admin1Context);
4988 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004989
4990 // Install a CA cert as caller
4991 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004992 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004993 .thenReturn(alias);
4994 assertTrue(dpm.installCaCert(callerName, caCert));
4995 });
4996
4997 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004998 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004999 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005000 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5001 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5002 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005003 flushTasks();
5004
Robin Lee2c68dad2017-03-17 12:50:24 +00005005 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005006 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00005007
5008 runAsCaller(serviceContext, dpms, (dpm) -> {
5009 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
5010 assertNotNull(ownerInstalledCaCerts);
5011 assertTrue(ownerInstalledCaCerts.isEmpty());
5012 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005013 }
5014
Eran Messeri94d56762017-12-21 20:50:54 +00005015 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
5016 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
5017 Arrays.sort(gotFlags);
5018 Arrays.sort(expectedFlags);
5019 assertTrue(Arrays.equals(expectedFlags, gotFlags));
5020 }
5021
5022 public void testTranslationOfIdAttestationFlag() {
5023 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
5024 int[] correspondingAttUtilsTypes = new int[]{
5025 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
5026 AttestationUtils.ID_TYPE_MEID};
5027
5028 // Test translation of zero flags
5029 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
5030
5031 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
5032 // non-null array
5033 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
5034
5035 // Test translation of a single flag
5036 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
5037 new int[] {AttestationUtils.ID_TYPE_SERIAL});
5038 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
5039
5040 // Test translation of two flags
5041 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
5042 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
5043 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
5044 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
5045
5046 // Test translation of all three flags
5047 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
5048 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5049 AttestationUtils.ID_TYPE_MEID});
5050 // Test translation of all three flags
5051 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
5052 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5053 AttestationUtils.ID_TYPE_MEID});
5054 }
5055
arangelov08d534b2018-01-22 15:20:53 +00005056 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
5057 setDeviceOwner();
5058 initializeDpms();
5059 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5060 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
5061 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
5062 }
5063
5064 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
5065 DpmTestUtils.writeInputStreamToFile(
5066 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5067 getDeviceOwnerPoliciesFile());
5068 DpmTestUtils.writeInputStreamToFile(
5069 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
5070 getDeviceOwnerFile());
5071 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5072 }
5073
5074 public void testRevertDeviceOwnership_deviceNotMigrated()
5075 throws Exception {
5076 DpmTestUtils.writeInputStreamToFile(
5077 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5078 getDeviceOwnerPoliciesFile());
5079 DpmTestUtils.writeInputStreamToFile(
5080 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5081 getDeviceOwnerFile());
5082 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5083 }
5084
5085 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
5086 throws Exception {
5087 DpmTestUtils.writeInputStreamToFile(
5088 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5089 getDeviceOwnerPoliciesFile());
5090 DpmTestUtils.writeInputStreamToFile(
5091 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5092 getDeviceOwnerFile());
5093 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5094 }
5095
5096 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
5097 setupProfileOwner();
5098 initializeDpms();
5099 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5100 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
5101 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
5102 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
5103 }
5104
5105 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
5106 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5107 UserHandle.USER_SYSTEM);
5108 DpmTestUtils.writeInputStreamToFile(
5109 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5110 getProfileOwnerPoliciesFile());
5111 DpmTestUtils.writeInputStreamToFile(
5112 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5113 getProfileOwnerFile());
5114 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5115 }
5116
5117 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
5118 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5119 UserHandle.USER_SYSTEM);
5120 DpmTestUtils.writeInputStreamToFile(
5121 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5122 getProfileOwnerPoliciesFile());
5123 DpmTestUtils.writeInputStreamToFile(
5124 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5125 getProfileOwnerFile());
5126 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5127 }
5128
5129 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5130 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5131 UserHandle.USER_SYSTEM);
5132 DpmTestUtils.writeInputStreamToFile(
5133 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5134 getProfileOwnerPoliciesFile());
5135 DpmTestUtils.writeInputStreamToFile(
5136 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5137 getProfileOwnerFile());
5138 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5139 }
5140
Eran Messeribb271892018-10-17 18:27:50 +01005141 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5142 setupProfileOwner();
5143 configureContextForAccess(mContext, false);
5144
5145 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005146 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005147 }
5148
5149 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5150 setupProfileOwner();
5151 configureContextForAccess(mContext, false);
5152
5153 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005154 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005155 }
5156
5157 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5158 setupProfileOwner();
5159
5160 // This method will throw if the system context could not call
5161 // setProfileOwnerCanAccessDeviceIds successfully.
5162 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5163 }
5164
5165 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5166 when(context.spiedContext.checkCallingPermission(
5167 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5168 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5169 : PackageManager.PERMISSION_DENIED);
5170 }
5171
5172 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5173 setupProfileOwner();
5174
5175 final long ident = mServiceContext.binder.clearCallingIdentity();
5176 configureContextForAccess(mServiceContext, true);
5177
5178 mServiceContext.binder.callingUid =
5179 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5180 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5181 try {
5182 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005183 dpm.setProfileOwnerCanAccessDeviceIds(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005184 });
5185 } finally {
5186 mServiceContext.binder.restoreCallingIdentity(ident);
5187 }
5188 }
5189
5190 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5191 throws Exception {
5192 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5193 setupDeviceOwner();
5194 configureContextForAccess(mContext, false);
5195
5196 // Device owner should be allowed to request Device ID attestation.
5197 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5198 DpmMockContext.CALLER_SYSTEM_USER_UID);
5199
5200 // Another package must not be allowed to request Device ID attestation.
5201 assertExpectException(SecurityException.class, null,
5202 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5203 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5204 // Another component that is not the admin must not be allowed to request Device ID
5205 // attestation.
5206 assertExpectException(SecurityException.class, null,
5207 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5208 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5209 }
5210
5211 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5212 throws Exception {
5213 configureContextForAccess(mContext, false);
5214
5215 // Make sure a security exception is thrown if the device has no profile owner.
5216 assertExpectException(SecurityException.class, null,
5217 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5218 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5219
5220 setupProfileOwner();
5221 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5222
5223 // The profile owner is allowed to request Device ID attestation.
5224 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5225 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5226 DpmMockContext.CALLER_UID);
5227 // But not another package.
5228 assertExpectException(SecurityException.class, null,
5229 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5230 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5231 // Or another component which is not the admin.
5232 assertExpectException(SecurityException.class, null,
5233 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5234 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5235 }
5236
5237 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5238 final long ident = mServiceContext.binder.clearCallingIdentity();
5239
5240 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5241 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5242 try {
5243 runAsCaller(mServiceContext, dpms, action);
5244 } finally {
5245 mServiceContext.binder.restoreCallingIdentity(ident);
5246 }
5247 }
5248
5249 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5250 setupProfileOwner();
5251 markDelegatedCertInstallerAsInstalled();
5252
5253 // Configure a delegated cert installer.
5254 runAsCaller(mServiceContext, dpms,
5255 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5256 Arrays.asList(DELEGATION_CERT_INSTALL)));
5257
5258 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5259
5260 // Make sure that the profile owner can still request Device ID attestation.
5261 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5262 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5263 DpmMockContext.CALLER_UID);
5264
5265 runAsDelegatedCertInstaller(dpm -> {
5266 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5267 DpmMockContext.DELEGATE_PACKAGE_NAME,
5268 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5269 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5270 });
5271 }
5272
5273 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5274 throws Exception {
5275 setupProfileOwner();
5276 markDelegatedCertInstallerAsInstalled();
5277
5278 // Configure a delegated cert installer.
5279 runAsCaller(mServiceContext, dpms,
5280 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5281 Arrays.asList(DELEGATION_CERT_INSTALL)));
5282
5283
5284 assertExpectException(SecurityException.class, null,
5285 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5286 admin1.getPackageName(),
5287 DpmMockContext.CALLER_UID));
5288
5289 runAsDelegatedCertInstaller(dpm -> {
5290 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5291 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5292 DpmMockContext.DELEGATE_PACKAGE_NAME,
5293 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5294 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5295 });
5296 }
5297
Alex Johnston07cb9f02019-11-01 17:40:38 +00005298 public void testGetPasswordComplexity_securityExceptionNotThrownForParentInstance() {
5299 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
5300 setAsProfileOwner(admin1);
5301
5302 new DevicePolicyManagerTestable(
5303 mServiceContext,
5304 dpms,
5305 /* parentInstance= */ true)
5306 .getPasswordComplexity();
5307
5308 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
Bernard Chaue9586552018-11-29 10:59:31 +00005309 }
5310
5311 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5312 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5313 .thenReturn(false);
5314 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5315 }
5316
5317 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5318 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5319 .thenReturn(true);
5320 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5321 }
5322
5323
5324 public void testGetPasswordComplexity_currentUserNoPassword() {
5325 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5326 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005327 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005328 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5329 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5330
5331 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5332 }
5333
5334 public void testGetPasswordComplexity_currentUserHasPassword() {
5335 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5336 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005337 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005338 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5339 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005340 when(getServices().lockSettingsInternal
5341 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005342 .thenReturn(computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005343
5344 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5345 }
5346
5347 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5348 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5349 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005350 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005351
5352 UserInfo parentUser = new UserInfo();
5353 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5354 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5355 .thenReturn(parentUser.id);
5356
Rubin Xu19854862019-08-15 16:37:23 +01005357 when(getServices().lockSettingsInternal
5358 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005359 .thenReturn(computeForPassword("asdf".getBytes()));
Rubin Xu19854862019-08-15 16:37:23 +01005360 when(getServices().lockSettingsInternal
5361 .getUserPasswordMetrics(parentUser.id))
Pavel Grafov6f334842019-08-06 14:37:06 +01005362 .thenReturn(computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005363
5364 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5365 }
5366
yuemingwd2bfbc82019-01-02 11:42:25 +00005367 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5368 setAsProfileOwner(admin1);
5369 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5370 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5371 }
5372
5373 public void testCrossProfileCalendarPackages_reopenDpms() {
5374 setAsProfileOwner(admin1);
5375 dpm.setCrossProfileCalendarPackages(admin1, null);
5376 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5377 assertTrue(packages == null);
5378 initializeDpms();
5379 packages = dpm.getCrossProfileCalendarPackages(admin1);
5380 assertTrue(packages == null);
5381
5382 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5383 packages = dpm.getCrossProfileCalendarPackages(admin1);
5384 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5385 initializeDpms();
5386 packages = dpm.getCrossProfileCalendarPackages(admin1);
5387 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5388
5389 final String dummyPackageName = "test";
5390 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5391 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5392 packages = dpm.getCrossProfileCalendarPackages(admin1);
5393 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5394 initializeDpms();
5395 packages = dpm.getCrossProfileCalendarPackages(admin1);
5396 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5397 }
5398
5399 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5400 assertTrue(expected != null);
5401 assertTrue(actual != null);
5402 assertTrue(expected.containsAll(actual));
5403 assertTrue(actual.containsAll(expected));
5404 }
5405
yuemingwdded98f2019-01-30 17:08:12 +00005406 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5407 setAsProfileOwner(admin1);
5408 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5409 when(getServices().settings.settingsSecureGetIntForUser(
5410 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5411 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5412 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5413 }
5414
5415 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5416 final String testPackage = "TEST_PACKAGE";
5417 setAsProfileOwner(admin1);
5418 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5419 when(getServices().settings.settingsSecureGetIntForUser(
5420 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5421 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5422 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5423 }
5424
5425 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5426 final String testPackage = "TEST_PACKAGE";
5427 setAsProfileOwner(admin1);
5428 dpm.setCrossProfileCalendarPackages(admin1, null);
5429 when(getServices().settings.settingsSecureGetIntForUser(
5430 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5431 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5432 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5433 }
5434
Eran Messeribb271892018-10-17 18:27:50 +01005435 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5436 final long ident = mServiceContext.binder.clearCallingIdentity();
5437 mServiceContext.binder.callingUid =
5438 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5439 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005440 dpm.setProfileOwnerCanAccessDeviceIds(who);
Eran Messeribb271892018-10-17 18:27:50 +01005441 });
5442 mServiceContext.binder.restoreCallingIdentity(ident);
5443 }
5444
arangelov08d534b2018-01-22 15:20:53 +00005445 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5446 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5447 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5448 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5449
5450 final long ident = mServiceContext.binder.clearCallingIdentity();
5451 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5452 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5453 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5454 // To simulate a reboot, we just reinitialize dpms and call systemReady
5455 initializeDpms();
5456
5457 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5458 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5459 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5460 assertTrue(dpm.isAdminActive(admin1));
5461 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5462 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5463
5464 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5465 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5466 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5467 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5468
5469 mServiceContext.binder.restoreCallingIdentity(ident);
5470 }
5471
5472 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5473 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5474 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5475 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5476
5477 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5478 DpmMockContext.CALLER_SYSTEM_USER_UID);
5479 setUpPackageManagerForAdmin(admin1, uid);
5480 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5481 // To simulate a reboot, we just reinitialize dpms and call systemReady
5482 initializeDpms();
5483
5484 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5485 assertTrue(dpm.isAdminActive(admin1));
5486 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5487 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5488 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5489 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5490 }
5491
5492 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5493 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5494 metadataManager.deleteMetadataFile();
5495
5496 final TransferOwnershipMetadataManager.Metadata metadata =
5497 new TransferOwnershipMetadataManager.Metadata(
5498 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5499 callerUserHandle,
5500 adminType);
5501 metadataManager.saveMetadataFile(metadata);
5502 }
5503
5504 private File getDeviceOwnerFile() {
5505 return dpms.mOwners.getDeviceOwnerFile();
5506 }
5507
5508 private File getProfileOwnerFile() {
5509 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5510 }
5511
5512 private File getProfileOwnerPoliciesFile() {
5513 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5514 DpmMockContext.CALLER_USER_HANDLE);
5515 return getPoliciesFile(parentDir);
5516 }
5517
5518 private File getDeviceOwnerPoliciesFile() {
5519 return getPoliciesFile(getServices().systemUserDataDir);
5520 }
5521
5522 private File getPoliciesFile(File parentDir) {
5523 return new File(parentDir, "device_policies.xml");
5524 }
5525
5526 private InputStream getRawStream(@RawRes int id) {
5527 return mRealTestContext.getResources().openRawResource(id);
5528 }
5529
Victor Chang3e794af2016-03-04 13:48:17 +00005530 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005531 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005532 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5533 dpms.notifyChangeToContentObserver(
5534 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5535 }
5536
5537 private void assertProvisioningAllowed(String action, boolean expected) {
5538 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5539 dpm.isProvisioningAllowed(action));
5540 }
Tony Mak2f26b792016-11-28 17:54:51 +00005541
Nicolas Prevot45d29072017-01-18 16:11:19 +00005542 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5543 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005544 final String previousPackageName = mContext.packageName;
5545 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005546
5547 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5548 mContext.packageName = packageName;
5549 mMockContext.binder.callingUid = uid;
5550 assertProvisioningAllowed(action, expected);
5551
5552 // Set the previous package name / calling uid to go back to the initial state.
5553 mContext.packageName = previousPackageName;
5554 mMockContext.binder.callingUid = previousUid;
5555 }
5556
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005557 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005558 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5559 }
5560
5561 private void assertCheckProvisioningPreCondition(
5562 String action, String packageName, int provisioningCondition) {
5563 assertEquals("checkProvisioningPreCondition("
5564 + action + ", " + packageName + ") returning unexpected result",
5565 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005566 }
5567
Tony Mak2f26b792016-11-28 17:54:51 +00005568 /**
5569 * Setup a managed profile with the specified admin and its uid.
5570 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5571 * @param adminUid uid of the admin package.
5572 * @param copyFromAdmin package information for {@code admin} will be built based on this
5573 * component's information.
5574 */
5575 private void addManagedProfile(
5576 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5577 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005578 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005579 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5580 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5581 dpm.setActiveAdmin(admin, false, userId);
5582 assertTrue(dpm.setProfileOwner(admin, null, userId));
5583 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5584 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005585
5586 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005587 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005588 */
Robin Leeabaa0692017-02-20 20:54:22 +00005589 private static StringParceledListSlice asSlice(String[] s) {
5590 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005591 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005592
5593 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005594 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5595 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005596
Robin Lee2c68dad2017-03-17 12:50:24 +00005597 // We can't let exceptions happen on the background thread. Throw them here if they happen
5598 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005599 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005600 }
Victor Chang3e794af2016-03-04 13:48:17 +00005601}