blob: 5825a8b70bfb64791a7588960dc14169928c1740 [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;
yinxuf4f9cec2017-06-19 10:28:19 -070024import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010025import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
26import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
27import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
28
Eugene Susla4f8680b2017-08-07 17:25:30 -070029import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010030
Pavel Grafov75c0a892017-05-18 17:28:27 +010031import static org.mockito.Matchers.any;
32import static org.mockito.Matchers.anyInt;
33import static org.mockito.Matchers.anyLong;
34import static org.mockito.Matchers.anyObject;
35import static org.mockito.Matchers.anyString;
36import static org.mockito.Matchers.eq;
37import static org.mockito.Matchers.isNull;
38import static org.mockito.Mockito.atLeast;
39import static org.mockito.Mockito.doAnswer;
40import static org.mockito.Mockito.doReturn;
41import static org.mockito.Mockito.never;
42import static org.mockito.Mockito.nullable;
43import static org.mockito.Mockito.reset;
44import static org.mockito.Mockito.timeout;
45import static org.mockito.Mockito.times;
46import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080047import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010048import static org.mockito.Mockito.verifyZeroInteractions;
49import static org.mockito.Mockito.when;
50import static org.mockito.hamcrest.MockitoHamcrest.argThat;
51
Makoto Onukif76b06a2015-09-22 15:03:44 -070052import android.Manifest.permission;
53import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000054import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070055import android.app.admin.DeviceAdminReceiver;
56import android.app.admin.DevicePolicyManager;
57import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010058import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070059import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070060import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000061import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000062import android.content.pm.ApplicationInfo;
63import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070064import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010065import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000066import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000067import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010068import android.graphics.Color;
69import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080070import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080071import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070072import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080073import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070074import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070075import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010076import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080077import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010078import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000079import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000080import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000081import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080082import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000083import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010084import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070085import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070086
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010087import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000088import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000089import com.android.server.LocalServices;
90import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000091import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000092import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000093
Robin Lee7f5c91c2017-02-08 21:27:02 +000094import org.hamcrest.BaseMatcher;
95import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -080096import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -070097import org.mockito.invocation.InvocationOnMock;
98import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070099
Makoto Onukic8a5a552015-11-19 14:29:12 -0800100import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000101import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000102import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700103import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700104import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700105import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100106import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000107import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700109/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700110 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000111 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700112 m FrameworksServicesTests &&
113 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000114 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800116 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117
118 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000119 *
120 * , or:
121 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700122 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000123@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100124@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700125public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000126 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
127 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
128 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100129 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800130 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100131 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000132
Pavel Grafov75c0a892017-05-18 17:28:27 +0100133 // TODO replace all instances of this with explicit {@link #mServiceContext}.
134 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700135 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100136
137 private DpmMockContext mServiceContext;
138 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700139 public DevicePolicyManager dpm;
140 public DevicePolicyManagerServiceTestable dpms;
141
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100142 /*
143 * The CA cert below is the content of cacert.pem as generated by:
144 *
145 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
146 */
147 private static final String TEST_CA =
148 "-----BEGIN CERTIFICATE-----\n" +
149 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
150 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
151 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
152 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
153 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
154 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
155 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
156 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
157 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
158 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
159 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
160 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
161 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
162 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
163 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
164 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
165 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
166 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
167 "wQ==\n" +
168 "-----END CERTIFICATE-----\n";
169
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700170 @Override
171 protected void setUp() throws Exception {
172 super.setUp();
173
174 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100175 mServiceContext = mContext;
176 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
177 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700178 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100179 doReturn(Collections.singletonList(new ResolveInfo()))
180 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
181 any(Intent.class),
182 anyInt(),
183 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700184
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800185 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100186 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800187
Makoto Onukia52562c2015-10-01 16:12:31 -0700188 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700189
Sudheer Shanka101c3532018-01-08 16:28:42 -0800190 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800191 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700192 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
193 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
194 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800195 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700196
Pavel Grafov75c0a892017-05-18 17:28:27 +0100197 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
198 mAdmin1Context.packageName = admin1.getPackageName();
199 mAdmin1Context.applicationInfo = new ApplicationInfo();
200 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
201
Makoto Onukib643fb02015-09-22 15:03:44 -0700202 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700203 }
204
Robin Lee2c68dad2017-03-17 12:50:24 +0000205 @Override
206 protected void tearDown() throws Exception {
207 flushTasks();
208 super.tearDown();
209 }
210
Makoto Onukia52562c2015-10-01 16:12:31 -0700211 private void initializeDpms() {
212 // Need clearCallingIdentity() to pass permission checks.
213 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100214 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700215
Pavel Grafov75c0a892017-05-18 17:28:27 +0100216 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
217 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
218 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700219
Pavel Grafov75c0a892017-05-18 17:28:27 +0100220 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700221
Pavel Grafov75c0a892017-05-18 17:28:27 +0100222 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700223 }
224
Makoto Onukib643fb02015-09-22 15:03:44 -0700225 private void setUpUserManager() {
226 // Emulate UserManager.set/getApplicationRestriction().
227 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
228
229 // UM.setApplicationRestrictions() will save to appRestrictions.
230 doAnswer(new Answer<Void>() {
231 @Override
232 public Void answer(InvocationOnMock invocation) throws Throwable {
233 String pkg = (String) invocation.getArguments()[0];
234 Bundle bundle = (Bundle) invocation.getArguments()[1];
235 UserHandle user = (UserHandle) invocation.getArguments()[2];
236
237 appRestrictions.put(Pair.create(pkg, user), bundle);
238
239 return null;
240 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100241 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100242 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700243
244 // UM.getApplicationRestrictions() will read from appRestrictions.
245 doAnswer(new Answer<Bundle>() {
246 @Override
247 public Bundle answer(InvocationOnMock invocation) throws Throwable {
248 String pkg = (String) invocation.getArguments()[0];
249 UserHandle user = (UserHandle) invocation.getArguments()[1];
250
251 return appRestrictions.get(Pair.create(pkg, user));
252 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100253 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700254 anyString(), any(UserHandle.class));
255
Makoto Onukid932f762015-09-29 16:53:38 -0700256 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100257 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700258 }
259
260 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100261 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700262
Pavel Grafov75c0a892017-05-18 17:28:27 +0100263 mServiceContext.binder.callingUid =
264 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
265 runAsCaller(mServiceContext, dpms, dpm -> {
266 // PO needs to be a DA.
267 dpm.setActiveAdmin(admin, /*replace=*/ false);
268 // Fire!
269 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
270 // Check
271 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
272 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700273
Pavel Grafov75c0a892017-05-18 17:28:27 +0100274 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700275 }
276
277 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100278 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700279 .thenReturn(false);
280
281 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100282 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700283
284 // If the device has no DPMS feature, it shouldn't register the local service.
285 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
286 }
287
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800288 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800289 // Device owner in SYSTEM_USER
290 setDeviceOwner();
291 // Profile owner in CALLER_USER_HANDLE
292 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
293 setAsProfileOwner(admin2);
294 // Active admin in CALLER_USER_HANDLE
295 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
296 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
297 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
298 DpmMockContext.CALLER_USER_HANDLE);
299 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
300 DpmMockContext.CALLER_USER_HANDLE));
301
302 initializeDpms();
303
304 // Verify
305 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800306 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800307 eq(UserHandle.USER_SYSTEM));
308 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800309 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800310 adminAnotherPackage.getPackageName()),
311 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800312 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
313 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
314 }
315
316 public void testLoadAdminData_noAdmins() throws Exception {
317 final int ANOTHER_USER_ID = 15;
318 getServices().addUser(ANOTHER_USER_ID, 0);
319
320 initializeDpms();
321
322 // Verify
323 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
324 null, DpmMockContext.CALLER_USER_HANDLE);
325 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
326 null, ANOTHER_USER_ID);
327 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
328 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800329 }
330
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700331 /**
332 * Caller doesn't have proper permissions.
333 */
334 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700335 // 1. Failure cases.
336
337 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100338 assertExpectException(SecurityException.class, /* messageRegex= */ null,
339 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700340
341 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
342 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100343
344 assertExpectException(SecurityException.class, /* messageRegex= */ null,
345 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700346 }
347
Makoto Onukif76b06a2015-09-22 15:03:44 -0700348 /**
349 * Test for:
350 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800351 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700352 * {@link DevicePolicyManager#isAdminActive}
353 * {@link DevicePolicyManager#isAdminActiveAsUser}
354 * {@link DevicePolicyManager#getActiveAdmins}
355 * {@link DevicePolicyManager#getActiveAdminsAsUser}
356 */
357 public void testSetActiveAdmin() throws Exception {
358 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700359 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
360
Makoto Onukif76b06a2015-09-22 15:03:44 -0700361 // 2. Call the API.
362 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700363
364 // 3. Verify internal calls.
365
366 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700367 verify(mContext.spiedContext).sendBroadcastAsUser(
368 MockUtils.checkIntentAction(
369 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
370 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
371 verify(mContext.spiedContext).sendBroadcastAsUser(
372 MockUtils.checkIntentAction(
373 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700374 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
375
Pavel Grafov75c0a892017-05-18 17:28:27 +0100376 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700377 eq(admin1.getPackageName()),
378 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
379 eq(PackageManager.DONT_KILL_APP),
380 eq(DpmMockContext.CALLER_USER_HANDLE),
381 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700382
Sudheer Shanka101c3532018-01-08 16:28:42 -0800383 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
384 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
385
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700386 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700387
388 // Make sure it's active admin1.
389 assertTrue(dpm.isAdminActive(admin1));
390 assertFalse(dpm.isAdminActive(admin2));
391 assertFalse(dpm.isAdminActive(admin3));
392
393 // But not admin1 for a different user.
394
395 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
396 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
397 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
398
399 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
400 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
401
402 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
403
404 // Next, add one more admin.
405 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700406 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700407 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700408
409 dpm.setActiveAdmin(admin2, /* replace =*/ false);
410
411 // Now we have two admins.
412 assertTrue(dpm.isAdminActive(admin1));
413 assertTrue(dpm.isAdminActive(admin2));
414 assertFalse(dpm.isAdminActive(admin3));
415
416 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
417 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100418 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700419 eq(admin1.getPackageName()),
420 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
421 eq(PackageManager.DONT_KILL_APP),
422 eq(DpmMockContext.CALLER_USER_HANDLE),
423 anyString());
424
Sudheer Shanka101c3532018-01-08 16:28:42 -0800425 // times(2) because it was previously called for admin1 which is in the same package
426 // as admin2.
427 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
428 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
429
Makoto Onukif76b06a2015-09-22 15:03:44 -0700430 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100431 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
432 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700433
434 // 5. Add the same admin1 again with replace, which should succeed.
435 dpm.setActiveAdmin(admin1, /* replace =*/ true);
436
437 // TODO make sure it's replaced.
438
439 // 6. Test getActiveAdmins()
440 List<ComponentName> admins = dpm.getActiveAdmins();
441 assertEquals(2, admins.size());
442 assertEquals(admin1, admins.get(0));
443 assertEquals(admin2, admins.get(1));
444
Sudheer Shanka101c3532018-01-08 16:28:42 -0800445 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
446 // replaced
447 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
448
Makoto Onukif76b06a2015-09-22 15:03:44 -0700449 // Another user has no admins.
450 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
451
452 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
453 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
454
455 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
456 }
457
Makoto Onukid932f762015-09-29 16:53:38 -0700458 public void testSetActiveAdmin_multiUsers() throws Exception {
459
460 final int ANOTHER_USER_ID = 100;
461 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
462
Pavel Grafov75c0a892017-05-18 17:28:27 +0100463 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700464
465 // Set up pacakge manager for the other user.
466 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700467
468 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
469
470 dpm.setActiveAdmin(admin1, /* replace =*/ false);
471
472 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
473 dpm.setActiveAdmin(admin2, /* replace =*/ false);
474
475
476 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
477 assertTrue(dpm.isAdminActive(admin1));
478 assertFalse(dpm.isAdminActive(admin2));
479
480 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
481 assertFalse(dpm.isAdminActive(admin1));
482 assertTrue(dpm.isAdminActive(admin2));
483 }
484
Makoto Onukif76b06a2015-09-22 15:03:44 -0700485 /**
486 * Test for:
487 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800488 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700489 */
490 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
491 // 1. Make sure the caller has proper permissions.
492 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
493
494 dpm.setActiveAdmin(admin1, /* replace =*/ false);
495 assertTrue(dpm.isAdminActive(admin1));
496
497 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100498 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
499 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700500 }
501
502 /**
503 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800504 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
505 * BIND_DEVICE_ADMIN.
506 */
507 public void testSetActiveAdmin_permissionCheck() throws Exception {
508 // 1. Make sure the caller has proper permissions.
509 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
510
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100511 assertExpectException(IllegalArgumentException.class,
512 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
513 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800514 assertFalse(dpm.isAdminActive(adminNoPerm));
515
516 // Change the target API level to MNC. Now it can be set as DA.
517 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
518 VERSION_CODES.M);
519 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
520 assertTrue(dpm.isAdminActive(adminNoPerm));
521
522 // TODO Test the "load from the file" case where DA will still be loaded even without
523 // BIND_DEVICE_ADMIN and target API is N.
524 }
525
526 /**
527 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700528 * {@link DevicePolicyManager#removeActiveAdmin}
529 */
530 public void testRemoveActiveAdmin_SecurityException() {
531 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
532
533 // Add admin.
534
535 dpm.setActiveAdmin(admin1, /* replace =*/ false);
536
537 assertTrue(dpm.isAdminActive(admin1));
538
539 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
540
541 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100542 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
543 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700544
545 // Try to remove active admin with a different caller userid should fail too, without
546 // having MANAGE_DEVICE_ADMINS.
547 mContext.callerPermissions.clear();
548
Makoto Onukid932f762015-09-29 16:53:38 -0700549 // Change the caller, and call into DPMS directly with a different user-id.
550
Makoto Onukif76b06a2015-09-22 15:03:44 -0700551 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100552 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
553 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700554 }
555
556 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800557 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
558 * (because we can't send the remove broadcast).
559 */
560 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
561 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
562
563 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
564
565 // Add admin.
566
567 dpm.setActiveAdmin(admin1, /* replace =*/ false);
568
569 assertTrue(dpm.isAdminActive(admin1));
570
571 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
572
573 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100574 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800575 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100576 assertExpectException(IllegalStateException.class,
577 /* messageRegex= */ "User must be running and unlocked",
578 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800579
580 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800581 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
582 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800583
584 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100585 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800586 .thenReturn(true);
587
588 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700589 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800590 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
591 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800592 }
593
594 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700595 * Test for:
596 * {@link DevicePolicyManager#removeActiveAdmin}
597 */
Makoto Onukid932f762015-09-29 16:53:38 -0700598 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700599 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
600
601 // Add admin1.
602
603 dpm.setActiveAdmin(admin1, /* replace =*/ false);
604
605 assertTrue(dpm.isAdminActive(admin1));
606 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
607
608 // Different user, but should work, because caller has proper permissions.
609 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700610
611 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700612 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700613
614 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700615 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800616 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
617 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700618
619 // TODO DO Still can't be removed in this case.
620 }
621
622 /**
623 * Test for:
624 * {@link DevicePolicyManager#removeActiveAdmin}
625 */
626 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
627 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
628 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
629
630 // Add admin1.
631
632 dpm.setActiveAdmin(admin1, /* replace =*/ false);
633
634 assertTrue(dpm.isAdminActive(admin1));
635 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
636
637 // Broadcast from saveSettingsLocked().
638 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
639 MockUtils.checkIntentAction(
640 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
641 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
642
643 // Remove. No permissions, but same user, so it'll work.
644 mContext.callerPermissions.clear();
645 dpm.removeActiveAdmin(admin1);
646
Makoto Onukif76b06a2015-09-22 15:03:44 -0700647 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
648 MockUtils.checkIntentAction(
649 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
650 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
651 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700652 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700653 eq(dpms.mHandler),
654 eq(Activity.RESULT_OK),
655 isNull(String.class),
656 isNull(Bundle.class));
657
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700658 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800659 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
660 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700661
662 // Again broadcast from saveSettingsLocked().
663 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
664 MockUtils.checkIntentAction(
665 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
666 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
667
668 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700669 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700670
Sudheer Shanka101c3532018-01-08 16:28:42 -0800671 public void testRemoveActiveAdmin_multipleAdminsInUser() {
672 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
673 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
674
675 // Add admin1.
676 dpm.setActiveAdmin(admin1, /* replace =*/ false);
677
678 assertTrue(dpm.isAdminActive(admin1));
679 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
680
681 // Add admin2.
682 dpm.setActiveAdmin(admin2, /* replace =*/ false);
683
684 assertTrue(dpm.isAdminActive(admin2));
685 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
686
687 // Broadcast from saveSettingsLocked().
688 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
689 MockUtils.checkIntentAction(
690 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
691 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
692
693 // Remove. No permissions, but same user, so it'll work.
694 mContext.callerPermissions.clear();
695 dpm.removeActiveAdmin(admin1);
696
697 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
698 MockUtils.checkIntentAction(
699 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
700 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
701 isNull(String.class),
702 any(BroadcastReceiver.class),
703 eq(dpms.mHandler),
704 eq(Activity.RESULT_OK),
705 isNull(String.class),
706 isNull(Bundle.class));
707
708 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
709 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800710 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800711 eq(DpmMockContext.CALLER_USER_HANDLE));
712
713 // Again broadcast from saveSettingsLocked().
714 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
715 MockUtils.checkIntentAction(
716 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
717 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
718 }
719
720 /**
721 * Test for:
722 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
723 */
724 public void testForceRemoveActiveAdmin() throws Exception {
725 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
726
727 // Add admin.
728 setupPackageInPackageManager(admin1.getPackageName(),
729 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
730 /* appId= */ 10138,
731 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
732 dpm.setActiveAdmin(admin1, /* replace =*/ false);
733 assertTrue(dpm.isAdminActive(admin1));
734
735 // Calling from a non-shell uid should fail with a SecurityException
736 mContext.binder.callingUid = 123456;
737 assertExpectException(SecurityException.class,
738 /* messageRegex =*/ "Non-shell user attempted to call",
739 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
740
741 mContext.binder.callingUid = Process.SHELL_UID;
742 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
743
744 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
745 // Verify
746 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
747 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
748 null, DpmMockContext.CALLER_USER_HANDLE);
749 }
750
Makoto Onukib643fb02015-09-22 15:03:44 -0700751 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000752 * Test for: @{link DevicePolicyManager#setActivePasswordState}
753 *
754 * Validates that when the password for a user changes, the notification broadcast intent
755 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
756 * addition to ones in the original user.
757 */
758 public void testSetActivePasswordState_sendToProfiles() throws Exception {
759 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
760
761 final int MANAGED_PROFILE_USER_ID = 78;
762 final int MANAGED_PROFILE_ADMIN_UID =
763 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
764
765 // Setup device owner.
766 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
767 mContext.packageName = admin1.getPackageName();
768 setupDeviceOwner();
769
770 // Add a managed profile belonging to the system user.
771 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
772
773 // Change the parent user's password.
774 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
775
776 // Both the device owner and the managed profile owner should receive this broadcast.
777 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
778 intent.setComponent(admin1);
779 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
780
781 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
782 MockUtils.checkIntent(intent),
783 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
784 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
785 MockUtils.checkIntent(intent),
786 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
787 }
788
789 /**
790 * Test for: @{link DevicePolicyManager#setActivePasswordState}
791 *
792 * Validates that when the password for a managed profile changes, the notification broadcast
793 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
794 * its parent.
795 */
796 public void testSetActivePasswordState_notSentToParent() throws Exception {
797 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
798
799 final int MANAGED_PROFILE_USER_ID = 78;
800 final int MANAGED_PROFILE_ADMIN_UID =
801 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
802
803 // Setup device owner.
804 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
805 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100806 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000807 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
808 setupDeviceOwner();
809
810 // Add a managed profile belonging to the system user.
811 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
812
813 // Change the profile's password.
814 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
815
816 // Both the device owner and the managed profile owner should receive this broadcast.
817 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
818 intent.setComponent(admin1);
819 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
820
821 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
822 MockUtils.checkIntent(intent),
823 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
824 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
825 MockUtils.checkIntent(intent),
826 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
827 }
828 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000829 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700830 */
831 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000832 setDeviceOwner();
833
834 // Try to set a profile owner on the same user, which should fail.
835 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
836 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100837 assertExpectException(IllegalStateException.class,
838 /* messageRegex= */ "already has a device owner",
839 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000840
841 // DO admin can't be deactivated.
842 dpm.removeActiveAdmin(admin1);
843 assertTrue(dpm.isAdminActive(admin1));
844
845 // TODO Test getDeviceOwnerName() too. To do so, we need to change
846 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
847 }
848
849 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700850 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800851 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700852 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
853 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
854
Makoto Onukid932f762015-09-29 16:53:38 -0700855 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700856 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
857
Makoto Onukid932f762015-09-29 16:53:38 -0700858 // Make sure admin1 is installed on system user.
859 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700860
Makoto Onukic8a5a552015-11-19 14:29:12 -0800861 // Check various get APIs.
862 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
863
Makoto Onukib643fb02015-09-22 15:03:44 -0700864 // DO needs to be an DA.
865 dpm.setActiveAdmin(admin1, /* replace =*/ false);
866
867 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700868 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700869
Makoto Onukic8a5a552015-11-19 14:29:12 -0800870 // getDeviceOwnerComponent should return the admin1 component.
871 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
872 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
873
874 // Check various get APIs.
875 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
876
877 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
878 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
879 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
880 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
881
882 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
883
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000884 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100885 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000886 eq(admin1.getPackageName()));
887
Makoto Onukib643fb02015-09-22 15:03:44 -0700888 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100889 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700890 eq(UserHandle.USER_SYSTEM), eq(false));
891
892 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
893 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
894 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
895
Makoto Onukic8a5a552015-11-19 14:29:12 -0800896 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700897 }
898
Makoto Onukic8a5a552015-11-19 14:29:12 -0800899 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
900 final int origCallingUser = mContext.binder.callingUid;
901 final List origPermissions = new ArrayList(mContext.callerPermissions);
902 mContext.callerPermissions.clear();
903
904 mContext.callerPermissions.add(permission.MANAGE_USERS);
905
906 mContext.binder.callingUid = Process.SYSTEM_UID;
907
908 // TODO Test getDeviceOwnerName() too. To do so, we need to change
909 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
910 if (hasDeviceOwner) {
911 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
912 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
913 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
914
915 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
916 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
917 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
918 } else {
919 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
920 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
921 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
922
923 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
924 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
925 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
926 }
927
928 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
929 if (hasDeviceOwner) {
930 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
931 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
932 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
933
934 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
935 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
936 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
937 } else {
938 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
939 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
940 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
941
942 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
943 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
944 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
945 }
946
947 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
948 // Still with MANAGE_USERS.
949 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
950 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
951 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
952
953 if (hasDeviceOwner) {
954 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
955 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
956 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
957 } else {
958 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
959 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
960 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
961 }
962
963 mContext.binder.callingUid = Process.SYSTEM_UID;
964 mContext.callerPermissions.remove(permission.MANAGE_USERS);
965 // System can still call "OnAnyUser" without MANAGE_USERS.
966 if (hasDeviceOwner) {
967 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
968 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
969 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
970
971 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
972 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
973 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
974 } else {
975 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
976 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
977 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
978
979 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
980 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
981 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
982 }
983
984 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
985 // Still no MANAGE_USERS.
986 if (hasDeviceOwner) {
987 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
988 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
989 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
990 } else {
991 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
992 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
993 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
994 }
995
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100996 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
997 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
998 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
999 dpm::getDeviceOwnerComponentOnAnyUser);
1000 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1001 dpm::getDeviceOwnerUserId);
1002 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1003 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001004
1005 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1006 // Still no MANAGE_USERS.
1007 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1008 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1009 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1010
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001011 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1012 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1013 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1014 dpm::getDeviceOwnerComponentOnAnyUser);
1015 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1016 dpm::getDeviceOwnerUserId);
1017 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1018 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001019
1020 // Restore.
1021 mContext.binder.callingUid = origCallingUser;
1022 mContext.callerPermissions.addAll(origPermissions);
1023 }
1024
1025
Makoto Onukib643fb02015-09-22 15:03:44 -07001026 /**
1027 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1028 */
1029 public void testSetDeviceOwner_noSuchPackage() {
1030 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001031 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001032 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1033 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1034
1035 // Call from a process on the system user.
1036 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1037
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001038 assertExpectException(IllegalArgumentException.class,
1039 /* messageRegex= */ "Invalid component",
1040 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001041 }
1042
1043 public void testSetDeviceOwner_failures() throws Exception {
1044 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1045 }
1046
Makoto Onukia52562c2015-10-01 16:12:31 -07001047 public void testClearDeviceOwner() throws Exception {
1048 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001049 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001050 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1051 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1052
1053 // Set admin1 as a DA to the secondary user.
1054 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1055
1056 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1057
1058 // Set admin 1 as the DO to the system user.
1059
1060 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1061 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1062 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1063 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1064
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001065 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001066 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001067 eq(admin1.getPackageName()));
1068
Makoto Onukic8a5a552015-11-19 14:29:12 -08001069 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001070
Makoto Onuki90b89652016-01-28 14:44:18 -08001071 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001072 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001073 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001074
1075 assertTrue(dpm.isAdminActive(admin1));
1076 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1077
Makoto Onukia52562c2015-10-01 16:12:31 -07001078 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001079 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001080
1081 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001082 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1083 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001084
1085 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001086 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001087 assertExpectException(IllegalStateException.class,
1088 /* messageRegex= */ "User must be running and unlocked",
1089 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001090
Pavel Grafov75c0a892017-05-18 17:28:27 +01001091 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1092 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001093 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1094
1095 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001096 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001097
Pavel Grafov75c0a892017-05-18 17:28:27 +01001098 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001099 eq(false),
1100 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1101
Pavel Grafov75c0a892017-05-18 17:28:27 +01001102 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001103 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001104 eq(null),
1105 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001106
Sudheer Shanka101c3532018-01-08 16:28:42 -08001107 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1108 null, UserHandle.USER_SYSTEM);
1109
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001110 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001111
1112 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1113 // and once for clearing it.
1114 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1115 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1116 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001117 // TODO Check other calls.
1118 }
1119
1120 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1121 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001122 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001123 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1124 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1125
1126 // Set admin1 as a DA to the secondary user.
1127 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1128
1129 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1130
1131 // Set admin 1 as the DO to the system user.
1132
1133 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1134 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1135 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1136 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1137
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001138 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001139 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001140 eq(admin1.getPackageName()));
1141
Makoto Onukic8a5a552015-11-19 14:29:12 -08001142 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001143
1144 // Now call clear from the secondary user, which should throw.
1145 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1146
1147 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001148 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001149 eq(admin1.getPackageName()),
1150 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001151 assertExpectException(SecurityException.class,
1152 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1153 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001154
Makoto Onukic8a5a552015-11-19 14:29:12 -08001155 // DO shouldn't be removed.
1156 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001157 }
1158
Makoto Onukib643fb02015-09-22 15:03:44 -07001159 public void testSetProfileOwner() throws Exception {
1160 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001161
Makoto Onuki90b89652016-01-28 14:44:18 -08001162 // PO admin can't be deactivated.
1163 dpm.removeActiveAdmin(admin1);
1164 assertTrue(dpm.isAdminActive(admin1));
1165
Makoto Onuki803d6752015-10-30 12:58:39 -07001166 // Try setting DO on the same user, which should fail.
1167 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001168 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1169 runAsCaller(mServiceContext, dpms, dpm -> {
1170 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001171 assertExpectException(IllegalStateException.class,
1172 /* messageRegex= */ "already has a profile owner",
1173 () -> dpm.setDeviceOwner(admin2, "owner-name",
1174 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001175 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001176 }
1177
Makoto Onuki90b89652016-01-28 14:44:18 -08001178 public void testClearProfileOwner() throws Exception {
1179 setAsProfileOwner(admin1);
1180
1181 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1182
1183 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1184 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1185
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001186 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001187 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001188 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001189 assertExpectException(IllegalStateException.class,
1190 /* messageRegex= */ "User must be running and unlocked",
1191 () -> dpm.clearProfileOwner(admin1));
1192
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001193 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001194 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001195 dpm.clearProfileOwner(admin1);
1196
1197 // Check
1198 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001199 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001200 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1201 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001202 }
1203
Makoto Onukib643fb02015-09-22 15:03:44 -07001204 public void testSetProfileOwner_failures() throws Exception {
1205 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1206 }
1207
Makoto Onukia52562c2015-10-01 16:12:31 -07001208 public void testGetDeviceOwnerAdminLocked() throws Exception {
1209 checkDeviceOwnerWithMultipleDeviceAdmins();
1210 }
1211
1212 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1213 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1214 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1215 // make sure it gets the right component from the right user.
1216
1217 final int ANOTHER_USER_ID = 100;
1218 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1219
Pavel Grafov75c0a892017-05-18 17:28:27 +01001220 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001221
1222 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001223 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001224 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1225 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1226
1227 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1228
Pavel Grafov75c0a892017-05-18 17:28:27 +01001229 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001230
Makoto Onukia52562c2015-10-01 16:12:31 -07001231 // Make sure the admin packge is installed to each user.
1232 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1233 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1234
1235 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1236 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1237
1238 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1239
1240
1241 // Set active admins to the users.
1242 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1243 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1244
1245 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1246 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1247
1248 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1249
1250 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001251 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001252 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1253
Makoto Onukic8a5a552015-11-19 14:29:12 -08001254 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001255
1256 // Then check getDeviceOwnerAdminLocked().
1257 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1258 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1259 }
1260
1261 /**
1262 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001263 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1264 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001265 *
1266 * We didn't use to persist the DO component class name, but now we do, and the above method
1267 * finds the right component from a package name upon migration.
1268 */
1269 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001270 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001271 checkDeviceOwnerWithMultipleDeviceAdmins();
1272
1273 // Overwrite the device owner setting and clears the clas name.
1274 dpms.mOwners.setDeviceOwner(
1275 new ComponentName(admin2.getPackageName(), ""),
1276 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1277 dpms.mOwners.writeDeviceOwner();
1278
1279 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001280 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001281
1282 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001283 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001284 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001285 initializeDpms();
1286
1287 // Now the DO component name is a full name.
1288 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1289 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001290 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001291 }
1292
Makoto Onukib643fb02015-09-22 15:03:44 -07001293 public void testSetGetApplicationRestriction() {
1294 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001295 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001296
1297 {
1298 Bundle rest = new Bundle();
1299 rest.putString("KEY_STRING", "Foo1");
1300 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1301 }
1302
1303 {
1304 Bundle rest = new Bundle();
1305 rest.putString("KEY_STRING", "Foo2");
1306 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1307 }
1308
1309 {
1310 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1311 assertNotNull(returned);
1312 assertEquals(returned.size(), 1);
1313 assertEquals(returned.get("KEY_STRING"), "Foo1");
1314 }
1315
1316 {
1317 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1318 assertNotNull(returned);
1319 assertEquals(returned.size(), 1);
1320 assertEquals(returned.get("KEY_STRING"), "Foo2");
1321 }
1322
1323 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1324 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1325 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001326
Edman Anjosf9946772016-11-28 16:35:15 +01001327 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001328 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1329 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001330 *
1331 * @param packageName the name of the package to be setup
1332 * @param appId the application ID to be given to the package
1333 * @return the UID of the package as known by the mock package manager
1334 */
1335 private int setupPackageInPackageManager(final String packageName, final int appId)
1336 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001337 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001338 ApplicationInfo.FLAG_HAS_CODE);
1339 }
1340
1341 /**
1342 * Setup a package in the package manager mock. Useful for faking installed applications.
1343 *
1344 * @param packageName the name of the package to be setup
1345 * @param userId the user id where the package will be "installed"
1346 * @param appId the application ID to be given to the package
1347 * @param flags flags to set in the ApplicationInfo for this package
1348 * @return the UID of the package as known by the mock package manager
1349 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001350 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1351 int flags) throws Exception {
1352 final int uid = UserHandle.getUid(userId, appId);
1353 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001354 final PackageInfo pi = new PackageInfo();
1355 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001356 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001357 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001358 eq(packageName),
1359 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001360 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001361 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001362 eq(packageName),
1363 anyInt(),
1364 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001365 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001366 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001367 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001368 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001369 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001370 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001371 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001372 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001373 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001374 return uid;
1375 }
1376
Robin Lee7f5c91c2017-02-08 21:27:02 +00001377 public void testCertificateDisclosure() throws Exception {
1378 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1379 final UserHandle user = UserHandle.of(userId);
1380
1381 mContext.applicationInfo = new ApplicationInfo();
1382 mContext.callerPermissions.add(permission.MANAGE_USERS);
1383 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001384 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001385 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1386
Robin Leeabaa0692017-02-20 20:54:22 +00001387 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1388 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001389
1390 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1391 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1392
1393 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001394 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001395 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001396 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001397 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001398 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001399 .cancelAsUser(anyString(), anyInt(), eq(user));
1400
1401 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001402 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001403 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001404 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1405 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001406 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001407 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001408 .notifyAsUser(anyString(), anyInt(), argThat(
1409 new BaseMatcher<Notification>() {
1410 @Override
1411 public boolean matches(Object item) {
1412 final Notification noti = (Notification) item;
1413 return TEST_STRING.equals(
1414 noti.extras.getString(Notification.EXTRA_TITLE));
1415 }
1416 @Override
1417 public void describeTo(Description description) {
1418 description.appendText(
1419 "Notification{title=\"" + TEST_STRING + "\"}");
1420 }
1421 }), eq(user));
1422 }
1423
Edman Anjosf9946772016-11-28 16:35:15 +01001424 /**
1425 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1426 * privileges can acually be exercised by a delegate are not covered here.
1427 */
1428 public void testDelegation() throws Exception {
1429 setAsProfileOwner(admin1);
1430
1431 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1432
1433 // Given two packages
1434 final String CERT_DELEGATE = "com.delegate.certs";
1435 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1436 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1437 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1438 20989);
1439
1440 // On delegation
1441 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1442 mContext.packageName = admin1.getPackageName();
1443 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1444 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1445
1446 // DPMS correctly stores and retrieves the delegates
1447 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1448 assertEquals(2, policy.mDelegationMap.size());
1449 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1450 DELEGATION_CERT_INSTALL);
1451 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1452 DELEGATION_CERT_INSTALL);
1453 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1454 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1455 DELEGATION_APP_RESTRICTIONS);
1456 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1457 DELEGATION_APP_RESTRICTIONS);
1458 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1459
1460 // On calling install certificate APIs from an unauthorized process
1461 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1462 mContext.packageName = RESTRICTIONS_DELEGATE;
1463
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001464 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1465 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001466
1467 // On calling install certificate APIs from an authorized process
1468 mContext.binder.callingUid = CERT_DELEGATE_UID;
1469 mContext.packageName = CERT_DELEGATE;
1470
1471 // DPMS executes without a SecurityException
1472 try {
1473 dpm.installCaCert(null, null);
1474 } catch (SecurityException unexpected) {
1475 fail("Threw SecurityException on authorized access");
1476 } catch (NullPointerException expected) {
1477 }
1478
1479 // On removing a delegate
1480 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1481 mContext.packageName = admin1.getPackageName();
1482 dpm.setCertInstallerPackage(admin1, null);
1483
1484 // DPMS does not allow access to ex-delegate
1485 mContext.binder.callingUid = CERT_DELEGATE_UID;
1486 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001487 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1488 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001489
1490 // But still allows access to other existing delegates
1491 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1492 mContext.packageName = RESTRICTIONS_DELEGATE;
1493 try {
1494 dpm.getApplicationRestrictions(null, "pkg");
1495 } catch (SecurityException expected) {
1496 fail("Threw SecurityException on authorized access");
1497 }
1498 }
1499
Esteban Talaverabf60f722015-12-10 16:26:44 +00001500 public void testApplicationRestrictionsManagingApp() throws Exception {
1501 setAsProfileOwner(admin1);
1502
Rubin Xued1928a2016-02-11 17:23:06 +00001503 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001504 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001505 final String nonDelegateExceptionMessageRegex =
1506 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001507 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001508 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1509 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001510
Esteban Talaverabf60f722015-12-10 16:26:44 +00001511 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1512 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001513 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1514 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001515 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001516 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001517 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001518 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1519 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001520
1521 // Check via the profile owner that no restrictions were set.
1522 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001523 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001524 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1525
Rubin Xued1928a2016-02-11 17:23:06 +00001526 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001527 assertExpectException(PackageManager.NameNotFoundException.class,
1528 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1529 () -> dpm.setApplicationRestrictionsManagingPackage(
1530 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001531
Esteban Talaverabf60f722015-12-10 16:26:44 +00001532 // Let appRestrictionsManagerPackage manage app restrictions
1533 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1534 assertEquals(appRestrictionsManagerPackage,
1535 dpm.getApplicationRestrictionsManagingPackage(admin1));
1536
1537 // Now that package should be able to set and retrieve app restrictions.
1538 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001539 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001540 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1541 dpm.setApplicationRestrictions(null, "pkg1", rest);
1542 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1543 assertEquals(1, returned.size(), 1);
1544 assertEquals("Foo1", returned.get("KEY_STRING"));
1545
1546 // The same app running on a separate user shouldn't be able to manage app restrictions.
1547 mContext.binder.callingUid = UserHandle.getUid(
1548 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1549 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001550 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1551 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001552
1553 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1554 // too.
1555 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001556 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001557 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1558 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1559 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1560
1561 // Removing the ability for the package to manage app restrictions.
1562 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1563 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1564 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001565 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001566 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001567 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1568 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001569 }
1570
Makoto Onukia4f11972015-10-01 13:19:58 -07001571 public void testSetUserRestriction_asDo() throws Exception {
1572 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001573 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001574 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1575 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1576
1577 // First, set DO.
1578
1579 // Call from a process on the system user.
1580 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1581
1582 // Make sure admin1 is installed on system user.
1583 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001584
1585 // Call.
1586 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001587 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001588 UserHandle.USER_SYSTEM));
1589
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001590 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001591 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001592 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001593 DpmTestUtils.assertRestrictions(
1594 DpmTestUtils.newRestrictions(defaultRestrictions),
1595 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1596 );
1597 DpmTestUtils.assertRestrictions(
1598 DpmTestUtils.newRestrictions(defaultRestrictions),
1599 dpm.getUserRestrictions(admin1)
1600 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001601 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001602 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001603 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001604 eq(true) /* isDeviceOwner */,
1605 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001606 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001607 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001608
1609 for (String restriction : defaultRestrictions) {
1610 dpm.clearUserRestriction(admin1, restriction);
1611 }
1612
Esteban Talavera548a04b2016-12-20 15:22:30 +00001613 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001614 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001615
1616 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001617 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001618 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001619 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1620 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001621 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001622
Makoto Onukia4f11972015-10-01 13:19:58 -07001623 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001624 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001625 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001626 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1627 UserManager.DISALLOW_ADD_USER),
1628 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001629 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001630
Makoto Onuki068c54a2015-10-13 14:34:03 -07001631 DpmTestUtils.assertRestrictions(
1632 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001633 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001634 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1635 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001636 DpmTestUtils.assertRestrictions(
1637 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001638 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001639 dpm.getUserRestrictions(admin1)
1640 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001641
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001642 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001643 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001644 eq(UserHandle.USER_SYSTEM),
1645 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001646 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001647 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001648
Makoto Onuki068c54a2015-10-13 14:34:03 -07001649 DpmTestUtils.assertRestrictions(
1650 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1651 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1652 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001653 DpmTestUtils.assertRestrictions(
1654 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1655 dpm.getUserRestrictions(admin1)
1656 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001657
1658 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001659 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001660 eq(UserHandle.USER_SYSTEM),
1661 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001662 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001663 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001664
Esteban Talavera548a04b2016-12-20 15:22:30 +00001665 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001666
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001667 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1668 // DO sets them, the scope is global.
1669 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001670 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001671 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001672 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001673 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001675 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1676 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001677 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001678
1679 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1680 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001681 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001682
1683 // More tests.
1684 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001685 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001687 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1688 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001689 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001690
1691 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001692 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001693 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001694 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001695 UserManager.DISALLOW_ADD_USER),
1696 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001697 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698
1699 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001700 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001701 eq(UserHandle.USER_SYSTEM),
1702 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001703 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001704 UserManager.DISALLOW_ADD_USER),
1705 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001706 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001707
1708 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1709 // locally.
1710 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001711 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001712
1713 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1714 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1715 dpm.setCameraDisabled(admin2, true);
1716
Pavel Grafov75c0a892017-05-18 17:28:27 +01001717 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001718 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001719 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001721 UserManager.DISALLOW_ADD_USER),
1722 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001723 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001724 // TODO Make sure restrictions are written to the file.
1725 }
1726
1727 public void testSetUserRestriction_asPo() {
1728 setAsProfileOwner(admin1);
1729
Makoto Onuki068c54a2015-10-13 14:34:03 -07001730 DpmTestUtils.assertRestrictions(
1731 DpmTestUtils.newRestrictions(),
1732 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1733 .ensureUserRestrictions()
1734 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001735
1736 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001737 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001738 eq(DpmMockContext.CALLER_USER_HANDLE),
1739 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001740 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001741 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001742
Makoto Onukia4f11972015-10-01 13:19:58 -07001743 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001744 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001745 eq(DpmMockContext.CALLER_USER_HANDLE),
1746 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1747 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001748 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001749 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001750
Makoto Onuki068c54a2015-10-13 14:34:03 -07001751 DpmTestUtils.assertRestrictions(
1752 DpmTestUtils.newRestrictions(
1753 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1754 UserManager.DISALLOW_OUTGOING_CALLS
1755 ),
1756 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1757 .ensureUserRestrictions()
1758 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001759 DpmTestUtils.assertRestrictions(
1760 DpmTestUtils.newRestrictions(
1761 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1762 UserManager.DISALLOW_OUTGOING_CALLS
1763 ),
1764 dpm.getUserRestrictions(admin1)
1765 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001766
1767 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001768 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001769 eq(DpmMockContext.CALLER_USER_HANDLE),
1770 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001771 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001772 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001773
1774 DpmTestUtils.assertRestrictions(
1775 DpmTestUtils.newRestrictions(
1776 UserManager.DISALLOW_OUTGOING_CALLS
1777 ),
1778 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1779 .ensureUserRestrictions()
1780 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001781 DpmTestUtils.assertRestrictions(
1782 DpmTestUtils.newRestrictions(
1783 UserManager.DISALLOW_OUTGOING_CALLS
1784 ),
1785 dpm.getUserRestrictions(admin1)
1786 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001787
1788 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001789 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001790 eq(DpmMockContext.CALLER_USER_HANDLE),
1791 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001792 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001793 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001794
Makoto Onuki068c54a2015-10-13 14:34:03 -07001795 DpmTestUtils.assertRestrictions(
1796 DpmTestUtils.newRestrictions(),
1797 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1798 .ensureUserRestrictions()
1799 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001800 DpmTestUtils.assertRestrictions(
1801 DpmTestUtils.newRestrictions(),
1802 dpm.getUserRestrictions(admin1)
1803 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001804
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001805 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1806 // though when DO sets them they'll be applied globally.
1807 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001808 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001809 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001810 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001811 eq(DpmMockContext.CALLER_USER_HANDLE),
1812 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1813 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001814 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001815 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001816
1817 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001818 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001819 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001820 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001821 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001822 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001823 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001824
Makoto Onukia4f11972015-10-01 13:19:58 -07001825 // TODO Make sure restrictions are written to the file.
1826 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001827
Esteban Talavera548a04b2016-12-20 15:22:30 +00001828
1829 public void testDefaultEnabledUserRestrictions() throws Exception {
1830 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1831 mContext.callerPermissions.add(permission.MANAGE_USERS);
1832 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1833 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1834
1835 // First, set DO.
1836
1837 // Call from a process on the system user.
1838 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1839
1840 // Make sure admin1 is installed on system user.
1841 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1842
1843 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1844 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1845 UserHandle.USER_SYSTEM));
1846
1847 // Check that the user restrictions that are enabled by default are set. Then unset them.
1848 String[] defaultRestrictions = UserRestrictionsUtils
1849 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1850 assertTrue(defaultRestrictions.length > 0);
1851 DpmTestUtils.assertRestrictions(
1852 DpmTestUtils.newRestrictions(defaultRestrictions),
1853 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1854 );
1855 DpmTestUtils.assertRestrictions(
1856 DpmTestUtils.newRestrictions(defaultRestrictions),
1857 dpm.getUserRestrictions(admin1)
1858 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001859 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001860 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001861 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001862 eq(true) /* isDeviceOwner */,
1863 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001864 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001865 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001866
1867 for (String restriction : defaultRestrictions) {
1868 dpm.clearUserRestriction(admin1, restriction);
1869 }
1870
1871 assertNoDeviceOwnerRestrictions();
1872
1873 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001874 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001875 initializeDpms();
1876 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1877 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1878
1879 assertNoDeviceOwnerRestrictions();
1880
1881 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1882 // is set as it wasn't enabled during setDeviceOwner.
1883 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1884 assertFalse(UserRestrictionsUtils
1885 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1886 UserRestrictionsUtils
1887 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1888 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001889 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001890 initializeDpms();
1891 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1892 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1893
1894 DpmTestUtils.assertRestrictions(
1895 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1896 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1897 );
1898 DpmTestUtils.assertRestrictions(
1899 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1900 dpm.getUserRestrictions(admin1)
1901 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001902 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001903 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001904 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001905 eq(true) /* isDeviceOwner */,
1906 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001907 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001908 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001909
1910 // Remove the restriction.
1911 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1912
1913 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1914 initializeDpms();
1915 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1916 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1917 assertNoDeviceOwnerRestrictions();
1918 } finally {
1919 UserRestrictionsUtils
1920 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1921 }
1922 }
1923
1924 private void assertNoDeviceOwnerRestrictions() {
1925 DpmTestUtils.assertRestrictions(
1926 DpmTestUtils.newRestrictions(),
1927 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1928 );
1929 DpmTestUtils.assertRestrictions(
1930 DpmTestUtils.newRestrictions(),
1931 dpm.getUserRestrictions(admin1)
1932 );
1933 }
1934
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001935 public void testGetMacAddress() throws Exception {
1936 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1937 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1938 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1939
1940 // In this test, change the caller user to "system".
1941 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1942
1943 // Make sure admin1 is installed on system user.
1944 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1945
1946 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001947 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1948 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001949
1950 // DO needs to be an DA.
1951 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1952 assertTrue(dpm.isAdminActive(admin1));
1953
1954 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001955 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1956 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001957
1958 // Test 3. Caller has PO, but not DO.
1959 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001960 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1961 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001962
1963 // Remove PO.
1964 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001965 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001966 // Test 4, Caller is DO now.
1967 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1968
1969 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001970 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001971
1972 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001973 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001974 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001975
1976 // 4-3. With a real MAC address.
1977 final WifiInfo wi = new WifiInfo();
1978 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001979 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001980 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001981 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001982
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001983 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001984 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1985 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1986
1987 // In this test, change the caller user to "system".
1988 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1989
1990 // Make sure admin1 is installed on system user.
1991 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1992
1993 // Set admin1 as DA.
1994 dpm.setActiveAdmin(admin1, false);
1995 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001996 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1997 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001998
1999 // Set admin1 as PO.
2000 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002001 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2002 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002003
2004 // Remove PO and add DO.
2005 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002006 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002007 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2008
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002009 // admin1 is DO.
2010 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002011 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002012 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002013 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2014 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002015
2016 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002017 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002018 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002019 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2020 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002021
2022 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002023 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002024 dpm.reboot(admin1);
2025 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002026
2027 public void testSetGetSupportText() {
2028 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2029 dpm.setActiveAdmin(admin1, true);
2030 dpm.setActiveAdmin(admin2, true);
2031 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2032
2033 // Null default support messages.
2034 {
2035 assertNull(dpm.getLongSupportMessage(admin1));
2036 assertNull(dpm.getShortSupportMessage(admin1));
2037 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2038 assertNull(dpm.getShortSupportMessageForUser(admin1,
2039 DpmMockContext.CALLER_USER_HANDLE));
2040 assertNull(dpm.getLongSupportMessageForUser(admin1,
2041 DpmMockContext.CALLER_USER_HANDLE));
2042 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2043 }
2044
2045 // Only system can call the per user versions.
2046 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002047 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2048 () -> dpm.getShortSupportMessageForUser(admin1,
2049 DpmMockContext.CALLER_USER_HANDLE));
2050 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2051 () -> dpm.getLongSupportMessageForUser(admin1,
2052 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002053 }
2054
2055 // Can't set message for admin in another uid.
2056 {
2057 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002058 assertExpectException(SecurityException.class,
2059 /* messageRegex= */ "is not owned by uid",
2060 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002061 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2062 }
2063
2064 // Set/Get short returns what it sets and other admins text isn't changed.
2065 {
2066 final String supportText = "Some text to test with.";
2067 dpm.setShortSupportMessage(admin1, supportText);
2068 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2069 assertNull(dpm.getLongSupportMessage(admin1));
2070 assertNull(dpm.getShortSupportMessage(admin2));
2071
2072 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2073 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2074 DpmMockContext.CALLER_USER_HANDLE));
2075 assertNull(dpm.getShortSupportMessageForUser(admin2,
2076 DpmMockContext.CALLER_USER_HANDLE));
2077 assertNull(dpm.getLongSupportMessageForUser(admin1,
2078 DpmMockContext.CALLER_USER_HANDLE));
2079 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2080
2081 dpm.setShortSupportMessage(admin1, null);
2082 assertNull(dpm.getShortSupportMessage(admin1));
2083 }
2084
2085 // Set/Get long returns what it sets and other admins text isn't changed.
2086 {
2087 final String supportText = "Some text to test with.\nWith more text.";
2088 dpm.setLongSupportMessage(admin1, supportText);
2089 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2090 assertNull(dpm.getShortSupportMessage(admin1));
2091 assertNull(dpm.getLongSupportMessage(admin2));
2092
2093 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2094 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2095 DpmMockContext.CALLER_USER_HANDLE));
2096 assertNull(dpm.getLongSupportMessageForUser(admin2,
2097 DpmMockContext.CALLER_USER_HANDLE));
2098 assertNull(dpm.getShortSupportMessageForUser(admin1,
2099 DpmMockContext.CALLER_USER_HANDLE));
2100 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2101
2102 dpm.setLongSupportMessage(admin1, null);
2103 assertNull(dpm.getLongSupportMessage(admin1));
2104 }
2105 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002106
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002107 public void testSetGetMeteredDataDisabled() throws Exception {
2108 setAsProfileOwner(admin1);
2109
2110 final ArrayList<String> emptyList = new ArrayList<>();
2111 assertEquals(emptyList, dpm.getMeteredDataDisabled(admin1));
2112
2113 // Setup
2114 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2115 final String package1 = "com.example.one";
2116 final String package2 = "com.example.two";
2117 pkgsToRestrict.add(package1);
2118 pkgsToRestrict.add(package2);
2119 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2120 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
2121 List<String> excludedPkgs = dpm.setMeteredDataDisabled(admin1, pkgsToRestrict);
2122
2123 // Verify
2124 assertEquals(emptyList, excludedPkgs);
2125 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabled(admin1));
2126 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2127 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2128 eq(DpmMockContext.CALLER_USER_HANDLE));
2129
2130 // Setup
2131 pkgsToRestrict.remove(package1);
2132 excludedPkgs = dpm.setMeteredDataDisabled(admin1, pkgsToRestrict);
2133
2134 // Verify
2135 assertEquals(emptyList, excludedPkgs);
2136 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabled(admin1));
2137 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2138 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2139 eq(DpmMockContext.CALLER_USER_HANDLE));
2140 }
2141
2142 public void testSetGetMeteredDataDisabled_deviceAdmin() {
2143 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2144 dpm.setActiveAdmin(admin1, true);
2145 assertTrue(dpm.isAdminActive(admin1));
2146 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2147
2148 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
2149 () -> dpm.setMeteredDataDisabled(admin1, new ArrayList<>()));
2150 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
2151 () -> dpm.getMeteredDataDisabled(admin1));
2152 }
2153
phweiss73145f42017-01-17 19:06:38 +01002154 public void testCreateAdminSupportIntent() throws Exception {
2155 // Setup device owner.
2156 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2157 setupDeviceOwner();
2158
2159 // Nonexisting permission returns null
2160 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2161 assertNull(intent);
2162
2163 // Existing permission that is not set returns null
2164 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2165 assertNull(intent);
2166
2167 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002168 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002169 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2170 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2171 .thenReturn(true);
2172 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2173 assertNull(intent);
2174
2175 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002176 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002177 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2178 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2179 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2180 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2181 assertNotNull(intent);
2182 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2183 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2184 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002185 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002186 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2187 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2188
Lenka Trochtova16a91c02018-01-17 11:03:30 +01002189 // Try with POLICY_DISABLE_CAMERA, POLICY_DISABLE_SCREEN_CAPTURE and
2190 // POLICY_MANDATORY_BACKUPS, which are not user restrictions
phweiss73145f42017-01-17 19:06:38 +01002191
2192 // Camera is not disabled
2193 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2194 assertNull(intent);
2195
2196 // Camera is disabled
2197 dpm.setCameraDisabled(admin1, true);
2198 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2199 assertNotNull(intent);
2200 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2201 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2202
2203 // Screen capture is not disabled
2204 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2205 assertNull(intent);
2206
2207 // Screen capture is disabled
2208 dpm.setScreenCaptureDisabled(admin1, true);
2209 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2210 assertNotNull(intent);
2211 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2212 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2213
Lenka Trochtova16a91c02018-01-17 11:03:30 +01002214 // Backups are not mandatory
2215 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_MANDATORY_BACKUPS);
2216 assertNull(intent);
2217
2218 // Backups are mandatory
2219 ComponentName transportComponent = ComponentName.unflattenFromString(
2220 "android/com.android.internal.backup.LocalTransport");
2221 dpm.setMandatoryBackupTransport(admin1, transportComponent);
2222 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_MANDATORY_BACKUPS);
2223 assertNotNull(intent);
2224 assertEquals(DevicePolicyManager.POLICY_MANDATORY_BACKUPS,
2225 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2226
phweiss73145f42017-01-17 19:06:38 +01002227 // Same checks for different user
2228 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2229 // Camera should be disabled by device owner
2230 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2231 assertNotNull(intent);
2232 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2233 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2234 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2235 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2236 // ScreenCapture should not be disabled by device owner
2237 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2238 assertNull(intent);
2239 }
2240
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002241 /**
2242 * Test for:
2243 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002244 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002245 * {@link DevicePolicyManager#isAffiliatedUser}
2246 */
2247 public void testUserAffiliation() throws Exception {
2248 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2249 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2250 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2251
2252 // Check that the system user is unaffiliated.
2253 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2254 assertFalse(dpm.isAffiliatedUser());
2255
2256 // Set a device owner on the system user. Check that the system user becomes affiliated.
2257 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2258 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2259 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2260 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002261 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002262
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002263 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002264 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2265 setAsProfileOwner(admin2);
2266 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002267 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002268
2269 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2270 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002271 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002272 userAffiliationIds.add("red");
2273 userAffiliationIds.add("green");
2274 userAffiliationIds.add("blue");
2275 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002276 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002277 assertFalse(dpm.isAffiliatedUser());
2278
2279 // Have the device owner specify a set of affiliation ids that do not intersect with those
2280 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002281 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002282 deviceAffiliationIds.add("cyan");
2283 deviceAffiliationIds.add("yellow");
2284 deviceAffiliationIds.add("magenta");
2285 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2286 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002287 MoreAsserts.assertContentsInAnyOrder(
2288 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002289 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2290 assertFalse(dpm.isAffiliatedUser());
2291
2292 // Have the profile owner specify a set of affiliation ids that intersect with those
2293 // specified by the device owner. Check that the test user becomes affiliated.
2294 userAffiliationIds.add("yellow");
2295 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002296 MoreAsserts.assertContentsInAnyOrder(
2297 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002298 assertTrue(dpm.isAffiliatedUser());
2299
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002300 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002301 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002302 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002303 assertFalse(dpm.isAffiliatedUser());
2304
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002305 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2306 dpm.setAffiliationIds(admin2, userAffiliationIds);
2307 assertTrue(dpm.isAffiliatedUser());
2308 dpm.clearProfileOwner(admin2);
2309 assertFalse(dpm.isAffiliatedUser());
2310
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002311 // Check that the system user remains affiliated.
2312 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2313 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002314
2315 // Clear the device owner - the user becomes unaffiliated.
2316 clearDeviceOwner();
2317 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002318 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002319
2320 public void testGetUserProvisioningState_defaultResult() {
2321 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2322 }
2323
2324 public void testSetUserProvisioningState_permission() throws Exception {
2325 setupProfileOwner();
2326 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2327
2328 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2329 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2330 }
2331
2332 public void testSetUserProvisioningState_unprivileged() throws Exception {
2333 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002334 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2335 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2336 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002337 }
2338
2339 public void testSetUserProvisioningState_noManagement() {
2340 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002341 assertExpectException(IllegalStateException.class,
2342 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2343 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2344 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002345 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2346 }
2347
2348 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2349 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2350 setupDeviceOwner();
2351 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2352
2353 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2354 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2355 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2356 }
2357
2358 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2359 throws Exception {
2360 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2361 setupDeviceOwner();
2362 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2363
2364 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2365 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2366 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2367 }
2368
2369 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2370 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2371 setupDeviceOwner();
2372 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2373
2374 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2375 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2376 }
2377
2378 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2379 throws Exception {
2380 setupProfileOwner();
2381 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2382
2383 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2384 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2385 DevicePolicyManager.STATE_USER_UNMANAGED);
2386 }
2387
2388 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2389 throws Exception {
2390 setupProfileOwner();
2391 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2392
2393 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2394 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2395 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2396 }
2397
2398 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2399 setupProfileOwner();
2400 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2401
2402 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2403 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2404 }
2405
2406 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2407 setupProfileOwner();
2408 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2409
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002410 assertExpectException(IllegalStateException.class,
2411 /* messageRegex= */ "Cannot move to user provisioning state",
2412 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2413 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2414 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002415 }
2416
2417 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2418 throws Exception {
2419 setupProfileOwner();
2420 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2421
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002422 assertExpectException(IllegalStateException.class,
2423 /* messageRegex= */ "Cannot move to user provisioning state",
2424 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2425 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2426 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002427 }
2428
2429 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2430 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2431 for (int state : states) {
2432 dpm.setUserProvisioningState(state, userId);
2433 assertEquals(state, dpm.getUserProvisioningState());
2434 }
2435 }
2436
2437 private void setupProfileOwner() throws Exception {
2438 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2439
2440 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2441 dpm.setActiveAdmin(admin1, false);
2442 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2443
2444 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2445 }
2446
2447 private void setupDeviceOwner() throws Exception {
2448 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2449
2450 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2451 dpm.setActiveAdmin(admin1, false);
2452 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2453
2454 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2455 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002456
2457 public void testSetMaximumTimeToLock() {
2458 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2459
2460 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2461 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2462
Pavel Grafov75c0a892017-05-18 17:28:27 +01002463 reset(getServices().powerManagerInternal);
2464 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002465
2466 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002467 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2468 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002469 reset(getServices().powerManagerInternal);
2470 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002471
2472 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002473 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2474 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002475 reset(getServices().powerManagerInternal);
2476 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002477
2478 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002479 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2480 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002481 reset(getServices().powerManagerInternal);
2482 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002483
2484 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002485 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2486 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002487 reset(getServices().powerManagerInternal);
2488 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002489
2490 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002491 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2492 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002493 reset(getServices().powerManagerInternal);
2494 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002495
2496 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002497 reset(getServices().powerManagerInternal);
2498 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002499
Pavel Grafov28939982017-10-03 15:11:52 +01002500 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2501 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2502 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002503 reset(getServices().powerManagerInternal);
2504 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002505
2506 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002507 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2508 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002509 reset(getServices().powerManagerInternal);
2510 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002511
Pavel Grafov28939982017-10-03 15:11:52 +01002512 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002513 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002514 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2515 verifyStayOnWhilePluggedCleared(false);
2516 }
2517
2518 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2519 // uses separate challenge.
2520 public void testSetMaximumTimeToLockProfile() throws Exception {
2521 final int PROFILE_USER = 15;
2522 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2523 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2524 mContext.binder.callingUid = PROFILE_ADMIN;
2525 final DevicePolicyManagerInternal dpmi =
2526 LocalServices.getService(DevicePolicyManagerInternal.class);
2527
2528 dpm.setMaximumTimeToLock(admin1, 0);
2529
2530 reset(getServices().powerManagerInternal);
2531 reset(getServices().settings);
2532
2533 // First add timeout for the profile.
2534 dpm.setMaximumTimeToLock(admin1, 10);
2535 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2536
2537 reset(getServices().powerManagerInternal);
2538 reset(getServices().settings);
2539
2540 // Add separate challenge
2541 when(getServices().lockPatternUtils
2542 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2543 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2544
2545 verifyScreenTimeoutCall(10L, PROFILE_USER);
2546 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2547
2548 reset(getServices().powerManagerInternal);
2549 reset(getServices().settings);
2550
2551 // Remove the timeout.
2552 dpm.setMaximumTimeToLock(admin1, 0);
2553 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2554 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2555
2556 reset(getServices().powerManagerInternal);
2557 reset(getServices().settings);
2558
2559 // Add it back.
2560 dpm.setMaximumTimeToLock(admin1, 10);
2561 verifyScreenTimeoutCall(10L, PROFILE_USER);
2562 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2563
2564 reset(getServices().powerManagerInternal);
2565 reset(getServices().settings);
2566
2567 // Remove separate challenge.
2568 reset(getServices().lockPatternUtils);
2569 when(getServices().lockPatternUtils
2570 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2571 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2572
2573 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2574 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2575
2576 reset(getServices().powerManagerInternal);
2577 reset(getServices().settings);
2578
2579 // Remove the timeout.
2580 dpm.setMaximumTimeToLock(admin1, 0);
2581 verifyScreenTimeoutCall(null, PROFILE_USER);
2582 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002583 }
2584
Michal Karpinski943aabd2016-10-06 11:09:25 +01002585 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2586 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2587 setupDeviceOwner();
2588 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2589
Michal Karpinskid084ca52017-01-18 15:54:18 +00002590 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2591 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2592 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2593 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2594 - ONE_MINUTE;
2595
2596 // verify that the minimum timeout cannot be modified on user builds (system property is
2597 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002598 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002599
2600 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2601 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2602 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2603
Pavel Grafov75c0a892017-05-18 17:28:27 +01002604 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002605
2606 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002607 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002608
Michal Karpinskid084ca52017-01-18 15:54:18 +00002609 // reset to default (0 means the admin is not participating, so default should be returned)
2610 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002611
2612 // aggregation should be the default if unset by any admin
2613 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2614 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2615
2616 // admin not participating by default
2617 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2618
2619 //clamping from the top
2620 dpm.setRequiredStrongAuthTimeout(admin1,
2621 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2622 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2623 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2624 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2625 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2626
Michal Karpinskid084ca52017-01-18 15:54:18 +00002627 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002628 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2629 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2630 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2631 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2632
2633 // clamping from the bottom
2634 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2635 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2636 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2637
Michal Karpinskid084ca52017-01-18 15:54:18 +00002638 // values within range
2639 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2640 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2641 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2642
2643 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2644 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2645 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002646
2647 // reset to default
2648 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2649 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2650 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2651 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2652
2653 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002654 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2655 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002656 }
2657
Pavel Grafov28939982017-10-03 15:11:52 +01002658 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002659 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002660 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002661 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002662 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002663 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002664 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002665 }
Pavel Grafov28939982017-10-03 15:11:52 +01002666 }
2667
2668 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002669 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2670 // UnfinishedVerificationException.
2671 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002672
Esteban Talavera01576862016-12-15 11:16:44 +00002673 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002674 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002675 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002676 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002677 .thenReturn(false);
2678 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002679 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2680 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002681 .thenReturn(true);
2682 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2683
2684 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002685 }
Victor Chang3e794af2016-03-04 13:48:17 +00002686
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002687 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2688 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002689 mContext.packageName = admin1.getPackageName();
2690 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002691 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2692 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2693 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2694 false);
2695 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2696 }
2697
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002698 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2699 setup_DeviceAdminFeatureOff();
2700 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2701 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2702 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2703 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2704 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2705 assertCheckProvisioningPreCondition(
2706 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2707 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2708 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2709 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2710 }
2711
Esteban Talavera01576862016-12-15 11:16:44 +00002712 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002713 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002714 .thenReturn(false);
2715 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002716 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2717 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002718 .thenReturn(true);
2719 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2720
2721 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002722 }
Victor Chang3e794af2016-03-04 13:48:17 +00002723
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002724 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2725 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002726 mContext.packageName = admin1.getPackageName();
2727 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002728 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2729 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2730 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2731 false);
2732 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2733
2734 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002735 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002736 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2737 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2738 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2739 true);
2740 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2741 }
2742
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002743 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2744 setup_ManagedProfileFeatureOff();
2745 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2746 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2747 DevicePolicyManager.CODE_OK);
2748 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2749 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2750 assertCheckProvisioningPreCondition(
2751 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2752 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2753 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2754 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2755
2756 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002757 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002758 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2759 DevicePolicyManager.CODE_OK);
2760 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2761 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2762 assertCheckProvisioningPreCondition(
2763 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2764 DevicePolicyManager.CODE_OK);
2765 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2766 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2767 }
2768
Esteban Talavera01576862016-12-15 11:16:44 +00002769 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002770 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002771 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002772 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2773 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002774 .thenReturn(true);
2775 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2776
2777 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002778 }
Victor Chang3e794af2016-03-04 13:48:17 +00002779
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002780 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2781 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002782 mContext.packageName = admin1.getPackageName();
2783 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002784 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2786 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2787 false /* because of non-split user */);
2788 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2789 false /* because of non-split user */);
2790 }
2791
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002792 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002793 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002794 setup_nonSplitUser_firstBoot_primaryUser();
2795 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2796 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2797 DevicePolicyManager.CODE_OK);
2798 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2799 DevicePolicyManager.CODE_OK);
2800 assertCheckProvisioningPreCondition(
2801 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2802 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2803 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2804 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2805 }
2806
Esteban Talavera01576862016-12-15 11:16:44 +00002807 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002808 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002809 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002810 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2811 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002812 .thenReturn(true);
2813 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2814
2815 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002816 }
Victor Chang3e794af2016-03-04 13:48:17 +00002817
Nicolas Prevot45d29072017-01-18 16:11:19 +00002818 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2819 setDeviceOwner();
2820 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2821 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2822 }
2823
2824 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2825 setup_nonSplitUser_withDo_primaryUser();
2826 final int MANAGED_PROFILE_USER_ID = 18;
2827 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2828 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002829 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002830 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002831 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002832 true)).thenReturn(true);
2833 }
2834
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002835 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2836 throws Exception {
2837 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002838 mContext.packageName = admin1.getPackageName();
2839 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002840 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2841 false/* because of completed device setup */);
2842 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2843 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2844 false/* because of non-split user */);
2845 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2846 false/* because of non-split user */);
2847 }
2848
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002849 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2850 throws Exception {
2851 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2852 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2853 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2854 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2855 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2856 DevicePolicyManager.CODE_OK);
2857 assertCheckProvisioningPreCondition(
2858 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2859 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2860 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2861 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2862 }
2863
Nicolas Prevot45d29072017-01-18 16:11:19 +00002864 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2865 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002866 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002867 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2868
2869 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2870 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002871 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002872
2873 // COMP mode is allowed.
2874 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2875 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002876 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002877
Nicolas Prevot45d29072017-01-18 16:11:19 +00002878 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002879 assertCheckProvisioningPreCondition(
2880 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002881 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002882 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002883 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2884 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2885 }
Esteban Talavera01576862016-12-15 11:16:44 +00002886
Nicolas Prevot45d29072017-01-18 16:11:19 +00002887 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2888 setup_nonSplitUser_withDo_primaryUser();
2889 mContext.packageName = admin1.getPackageName();
2890 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2891 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2892 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002893 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002894 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2895 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2896 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002897 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002898 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2899 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2900 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2901 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2902 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002903 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002904 assertCheckProvisioningPreCondition(
2905 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002906 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002907 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002908 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2909 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2910 }
Esteban Talavera01576862016-12-15 11:16:44 +00002911
Nicolas Prevot45d29072017-01-18 16:11:19 +00002912 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2913 throws Exception {
2914 setup_nonSplitUser_withDo_primaryUser();
2915 mContext.packageName = admin1.getPackageName();
2916 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002917 // The DO should not be allowed to initiate provisioning if the restriction is set by
2918 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002919 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002920 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2921 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2922 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002923 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002924 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2925 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2926 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2927 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2928 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002929 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2930
2931 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002932 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002933 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002934 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002935 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2936 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2937 }
2938
2939 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2940 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2941 mContext.packageName = admin1.getPackageName();
2942 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2943
2944 // We can delete the managed profile to create a new one, so provisioning is allowed.
2945 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2946 DevicePolicyManager.CODE_OK);
2947 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2948 assertCheckProvisioningPreCondition(
2949 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2950 DpmMockContext.ANOTHER_PACKAGE_NAME,
2951 DevicePolicyManager.CODE_OK);
2952 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2953 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2954 }
2955
2956 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2957 throws Exception {
2958 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2959 mContext.packageName = admin1.getPackageName();
2960 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002961 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002962 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2963 eq(UserHandle.SYSTEM)))
2964 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002965 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002966 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2967 eq(UserHandle.SYSTEM)))
2968 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002969
2970 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002971 assertCheckProvisioningPreCondition(
2972 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2973 DpmMockContext.ANOTHER_PACKAGE_NAME,
2974 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2975 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2976 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002977
2978 // But the device owner can still do it because it has set the restriction itself.
2979 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2980 DevicePolicyManager.CODE_OK);
2981 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002982 }
2983
2984 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002985 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002986 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002987 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2988 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002989 .thenReturn(false);
2990 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2991
2992 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002993 }
Victor Chang3e794af2016-03-04 13:48:17 +00002994
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002995 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2996 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002997 mContext.packageName = admin1.getPackageName();
2998 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002999 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3000 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3001 false /* because canAddMoreManagedProfiles returns false */);
3002 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3003 true);
3004 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3005 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003006 }
3007
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003008 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3009 throws Exception {
3010 setup_splitUser_firstBoot_systemUser();
3011 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3012 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3013 DevicePolicyManager.CODE_OK);
3014 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003015 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003016 assertCheckProvisioningPreCondition(
3017 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3018 DevicePolicyManager.CODE_OK);
3019 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3020 DevicePolicyManager.CODE_SYSTEM_USER);
3021 }
3022
Esteban Talavera01576862016-12-15 11:16:44 +00003023 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003024 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003025 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003026 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3027 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003028 .thenReturn(false);
3029 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3030
3031 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003032 }
Victor Chang3e794af2016-03-04 13:48:17 +00003033
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003034 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3035 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003036 mContext.packageName = admin1.getPackageName();
3037 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003038 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3039 true/* it's undefined behavior. Can be changed into false in the future */);
3040 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3041 false /* because canAddMoreManagedProfiles returns false */);
3042 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3043 true/* it's undefined behavior. Can be changed into false in the future */);
3044 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3045 false/* because calling uid is system user */);
3046 }
3047
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003048 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3049 throws Exception {
3050 setup_splitUser_afterDeviceSetup_systemUser();
3051 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3052 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3053 DevicePolicyManager.CODE_OK);
3054 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003055 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003056 assertCheckProvisioningPreCondition(
3057 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3058 DevicePolicyManager.CODE_OK);
3059 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3060 DevicePolicyManager.CODE_SYSTEM_USER);
3061 }
3062
Esteban Talavera01576862016-12-15 11:16:44 +00003063 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003064 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003065 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003066 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3067 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003068 true)).thenReturn(true);
3069 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3070
3071 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003072 }
Victor Chang3e794af2016-03-04 13:48:17 +00003073
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003074 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3075 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003076 mContext.packageName = admin1.getPackageName();
3077 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003078 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3079 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3080 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3081 true);
3082 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003083 }
3084
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003085 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003086 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003087 setup_splitUser_firstBoot_primaryUser();
3088 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3089 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3090 DevicePolicyManager.CODE_OK);
3091 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3092 DevicePolicyManager.CODE_OK);
3093 assertCheckProvisioningPreCondition(
3094 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3095 DevicePolicyManager.CODE_OK);
3096 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3097 DevicePolicyManager.CODE_OK);
3098 }
3099
Esteban Talavera01576862016-12-15 11:16:44 +00003100 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003101 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003102 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003103 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3104 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003105 true)).thenReturn(true);
3106 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3107
3108 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003109 }
Victor Chang3e794af2016-03-04 13:48:17 +00003110
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003111 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3112 throws Exception {
3113 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003114 mContext.packageName = admin1.getPackageName();
3115 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003116 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3117 true/* it's undefined behavior. Can be changed into false in the future */);
3118 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3119 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3120 true/* it's undefined behavior. Can be changed into false in the future */);
3121 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3122 false/* because user setup completed */);
3123 }
3124
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003125 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003126 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003127 setup_splitUser_afterDeviceSetup_primaryUser();
3128 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3129 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3130 DevicePolicyManager.CODE_OK);
3131 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3132 DevicePolicyManager.CODE_OK);
3133 assertCheckProvisioningPreCondition(
3134 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3135 DevicePolicyManager.CODE_OK);
3136 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3137 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3138 }
3139
Esteban Talavera01576862016-12-15 11:16:44 +00003140 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003141 setDeviceOwner();
3142
Pavel Grafov75c0a892017-05-18 17:28:27 +01003143 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003144 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003145 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3146 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003147 .thenReturn(false);
3148 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3149
3150 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003151 }
Victor Chang3e794af2016-03-04 13:48:17 +00003152
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003153 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3154 throws Exception {
3155 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003156 mContext.packageName = admin1.getPackageName();
3157 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003158 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3159 false /* can't provision managed profile on system user */);
3160 }
3161
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003162 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003163 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003164 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3165 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3166 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3167 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3168 }
3169
3170 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003171 setDeviceOwner();
3172
Pavel Grafov75c0a892017-05-18 17:28:27 +01003173 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003174 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003175 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3176 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003177 true)).thenReturn(true);
3178 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3179
3180 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003181 }
Victor Chang3e794af2016-03-04 13:48:17 +00003182
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003183 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3184 throws Exception {
3185 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003186 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3187 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003188 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3189 }
3190
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003191 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003192 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003193 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3194 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003195
3196 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003197 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3198 DevicePolicyManager.CODE_OK);
3199 }
3200
3201 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003202 setDeviceOwner();
3203
Pavel Grafov75c0a892017-05-18 17:28:27 +01003204 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003205 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003206 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3207 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003208 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3209 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003210 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003211 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003212 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003213 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003214 true)).thenReturn(true);
3215 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3216
3217 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003218 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003219
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003220 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3221 throws Exception {
3222 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003223 mContext.packageName = admin1.getPackageName();
3224 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003225 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3226 }
3227
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003228 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3229 throws Exception {
3230 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3231 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3232 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3233 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3234 }
3235
3236 public void testCheckProvisioningPreCondition_permission() {
3237 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003238 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3239 () -> dpm.checkProvisioningPreCondition(
3240 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003241 }
3242
Victor Chang3577ed22016-08-25 18:49:26 +01003243 public void testForceUpdateUserSetupComplete_permission() {
3244 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003245 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3246 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003247 }
3248
3249 public void testForceUpdateUserSetupComplete_systemUser() {
3250 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3251 // GIVEN calling from user 20
3252 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003253 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3254 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003255 }
3256
3257 public void testForceUpdateUserSetupComplete_userbuild() {
3258 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3259 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3260
3261 final int userId = UserHandle.USER_SYSTEM;
3262 // GIVEN userComplete is false in SettingsProvider
3263 setUserSetupCompleteForUser(false, userId);
3264
3265 // GIVEN userComplete is true in DPM
3266 DevicePolicyManagerService.DevicePolicyData userData =
3267 new DevicePolicyManagerService.DevicePolicyData(userId);
3268 userData.mUserSetupComplete = true;
3269 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3270
3271 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003272 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003273
3274 assertTrue(dpms.hasUserSetupCompleted());
3275
3276 dpm.forceUpdateUserSetupComplete();
3277
3278 // THEN the state in dpms is not changed
3279 assertTrue(dpms.hasUserSetupCompleted());
3280 }
3281
3282 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3283 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3284 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3285
3286 final int userId = UserHandle.USER_SYSTEM;
3287 // GIVEN userComplete is false in SettingsProvider
3288 setUserSetupCompleteForUser(false, userId);
3289
3290 // GIVEN userComplete is true in DPM
3291 DevicePolicyManagerService.DevicePolicyData userData =
3292 new DevicePolicyManagerService.DevicePolicyData(userId);
3293 userData.mUserSetupComplete = true;
3294 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3295
3296 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003297 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003298
3299 assertTrue(dpms.hasUserSetupCompleted());
3300
3301 dpm.forceUpdateUserSetupComplete();
3302
3303 // THEN the state in dpms is not changed
3304 assertFalse(dpms.hasUserSetupCompleted());
3305 }
3306
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003307 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003308 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003309 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003310
3311 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3312 runAsCaller(mAdmin1Context, dpms, dpm -> {
3313 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3314 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003315 }
3316
3317 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3318 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3319 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003320
3321 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3322 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003323 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003324 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3325 .thenReturn(true);
3326
3327 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003328 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003329
3330 // Enabling logging should not change the timestamp.
3331 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003332 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003333 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003334 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003335 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003336 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003337
3338 // Retrieving the logs should update the timestamp.
3339 final long beforeRetrieval = System.currentTimeMillis();
3340 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003341 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003342 final long afterRetrieval = System.currentTimeMillis();
3343 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3344 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3345
3346 // Retrieving the pre-boot logs should update the timestamp.
3347 Thread.sleep(2);
3348 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003349 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003350 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3351
3352 // Checking the timestamp again should not change it.
3353 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003354 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003355
3356 // Retrieving the logs again should update the timestamp.
3357 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003358 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003359 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3360
3361 // Disabling logging should not change the timestamp.
3362 Thread.sleep(2);
3363 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003364 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003365
3366 // Restarting the DPMS should not lose the timestamp.
3367 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003368 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003369
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003370 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3371 mContext.binder.callingUid = 1234567;
3372 mContext.callerPermissions.add(permission.MANAGE_USERS);
3373 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3374 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3375
3376 // System can retrieve the timestamp.
3377 mContext.binder.clearCallingIdentity();
3378 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3379
3380 // Removing the device owner should clear the timestamp.
3381 clearDeviceOwner();
3382 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003383 }
3384
yuemingw0de748d2017-11-15 19:22:27 +00003385 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3386 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3387 setupDeviceOwner();
3388 assertExpectException(SecurityException.class, null, () ->
3389 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3390 }
3391
3392 public void testSetSystemSettingFailWithPO() throws Exception {
3393 setupProfileOwner();
3394 assertExpectException(SecurityException.class, null, () ->
3395 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"));
3396 }
3397
3398 public void testSetSystemSetting() throws Exception {
3399 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3400 setupDeviceOwner();
3401 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3402 verify(getServices().settings).settingsSystemPutString(
3403 Settings.System.SCREEN_BRIGHTNESS, "0");
3404 }
3405
yuemingwe43cdf72017-10-12 16:52:11 +01003406 public void testSetTime() throws Exception {
3407 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3408 setupDeviceOwner();
3409 dpm.setTime(admin1, 0);
3410 verify(getServices().alarmManager).setTime(0);
3411 }
3412
3413 public void testSetTimeFailWithPO() throws Exception {
3414 setupProfileOwner();
3415 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3416 }
3417
3418 public void testSetTimeWithAutoTimeOn() throws Exception {
3419 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3420 setupDeviceOwner();
3421 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3422 .thenReturn(1);
3423 assertFalse(dpm.setTime(admin1, 0));
3424 }
3425
3426 public void testSetTimeZone() throws Exception {
3427 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3428 setupDeviceOwner();
3429 dpm.setTimeZone(admin1, "Asia/Shanghai");
3430 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3431 }
3432
3433 public void testSetTimeZoneFailWithPO() throws Exception {
3434 setupProfileOwner();
3435 assertExpectException(SecurityException.class, null,
3436 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3437 }
3438
3439 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3440 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3441 setupDeviceOwner();
3442 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3443 .thenReturn(1);
3444 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3445 }
3446
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003447 public void testGetLastBugReportRequestTime() throws Exception {
3448 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3449 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003450
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003451 mContext.packageName = admin1.getPackageName();
3452 mContext.applicationInfo = new ApplicationInfo();
3453 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3454 .thenReturn(Color.WHITE);
3455 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3456 anyObject())).thenReturn(Color.WHITE);
3457
Esteban Talaverad36dd152016-12-15 08:51:45 +00003458 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3459 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003460 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003461
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003462 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003463 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003464
3465 // Requesting a bug report should update the timestamp.
3466 final long beforeRequest = System.currentTimeMillis();
3467 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003468 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003469 final long afterRequest = System.currentTimeMillis();
3470 assertTrue(bugReportRequestTime >= beforeRequest);
3471 assertTrue(bugReportRequestTime <= afterRequest);
3472
3473 // Checking the timestamp again should not change it.
3474 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003475 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003476
3477 // Restarting the DPMS should not lose the timestamp.
3478 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003479 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003480
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003481 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3482 mContext.binder.callingUid = 1234567;
3483 mContext.callerPermissions.add(permission.MANAGE_USERS);
3484 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3485 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3486
3487 // System can retrieve the timestamp.
3488 mContext.binder.clearCallingIdentity();
3489 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3490
3491 // Removing the device owner should clear the timestamp.
3492 clearDeviceOwner();
3493 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003494 }
3495
3496 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3497 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3498 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003499 mContext.packageName = admin1.getPackageName();
3500 mContext.applicationInfo = new ApplicationInfo();
3501 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3502 .thenReturn(Color.WHITE);
3503 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3504 anyObject())).thenReturn(Color.WHITE);
3505
3506 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3507 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003508 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003509 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003510 .thenReturn(true);
3511
3512 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003513 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003514
3515 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3516 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003517 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003518
3519 // Enabling logging should not change the timestamp.
3520 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003521 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003522
3523 // Retrieving the logs should update the timestamp.
3524 final long beforeRetrieval = System.currentTimeMillis();
3525 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003526 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003527 final long afterRetrieval = System.currentTimeMillis();
3528 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3529 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3530
3531 // Checking the timestamp again should not change it.
3532 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003533 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003534
3535 // Retrieving the logs again should update the timestamp.
3536 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003537 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003538 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3539
3540 // Disabling logging should not change the timestamp.
3541 Thread.sleep(2);
3542 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003543 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003544
3545 // Restarting the DPMS should not lose the timestamp.
3546 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003547 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3548
3549 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3550 mContext.binder.callingUid = 1234567;
3551 mContext.callerPermissions.add(permission.MANAGE_USERS);
3552 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3553 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3554
3555 // System can retrieve the timestamp.
3556 mContext.binder.clearCallingIdentity();
3557 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3558
3559 // Removing the device owner should clear the timestamp.
3560 clearDeviceOwner();
3561 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003562 }
3563
Tony Mak2f26b792016-11-28 17:54:51 +00003564 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3565 // Setup device owner.
3566 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3567 setupDeviceOwner();
3568
3569 // Only device owner is setup, the result list should be empty.
3570 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3571 MoreAsserts.assertEmpty(targetUsers);
3572
3573 // Setup a managed profile managed by the same admin.
3574 final int MANAGED_PROFILE_USER_ID = 15;
3575 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3576 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3577
3578 // Add a secondary user, it should never talk with.
3579 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003580 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003581
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003582 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3583 // other.
3584 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3585 MoreAsserts.assertEmpty(targetUsers);
3586
3587 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3588 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3589 MoreAsserts.assertEmpty(targetUsers);
3590
3591 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003592 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003593 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3594 dpm.setAffiliationIds(admin1, userAffiliationIds);
3595
3596 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3597 dpm.setAffiliationIds(admin1, userAffiliationIds);
3598
Tony Mak2f26b792016-11-28 17:54:51 +00003599 // Calling from device owner admin, the result list should just contain the managed
3600 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003601 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003602 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3603 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3604
3605 // Calling from managed profile admin, the result list should just contain the system
3606 // user id.
3607 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3608 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3609 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003610
3611 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003612 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003613
3614 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3615 // to each other.
3616 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3617 MoreAsserts.assertEmpty(targetUsers);
3618
3619 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3620 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3621 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003622 }
3623
3624 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3625 // Setup a device owner.
3626 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3627 setupDeviceOwner();
3628
3629 // Set up a managed profile managed by different package.
3630 final int MANAGED_PROFILE_USER_ID = 15;
3631 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3632 final ComponentName adminDifferentPackage =
3633 new ComponentName("another.package", "whatever.class");
3634 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3635
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003636 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003637 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003638 dpm.setAffiliationIds(admin1, userAffiliationIds);
3639
3640 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3641 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3642
Tony Mak2f26b792016-11-28 17:54:51 +00003643 // Calling from device owner admin, we should get zero bind device admin target users as
3644 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003645 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003646 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3647 MoreAsserts.assertEmpty(targetUsers);
3648
3649 // Calling from managed profile admin, we should still get zero target users for the same
3650 // reason.
3651 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3652 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3653 MoreAsserts.assertEmpty(targetUsers);
3654 }
3655
Charles Hee078db72017-10-19 18:03:20 +01003656 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003657 // Setup a device owner.
3658 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3659 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003660 // Lock task policy is updated when loading user data.
3661 verify(getServices().iactivityManager).updateLockTaskPackages(
3662 UserHandle.USER_SYSTEM, new String[0]);
3663 verify(getServices().iactivityManager).updateLockTaskFeatures(
3664 UserHandle.USER_SYSTEM, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003665
3666 // Set up a managed profile managed by different package (package name shouldn't matter)
3667 final int MANAGED_PROFILE_USER_ID = 15;
3668 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3669 final ComponentName adminDifferentPackage =
3670 new ComponentName("another.package", "whatever.class");
3671 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Charles Hee078db72017-10-19 18:03:20 +01003672 verify(getServices().iactivityManager).updateLockTaskPackages(
3673 MANAGED_PROFILE_USER_ID, new String[0]);
3674 verify(getServices().iactivityManager).updateLockTaskFeatures(
3675 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003676
3677 // The DO can still set lock task packages
3678 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3679 final String[] doPackages = {"doPackage1", "doPackage2"};
3680 dpm.setLockTaskPackages(admin1, doPackages);
3681 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3682 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3683 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Charles Hee078db72017-10-19 18:03:20 +01003684 verify(getServices().iactivityManager).updateLockTaskPackages(
3685 UserHandle.USER_SYSTEM, doPackages);
3686 // And the DO can still set lock task features
3687 final int doFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3688 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3689 dpm.setLockTaskFeatures(admin1, doFlags);
3690 verify(getServices().iactivityManager).updateLockTaskFeatures(
3691 UserHandle.USER_SYSTEM, doFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003692
3693 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3694 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3695 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003696 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3697 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3698 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3699 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003700 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
Charles Hee078db72017-10-19 18:03:20 +01003701 // And it shouldn't be able to setLockTaskFeatures.
3702 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3703 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3704 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3705 () -> dpm.setLockTaskFeatures(adminDifferentPackage, poFlags));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003706
3707 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003708 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003709 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3710 dpm.setAffiliationIds(admin1, userAffiliationIds);
3711
3712 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3713 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3714
3715 // Now the managed profile can set lock task packages.
3716 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3717 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3718 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3719 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003720 verify(getServices().iactivityManager).updateLockTaskPackages(
3721 MANAGED_PROFILE_USER_ID, poPackages);
3722 // And it can set lock task features.
3723 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
3724 verify(getServices().iactivityManager).updateLockTaskFeatures(
3725 MANAGED_PROFILE_USER_ID, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003726
3727 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003728 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003729 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3730 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003731 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3732 MANAGED_PROFILE_USER_ID, new String[0]);
3733 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3734 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003735
3736 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3737 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3738 }
3739
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003740 public void testIsDeviceManaged() throws Exception {
3741 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3742 setupDeviceOwner();
3743
3744 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3745 // find out that the device has a device owner.
3746 assertTrue(dpm.isDeviceManaged());
3747 mContext.binder.callingUid = 1234567;
3748 mContext.callerPermissions.add(permission.MANAGE_USERS);
3749 assertTrue(dpm.isDeviceManaged());
3750 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3751 mContext.binder.clearCallingIdentity();
3752 assertTrue(dpm.isDeviceManaged());
3753
3754 clearDeviceOwner();
3755
3756 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3757 // not have a device owner.
3758 mContext.binder.callingUid = 1234567;
3759 mContext.callerPermissions.add(permission.MANAGE_USERS);
3760 assertFalse(dpm.isDeviceManaged());
3761 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3762 mContext.binder.clearCallingIdentity();
3763 assertFalse(dpm.isDeviceManaged());
3764 }
3765
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003766 public void testDeviceOwnerOrganizationName() throws Exception {
3767 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3768 setupDeviceOwner();
3769
3770 dpm.setOrganizationName(admin1, "organization");
3771
3772 // Device owner can retrieve organization managing the device.
3773 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3774
3775 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3776 mContext.binder.callingUid = 1234567;
3777 mContext.callerPermissions.add(permission.MANAGE_USERS);
3778 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3779 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3780
3781 // System can retrieve organization managing the device.
3782 mContext.binder.clearCallingIdentity();
3783 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3784
3785 // Removing the device owner clears the organization managing the device.
3786 clearDeviceOwner();
3787 assertNull(dpm.getDeviceOwnerOrganizationName());
3788 }
3789
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003790 public void testWipeDataManagedProfile() throws Exception {
3791 final int MANAGED_PROFILE_USER_ID = 15;
3792 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3793 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3794 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3795
3796 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003797 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003798 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003799 // Get mock reason string since we throw an IAE with empty string input.
3800 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3801 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003802
3803 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003804 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003805 MANAGED_PROFILE_USER_ID);
3806 }
3807
3808 public void testWipeDataManagedProfileDisallowed() throws Exception {
3809 final int MANAGED_PROFILE_USER_ID = 15;
3810 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3811 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3812
3813 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003814 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003815 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3816
Pavel Grafov75c0a892017-05-18 17:28:27 +01003817 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003818 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3819 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3820 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003821 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3822 thenReturn("Just a test string.");
3823
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003824 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003825 // The PO is not allowed to remove the profile if the user restriction was set on the
3826 // profile by the system
3827 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3828 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003829 }
3830
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003831 public void testWipeDataDeviceOwner() throws Exception {
3832 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003833 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003834 UserManager.DISALLOW_FACTORY_RESET,
3835 UserHandle.SYSTEM))
3836 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003837 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3838 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003839
3840 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003841 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003842 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3843 /*wipeEuicc=*/ eq(false));
3844 }
3845
3846 public void testWipeEuiccDataEnabled() throws Exception {
3847 setDeviceOwner();
3848 when(getServices().userManager.getUserRestrictionSource(
3849 UserManager.DISALLOW_FACTORY_RESET,
3850 UserHandle.SYSTEM))
3851 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003852 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3853 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003854
3855 dpm.wipeData(WIPE_EUICC);
3856 verify(getServices().recoverySystem).rebootWipeUserData(
3857 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3858 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003859 }
3860
3861 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3862 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003863 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003864 UserManager.DISALLOW_FACTORY_RESET,
3865 UserHandle.SYSTEM))
3866 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003867 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3868 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003869 // The DO is not allowed to wipe the device if the user restriction was set
3870 // by the system
3871 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3872 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003873 }
3874
3875 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3876 final int MANAGED_PROFILE_USER_ID = 15;
3877 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3878 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3879
3880 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003881 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003882 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3883
Pavel Grafov75c0a892017-05-18 17:28:27 +01003884 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003885 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3886 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3887 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3888
3889 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3890 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3891
3892 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3893 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3894 // Failed password attempts on the parent user are taken into account, as there isn't a
3895 // separate work challenge.
3896 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3897 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3898 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3899
3900 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3901 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003902 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003903 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003904 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003905 }
3906
3907 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3908 throws Exception {
3909 final int MANAGED_PROFILE_USER_ID = 15;
3910 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3911 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3912
3913 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003914 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003915 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3916
Pavel Grafov75c0a892017-05-18 17:28:27 +01003917 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003918 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3919 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3920 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3921
3922 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3923 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3924
3925 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3926 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3927 // Failed password attempts on the parent user are taken into account, as there isn't a
3928 // separate work challenge.
3929 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3930 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3931 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3932
3933 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3934 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003935 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003936 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003937 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003938 }
3939
3940 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3941 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003942 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003943 UserManager.DISALLOW_FACTORY_RESET,
3944 UserHandle.SYSTEM))
3945 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3946
3947 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3948
3949 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3950 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3951 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3952 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3953 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3954
3955 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3956 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003957 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003958 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3959 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003960 }
3961
3962 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3963 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003964 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003965 UserManager.DISALLOW_FACTORY_RESET,
3966 UserHandle.SYSTEM))
3967 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3968
3969 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3970
3971 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3972 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3973 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3974 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3975 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3976
3977 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003978 verifyZeroInteractions(getServices().recoverySystem);
3979 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003980 .removeUserEvenWhenDisallowed(anyInt());
3981 }
3982
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003983 public void testGetPermissionGrantState() throws Exception {
3984 final String permission = "some.permission";
3985 final String app1 = "com.example.app1";
3986 final String app2 = "com.example.app2";
3987
Pavel Grafov75c0a892017-05-18 17:28:27 +01003988 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003989 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003990 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003991 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003992 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003993 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3994 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003995 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003996 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003997 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003998 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003999 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004000 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4001
4002 // System can retrieve permission grant state.
4003 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004004 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004005 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4006 dpm.getPermissionGrantState(null, app1, permission));
4007 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4008 dpm.getPermissionGrantState(null, app2, permission));
4009
4010 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004011 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4012 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004013 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4014 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004015
4016 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004017 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4018 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004019 setAsProfileOwner(admin1);
4020 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4021 dpm.getPermissionGrantState(admin1, app1, permission));
4022 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4023 dpm.getPermissionGrantState(admin1, app2, permission));
4024 }
4025
Rubin Xuaab7a412016-12-30 21:13:29 +00004026 public void testResetPasswordWithToken() throws Exception {
4027 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4028 setupDeviceOwner();
4029 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004030 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4031 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4032
Rubin Xuaab7a412016-12-30 21:13:29 +00004033 // test adding a token
4034 final byte[] token = new byte[32];
4035 final long handle = 123456;
4036 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01004037 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004038 .thenReturn(handle);
4039 assertTrue(dpm.setResetPasswordToken(admin1, token));
4040
4041 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004042 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004043 .thenReturn(true);
4044 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4045
4046 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004047 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01004048 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
4049 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004050 eq(UserHandle.USER_SYSTEM)))
4051 .thenReturn(true);
4052 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4053
4054 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004055 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004056 .thenReturn(true);
4057 assertTrue(dpm.clearResetPasswordToken(admin1));
4058 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004059
Alexandru-Andrei Rotaru7f31bb02017-09-07 16:29:48 +01004060 public void testSetPasswordBlacklistCannotBeCalledByNonAdmin() throws Exception {
4061 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4062 () -> dpm.setPasswordBlacklist(admin1, null, null));
4063 verifyZeroInteractions(getServices().passwordBlacklist);
4064 }
4065
4066 public void testClearingPasswordBlacklistDoesNotCreateNewBlacklist() throws Exception {
4067 setupProfileOwner();
4068 dpm.setPasswordBlacklist(admin1, null, null);
4069 verifyZeroInteractions(getServices().passwordBlacklist);
4070 }
4071
4072 public void testSetPasswordBlacklistCreatesNewBlacklist() throws Exception {
4073 final String name = "myblacklist";
4074 final List<String> explicit = Arrays.asList("password", "letmein");
4075 setupProfileOwner();
4076 dpm.setPasswordBlacklist(admin1, name, explicit);
4077 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, explicit);
4078 }
4079
4080 public void testSetPasswordBlacklistOnlyConvertsExplicitToLowerCase() throws Exception {
4081 final List<String> mixedCase = Arrays.asList("password", "LETMEIN", "FooTBAll");
4082 final List<String> lowerCase = Arrays.asList("password", "letmein", "football");
4083 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4084 setupDeviceOwner();
4085 final String name = "Name of the Blacklist";
4086 dpm.setPasswordBlacklist(admin1, name, mixedCase);
4087 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, lowerCase);
4088 }
4089
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004090 public void testIsActivePasswordSufficient() throws Exception {
4091 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4092 mContext.packageName = admin1.getPackageName();
4093 setupDeviceOwner();
4094
4095 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4096 dpm.setPasswordMinimumLength(admin1, 8);
4097 dpm.setPasswordMinimumLetters(admin1, 6);
4098 dpm.setPasswordMinimumLowerCase(admin1, 3);
4099 dpm.setPasswordMinimumUpperCase(admin1, 1);
4100 dpm.setPasswordMinimumNonLetter(admin1, 1);
4101 dpm.setPasswordMinimumNumeric(admin1, 1);
4102 dpm.setPasswordMinimumSymbols(admin1, 0);
4103
Rubin Xucc391c22018-01-02 20:37:35 +00004104 reset(mContext.spiedContext);
4105
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004106 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4107 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4108 8, 2,
4109 6, 1,
4110 0, 1);
4111
4112 setActivePasswordState(passwordMetricsNoSymbols);
4113 assertTrue(dpm.isActivePasswordSufficient());
4114
4115 initializeDpms();
4116 reset(mContext.spiedContext);
4117 assertTrue(dpm.isActivePasswordSufficient());
4118
4119 // This call simulates the user entering the password for the first time after a reboot.
4120 // This causes password metrics to be reloaded into memory. Until this happens,
4121 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4122 // even if the DPC changes password requirements so that the password no longer meets the
4123 // requirements. This is a known limitation of the current implementation of
4124 // isActivePasswordSufficient() - see b/34218769.
4125 setActivePasswordState(passwordMetricsNoSymbols);
4126 assertTrue(dpm.isActivePasswordSufficient());
4127
4128 dpm.setPasswordMinimumSymbols(admin1, 1);
4129 // This assertion would fail if we had not called setActivePasswordState() again after
4130 // initializeDpms() - see previous comment.
4131 assertFalse(dpm.isActivePasswordSufficient());
4132
4133 initializeDpms();
4134 reset(mContext.spiedContext);
4135 assertFalse(dpm.isActivePasswordSufficient());
4136
4137 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4138 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4139 7, 2,
4140 5, 1,
4141 1, 2);
4142
4143 setActivePasswordState(passwordMetricsWithSymbols);
4144 assertTrue(dpm.isActivePasswordSufficient());
4145 }
4146
Pavel Grafov75c0a892017-05-18 17:28:27 +01004147 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4148 throws Exception {
4149 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004150 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004151
Pavel Grafov75c0a892017-05-18 17:28:27 +01004152 dpm.setActivePasswordState(passwordMetrics, userHandle);
4153 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004154
Rubin Xucc391c22018-01-02 20:37:35 +00004155 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4156 // reportPasswordChanged()
4157 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
4158 MockUtils.checkIntentAction(
4159 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4160 MockUtils.checkUserHandle(userHandle));
4161
Pavel Grafov75c0a892017-05-18 17:28:27 +01004162 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4163 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004164 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004165
4166 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4167 MockUtils.checkIntent(intent),
4168 MockUtils.checkUserHandle(userHandle));
4169
4170 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4171 // let it finish with system uid, otherwise it will throw and crash.
4172 flushTasks();
4173
4174 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004175 }
4176
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004177 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4178 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4179 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4180 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4181 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4182 DpmMockContext.SYSTEM_UID);
4183 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4184 DpmMockContext.SYSTEM_UID);
4185
4186 // Set up a device owner.
4187 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004188 setupDeviceOwner();
4189
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004190 // First and second user set IMEs manually.
4191 mContext.binder.callingUid = firstUserSystemUid;
4192 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4193 mContext.binder.callingUid = secondUserSystemUid;
4194 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004195
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004196 // Device owner changes IME for first user.
4197 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004198 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004199 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004200 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004201 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004202 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004203 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004204 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4205 mContext.binder.callingUid = firstUserSystemUid;
4206 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4207 mContext.binder.callingUid = secondUserSystemUid;
4208 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004209
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004210 // Second user changes IME manually.
4211 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4212 mContext.binder.callingUid = firstUserSystemUid;
4213 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4214 mContext.binder.callingUid = secondUserSystemUid;
4215 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004216
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004217 // First user changes IME manually.
4218 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4219 mContext.binder.callingUid = firstUserSystemUid;
4220 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4221 mContext.binder.callingUid = secondUserSystemUid;
4222 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004223
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004224 // Device owner changes IME for first user again.
4225 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004226 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004227 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004228 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004229 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004230 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004231 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4232 mContext.binder.callingUid = firstUserSystemUid;
4233 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4234 mContext.binder.callingUid = secondUserSystemUid;
4235 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004236
4237 // Restarting the DPMS should not lose information.
4238 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004239 mContext.binder.callingUid = firstUserSystemUid;
4240 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4241 mContext.binder.callingUid = secondUserSystemUid;
4242 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004243
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004244 // Device owner can find out whether it set the current IME itself.
4245 mContext.binder.callingUid = deviceOwnerUid;
4246 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004247
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004248 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004249 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004250 mContext.binder.callingUid = firstUserSystemUid;
4251 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4252 mContext.binder.callingUid = secondUserSystemUid;
4253 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004254 }
4255
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004256 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4257 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4258 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4259 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4260 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4261 DpmMockContext.SYSTEM_UID);
4262 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4263 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004264
4265 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004266 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004267 setupProfileOwner();
4268
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004269 // First and second user set IMEs manually.
4270 mContext.binder.callingUid = firstUserSystemUid;
4271 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4272 mContext.binder.callingUid = secondUserSystemUid;
4273 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004274
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004275 // Profile owner changes IME for second user.
4276 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004277 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004278 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004279 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004280 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004281 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004282 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004283 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4284 mContext.binder.callingUid = firstUserSystemUid;
4285 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4286 mContext.binder.callingUid = secondUserSystemUid;
4287 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004288
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004289 // First user changes IME manually.
4290 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4291 mContext.binder.callingUid = firstUserSystemUid;
4292 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4293 mContext.binder.callingUid = secondUserSystemUid;
4294 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004295
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004296 // Second user changes IME manually.
4297 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4298 mContext.binder.callingUid = firstUserSystemUid;
4299 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4300 mContext.binder.callingUid = secondUserSystemUid;
4301 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004302
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004303 // Profile owner changes IME for second user again.
4304 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004305 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004306 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004307 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004308 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004309 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004310 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4311 mContext.binder.callingUid = firstUserSystemUid;
4312 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4313 mContext.binder.callingUid = secondUserSystemUid;
4314 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004315
4316 // Restarting the DPMS should not lose information.
4317 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004318 mContext.binder.callingUid = firstUserSystemUid;
4319 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4320 mContext.binder.callingUid = secondUserSystemUid;
4321 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004322
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004323 // Profile owner can find out whether it set the current IME itself.
4324 mContext.binder.callingUid = profileOwnerUid;
4325 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004326
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004327 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004328 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004329 mContext.binder.callingUid = firstUserSystemUid;
4330 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4331 mContext.binder.callingUid = secondUserSystemUid;
4332 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004333 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004334
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004335 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4336 throws Exception {
4337 // Set up a device owner.
4338 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4339 setupDeviceOwner();
4340 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4341 }
4342
4343 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4344 throws Exception {
4345 // Set up a profile owner.
4346 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4347 setupProfileOwner();
4348 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4349 }
4350
4351 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4352 int adminUid) throws Exception {
4353 mContext.binder.callingUid = adminUid;
4354 final int userId = UserHandle.getUserId(adminUid);
4355
4356 final String packageName = "some.package";
4357 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4358 admin1, Collections.singletonList(packageName)));
4359 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4360
4361 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4362 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4363
4364 // Attempt to set to empty list (which means no listener is whitelisted)
4365 mContext.binder.callingUid = adminUid;
4366 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004367 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004368 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4369
4370 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4371 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4372 }
4373
4374 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4375 // Set up a managed profile
4376 final int MANAGED_PROFILE_USER_ID = 15;
4377 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4378 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4379 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4380
4381 final String permittedListener = "some.package";
4382 setupPackageInPackageManager(
4383 permittedListener,
4384 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4385 /*appId=*/ 12345, /*flags=*/ 0);
4386
4387 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4388 admin1, Collections.singletonList(permittedListener)));
4389
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004390 // isNotificationListenerServicePermitted should throw if not called from System.
4391 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4392 () -> dpms.isNotificationListenerServicePermitted(
4393 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004394
4395 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4396 assertTrue(dpms.isNotificationListenerServicePermitted(
4397 permittedListener, MANAGED_PROFILE_USER_ID));
4398 }
4399
4400 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4401 throws Exception {
4402 // Set up a managed profile
4403 final int MANAGED_PROFILE_USER_ID = 15;
4404 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4405 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4406 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4407
4408 final String permittedListener = "permitted.package";
4409 int appId = 12345;
4410 setupPackageInPackageManager(
4411 permittedListener,
4412 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4413 appId, /*flags=*/ 0);
4414
4415 final String notPermittedListener = "not.permitted.package";
4416 setupPackageInPackageManager(
4417 notPermittedListener,
4418 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4419 ++appId, /*flags=*/ 0);
4420
4421 final String systemListener = "system.package";
4422 setupPackageInPackageManager(
4423 systemListener,
4424 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4425 ++appId, ApplicationInfo.FLAG_SYSTEM);
4426
4427 // By default all packages are allowed
4428 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4429
4430 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4431 assertTrue(dpms.isNotificationListenerServicePermitted(
4432 permittedListener, MANAGED_PROFILE_USER_ID));
4433 assertTrue(dpms.isNotificationListenerServicePermitted(
4434 notPermittedListener, MANAGED_PROFILE_USER_ID));
4435 assertTrue(dpms.isNotificationListenerServicePermitted(
4436 systemListener, MANAGED_PROFILE_USER_ID));
4437
4438 // Setting only one package in the whitelist
4439 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4440 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4441 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004442 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004443 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4444 assertEquals(1, permittedListeners.size());
4445 assertEquals(permittedListener, permittedListeners.get(0));
4446
4447 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4448 assertTrue(dpms.isNotificationListenerServicePermitted(
4449 permittedListener, MANAGED_PROFILE_USER_ID));
4450 assertFalse(dpms.isNotificationListenerServicePermitted(
4451 notPermittedListener, MANAGED_PROFILE_USER_ID));
4452 // System packages are always allowed (even if not in the whitelist)
4453 assertTrue(dpms.isNotificationListenerServicePermitted(
4454 systemListener, MANAGED_PROFILE_USER_ID));
4455
4456 // Setting an empty whitelist - only system listeners allowed
4457 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4458 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004459 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004460 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4461
4462 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4463 assertFalse(dpms.isNotificationListenerServicePermitted(
4464 permittedListener, MANAGED_PROFILE_USER_ID));
4465 assertFalse(dpms.isNotificationListenerServicePermitted(
4466 notPermittedListener, MANAGED_PROFILE_USER_ID));
4467 // System packages are always allowed (even if not in the whitelist)
4468 assertTrue(dpms.isNotificationListenerServicePermitted(
4469 systemListener, MANAGED_PROFILE_USER_ID));
4470
4471 // Setting a null whitelist - all listeners allowed
4472 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4473 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4474 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4475
4476 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4477 assertTrue(dpms.isNotificationListenerServicePermitted(
4478 permittedListener, MANAGED_PROFILE_USER_ID));
4479 assertTrue(dpms.isNotificationListenerServicePermitted(
4480 notPermittedListener, MANAGED_PROFILE_USER_ID));
4481 assertTrue(dpms.isNotificationListenerServicePermitted(
4482 systemListener, MANAGED_PROFILE_USER_ID));
4483 }
4484
4485 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4486 throws Exception {
4487 // Set up a managed profile
4488 final int MANAGED_PROFILE_USER_ID = 15;
4489 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4490 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4491 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4492
4493 final String nonSystemPackage = "non.system.package";
4494 int appId = 12345;
4495 setupPackageInPackageManager(
4496 nonSystemPackage,
4497 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4498 appId, /*flags=*/ 0);
4499
4500 final String systemListener = "system.package";
4501 setupPackageInPackageManager(
4502 systemListener,
4503 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4504 ++appId, ApplicationInfo.FLAG_SYSTEM);
4505
4506 // By default all packages are allowed (for all profiles)
4507 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4508
4509 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4510 assertTrue(dpms.isNotificationListenerServicePermitted(
4511 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4512 assertTrue(dpms.isNotificationListenerServicePermitted(
4513 systemListener, MANAGED_PROFILE_USER_ID));
4514 assertTrue(dpms.isNotificationListenerServicePermitted(
4515 nonSystemPackage, UserHandle.USER_SYSTEM));
4516 assertTrue(dpms.isNotificationListenerServicePermitted(
4517 systemListener, UserHandle.USER_SYSTEM));
4518
4519 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4520 // all allowed in primary profile
4521 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4522 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004523 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004524 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4525
4526 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4527 assertFalse(dpms.isNotificationListenerServicePermitted(
4528 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4529 assertTrue(dpms.isNotificationListenerServicePermitted(
4530 systemListener, MANAGED_PROFILE_USER_ID));
4531 assertTrue(dpms.isNotificationListenerServicePermitted(
4532 nonSystemPackage, UserHandle.USER_SYSTEM));
4533 assertTrue(dpms.isNotificationListenerServicePermitted(
4534 systemListener, UserHandle.USER_SYSTEM));
4535 }
4536
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004537 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004538 mServiceContext.packageName = mRealTestContext.getPackageName();
4539 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4540 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004541 setDeviceOwner();
4542
Pavel Grafov75c0a892017-05-18 17:28:27 +01004543 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004544 }
4545
4546 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004547 mServiceContext.packageName = mRealTestContext.getPackageName();
4548 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4549 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004550 setAsProfileOwner(admin1);
4551
Pavel Grafov75c0a892017-05-18 17:28:27 +01004552 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4553 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004554 }
4555
4556 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004557 mServiceContext.packageName = mRealTestContext.getPackageName();
4558 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4559 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004560 setAsProfileOwner(admin1);
4561
Pavel Grafov75c0a892017-05-18 17:28:27 +01004562 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4563 caller.packageName = "com.example.delegate";
4564 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4565 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004566
Pavel Grafov75c0a892017-05-18 17:28:27 +01004567 // Make caller a delegated cert installer.
4568 runAsCaller(mAdmin1Context, dpms,
4569 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004570
4571 verifyCanGetOwnerInstalledCaCerts(null, caller);
4572 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004573 }
4574
Rubin Xucc391c22018-01-02 20:37:35 +00004575 public void testDisallowSharingIntoProfileSetRestriction() {
4576 Bundle restriction = new Bundle();
4577 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4578
4579 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4580 RestrictionsListener listener = new RestrictionsListener(mContext);
4581 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4582 new Bundle());
4583 verifyDataSharingChangedBroadcast();
4584 }
4585
4586 public void testDisallowSharingIntoProfileClearRestriction() {
4587 Bundle restriction = new Bundle();
4588 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4589
4590 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4591 RestrictionsListener listener = new RestrictionsListener(mContext);
4592 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4593 restriction);
4594 verifyDataSharingChangedBroadcast();
4595 }
4596
4597 public void testDisallowSharingIntoProfileUnchanged() {
4598 RestrictionsListener listener = new RestrictionsListener(mContext);
4599 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4600 new Bundle());
4601 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4602 }
4603
4604 private void verifyDataSharingChangedBroadcast() {
4605 Intent expectedIntent = new Intent(
4606 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4607 expectedIntent.setPackage("com.android.managedprovisioning");
4608 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4609 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4610 MockUtils.checkIntent(expectedIntent),
4611 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4612 }
4613
yuemingwe3d9c092018-01-11 12:11:44 +00004614 public void testOverrideApnAPIsFailWithPO() throws Exception {
4615 setupProfileOwner();
4616 ApnSetting apn = (new ApnSetting.Builder()).build();
4617 assertExpectException(SecurityException.class, null, () ->
4618 dpm.addOverrideApn(admin1, apn));
4619 assertExpectException(SecurityException.class, null, () ->
4620 dpm.updateOverrideApn(admin1, 0, apn));
4621 assertExpectException(SecurityException.class, null, () ->
4622 dpm.removeOverrideApn(admin1, 0));
4623 assertExpectException(SecurityException.class, null, () ->
4624 dpm.getOverrideApns(admin1));
4625 assertExpectException(SecurityException.class, null, () ->
4626 dpm.setOverrideApnsEnabled(admin1, false));
4627 assertExpectException(SecurityException.class, null, () ->
4628 dpm.isOverrideApnEnabled(admin1));
4629 }
4630
Robin Lee2c68dad2017-03-17 12:50:24 +00004631 private void verifyCanGetOwnerInstalledCaCerts(
4632 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004633 final String alias = "cert";
4634 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004635
4636 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004637 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004638 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4639 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004640 }
4641 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4642
4643 // caller: device admin or delegated certificate installer
4644 callerContext.applicationInfo = new ApplicationInfo();
4645 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4646
4647 // system_server
4648 final DpmMockContext serviceContext = mContext;
4649 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004650 getServices().addPackageContext(callerUser, admin1Context);
4651 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004652
4653 // Install a CA cert.
4654 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004655 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004656 .thenReturn(alias);
4657 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004658 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004659 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004660 });
4661
Pavel Grafov75c0a892017-05-18 17:28:27 +01004662 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4663 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4664 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004665 flushTasks();
4666
Robin Lee2c68dad2017-03-17 12:50:24 +00004667 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4668
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004669 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004670 runAsCaller(admin1Context, dpms, (dpm) -> {
4671 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004672 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004673 ownerInstalledCaCerts.addAll(installedCaCerts);
4674 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004675
4676 // Restarting the DPMS should not lose information.
4677 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004678 runAsCaller(admin1Context, dpms, (dpm) ->
4679 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004680
4681 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004682 runAsCaller(serviceContext, dpms, (dpm) -> {
4683 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004684
Robin Lee2c68dad2017-03-17 12:50:24 +00004685 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004686 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004687 });
4688
Pavel Grafov75c0a892017-05-18 17:28:27 +01004689 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4690 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4691 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004692 flushTasks();
4693
4694 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4695 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004696 runAsCaller(admin1Context, dpms, (dpm) -> {
4697 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4698 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004699 }
4700
Robin Lee2c68dad2017-03-17 12:50:24 +00004701 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4702 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004703 final String alias = "cert";
4704 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004705
4706 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004707 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004708 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4709 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004710 }
4711 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4712
4713 // caller: device admin or delegated certificate installer
4714 callerContext.applicationInfo = new ApplicationInfo();
4715 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4716
4717 // system_server
4718 final DpmMockContext serviceContext = mContext;
4719 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004720 getServices().addPackageContext(callerUser, admin1Context);
4721 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004722
4723 // Install a CA cert as caller
4724 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004725 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004726 .thenReturn(alias);
4727 assertTrue(dpm.installCaCert(callerName, caCert));
4728 });
4729
4730 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004731 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004732 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004733 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4734 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4735 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004736 flushTasks();
4737
Robin Lee2c68dad2017-03-17 12:50:24 +00004738 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004739 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004740
4741 runAsCaller(serviceContext, dpms, (dpm) -> {
4742 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4743 assertNotNull(ownerInstalledCaCerts);
4744 assertTrue(ownerInstalledCaCerts.isEmpty());
4745 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004746 }
4747
Eran Messeri94d56762017-12-21 20:50:54 +00004748 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4749 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4750 Arrays.sort(gotFlags);
4751 Arrays.sort(expectedFlags);
4752 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4753 }
4754
4755 public void testTranslationOfIdAttestationFlag() {
4756 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4757 int[] correspondingAttUtilsTypes = new int[]{
4758 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4759 AttestationUtils.ID_TYPE_MEID};
4760
4761 // Test translation of zero flags
4762 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4763
4764 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4765 // non-null array
4766 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4767
4768 // Test translation of a single flag
4769 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4770 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4771 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4772
4773 // Test translation of two flags
4774 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4775 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4776 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4777 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4778
4779 // Test translation of all three flags
4780 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4781 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4782 AttestationUtils.ID_TYPE_MEID});
4783 // Test translation of all three flags
4784 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4785 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4786 AttestationUtils.ID_TYPE_MEID});
4787 }
4788
Victor Chang3e794af2016-03-04 13:48:17 +00004789 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004790 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004791 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4792 dpms.notifyChangeToContentObserver(
4793 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4794 }
4795
4796 private void assertProvisioningAllowed(String action, boolean expected) {
4797 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4798 dpm.isProvisioningAllowed(action));
4799 }
Tony Mak2f26b792016-11-28 17:54:51 +00004800
Nicolas Prevot45d29072017-01-18 16:11:19 +00004801 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4802 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004803 final String previousPackageName = mContext.packageName;
4804 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004805
4806 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4807 mContext.packageName = packageName;
4808 mMockContext.binder.callingUid = uid;
4809 assertProvisioningAllowed(action, expected);
4810
4811 // Set the previous package name / calling uid to go back to the initial state.
4812 mContext.packageName = previousPackageName;
4813 mMockContext.binder.callingUid = previousUid;
4814 }
4815
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004816 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004817 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4818 }
4819
4820 private void assertCheckProvisioningPreCondition(
4821 String action, String packageName, int provisioningCondition) {
4822 assertEquals("checkProvisioningPreCondition("
4823 + action + ", " + packageName + ") returning unexpected result",
4824 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004825 }
4826
Tony Mak2f26b792016-11-28 17:54:51 +00004827 /**
4828 * Setup a managed profile with the specified admin and its uid.
4829 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4830 * @param adminUid uid of the admin package.
4831 * @param copyFromAdmin package information for {@code admin} will be built based on this
4832 * component's information.
4833 */
4834 private void addManagedProfile(
4835 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4836 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004837 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004838 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4839 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4840 dpm.setActiveAdmin(admin, false, userId);
4841 assertTrue(dpm.setProfileOwner(admin, null, userId));
4842 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4843 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004844
4845 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004846 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004847 */
Robin Leeabaa0692017-02-20 20:54:22 +00004848 private static StringParceledListSlice asSlice(String[] s) {
4849 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004850 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004851
4852 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004853 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4854 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004855
Robin Lee2c68dad2017-03-17 12:50:24 +00004856 // We can't let exceptions happen on the background thread. Throw them here if they happen
4857 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004858 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004859 }
Victor Chang3e794af2016-03-04 13:48:17 +00004860}