blob: 26da4365c2c8a1677179dc30fe03ae8a247c64e5 [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;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080081import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000082import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010083import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070084import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070085
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010086import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000087import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000088import com.android.server.LocalServices;
89import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000090import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000091import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000092
Robin Lee7f5c91c2017-02-08 21:27:02 +000093import org.hamcrest.BaseMatcher;
94import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -080095import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -070096import org.mockito.invocation.InvocationOnMock;
97import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098
Makoto Onukic8a5a552015-11-19 14:29:12 -080099import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000100import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000101import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700102import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700104import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100105import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000106import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700109 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000110 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111 m FrameworksServicesTests &&
112 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000113 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700114 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800115 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116
117 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000118 *
119 * , or:
120 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000122@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100123@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000125 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
126 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
127 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100128 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800129 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100130 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000131
Pavel Grafov75c0a892017-05-18 17:28:27 +0100132 // TODO replace all instances of this with explicit {@link #mServiceContext}.
133 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700134 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100135
136 private DpmMockContext mServiceContext;
137 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700138 public DevicePolicyManager dpm;
139 public DevicePolicyManagerServiceTestable dpms;
140
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100141 /*
142 * The CA cert below is the content of cacert.pem as generated by:
143 *
144 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
145 */
146 private static final String TEST_CA =
147 "-----BEGIN CERTIFICATE-----\n" +
148 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
149 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
150 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
151 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
152 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
153 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
154 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
155 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
156 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
157 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
158 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
159 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
160 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
161 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
162 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
163 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
164 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
165 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
166 "wQ==\n" +
167 "-----END CERTIFICATE-----\n";
168
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700169 @Override
170 protected void setUp() throws Exception {
171 super.setUp();
172
173 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100174 mServiceContext = mContext;
175 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
176 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700177 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100178 doReturn(Collections.singletonList(new ResolveInfo()))
179 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
180 any(Intent.class),
181 anyInt(),
182 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700183
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800184 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100185 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800186
Makoto Onukia52562c2015-10-01 16:12:31 -0700187 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700188
Sudheer Shanka101c3532018-01-08 16:28:42 -0800189 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800190 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700191 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
192 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
193 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800194 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700195
Pavel Grafov75c0a892017-05-18 17:28:27 +0100196 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
197 mAdmin1Context.packageName = admin1.getPackageName();
198 mAdmin1Context.applicationInfo = new ApplicationInfo();
199 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
200
Makoto Onukib643fb02015-09-22 15:03:44 -0700201 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700202 }
203
Robin Lee2c68dad2017-03-17 12:50:24 +0000204 @Override
205 protected void tearDown() throws Exception {
206 flushTasks();
207 super.tearDown();
208 }
209
Makoto Onukia52562c2015-10-01 16:12:31 -0700210 private void initializeDpms() {
211 // Need clearCallingIdentity() to pass permission checks.
212 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100213 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700214
Pavel Grafov75c0a892017-05-18 17:28:27 +0100215 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
216 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
217 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700218
Pavel Grafov75c0a892017-05-18 17:28:27 +0100219 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700220
Pavel Grafov75c0a892017-05-18 17:28:27 +0100221 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700222 }
223
Makoto Onukib643fb02015-09-22 15:03:44 -0700224 private void setUpUserManager() {
225 // Emulate UserManager.set/getApplicationRestriction().
226 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
227
228 // UM.setApplicationRestrictions() will save to appRestrictions.
229 doAnswer(new Answer<Void>() {
230 @Override
231 public Void answer(InvocationOnMock invocation) throws Throwable {
232 String pkg = (String) invocation.getArguments()[0];
233 Bundle bundle = (Bundle) invocation.getArguments()[1];
234 UserHandle user = (UserHandle) invocation.getArguments()[2];
235
236 appRestrictions.put(Pair.create(pkg, user), bundle);
237
238 return null;
239 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100240 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100241 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700242
243 // UM.getApplicationRestrictions() will read from appRestrictions.
244 doAnswer(new Answer<Bundle>() {
245 @Override
246 public Bundle answer(InvocationOnMock invocation) throws Throwable {
247 String pkg = (String) invocation.getArguments()[0];
248 UserHandle user = (UserHandle) invocation.getArguments()[1];
249
250 return appRestrictions.get(Pair.create(pkg, user));
251 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100252 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700253 anyString(), any(UserHandle.class));
254
Makoto Onukid932f762015-09-29 16:53:38 -0700255 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100256 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700257 }
258
259 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100260 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700261
Pavel Grafov75c0a892017-05-18 17:28:27 +0100262 mServiceContext.binder.callingUid =
263 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
264 runAsCaller(mServiceContext, dpms, dpm -> {
265 // PO needs to be a DA.
266 dpm.setActiveAdmin(admin, /*replace=*/ false);
267 // Fire!
268 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
269 // Check
270 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
271 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700272
Pavel Grafov75c0a892017-05-18 17:28:27 +0100273 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700274 }
275
276 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100277 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700278 .thenReturn(false);
279
280 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100281 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700282
283 // If the device has no DPMS feature, it shouldn't register the local service.
284 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
285 }
286
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800287 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800288 // Device owner in SYSTEM_USER
289 setDeviceOwner();
290 // Profile owner in CALLER_USER_HANDLE
291 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
292 setAsProfileOwner(admin2);
293 // Active admin in CALLER_USER_HANDLE
294 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
295 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
296 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
297 DpmMockContext.CALLER_USER_HANDLE);
298 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
299 DpmMockContext.CALLER_USER_HANDLE));
300
301 initializeDpms();
302
303 // Verify
304 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800305 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800306 eq(UserHandle.USER_SYSTEM));
307 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800308 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800309 adminAnotherPackage.getPackageName()),
310 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800311 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
312 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
313 }
314
315 public void testLoadAdminData_noAdmins() throws Exception {
316 final int ANOTHER_USER_ID = 15;
317 getServices().addUser(ANOTHER_USER_ID, 0);
318
319 initializeDpms();
320
321 // Verify
322 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
323 null, DpmMockContext.CALLER_USER_HANDLE);
324 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
325 null, ANOTHER_USER_ID);
326 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
327 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800328 }
329
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700330 /**
331 * Caller doesn't have proper permissions.
332 */
333 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700334 // 1. Failure cases.
335
336 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100337 assertExpectException(SecurityException.class, /* messageRegex= */ null,
338 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700339
340 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
341 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100342
343 assertExpectException(SecurityException.class, /* messageRegex= */ null,
344 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700345 }
346
Makoto Onukif76b06a2015-09-22 15:03:44 -0700347 /**
348 * Test for:
349 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800350 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700351 * {@link DevicePolicyManager#isAdminActive}
352 * {@link DevicePolicyManager#isAdminActiveAsUser}
353 * {@link DevicePolicyManager#getActiveAdmins}
354 * {@link DevicePolicyManager#getActiveAdminsAsUser}
355 */
356 public void testSetActiveAdmin() throws Exception {
357 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700358 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
359
Makoto Onukif76b06a2015-09-22 15:03:44 -0700360 // 2. Call the API.
361 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700362
363 // 3. Verify internal calls.
364
365 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700366 verify(mContext.spiedContext).sendBroadcastAsUser(
367 MockUtils.checkIntentAction(
368 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
369 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
370 verify(mContext.spiedContext).sendBroadcastAsUser(
371 MockUtils.checkIntentAction(
372 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700373 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
374
Pavel Grafov75c0a892017-05-18 17:28:27 +0100375 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700376 eq(admin1.getPackageName()),
377 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
378 eq(PackageManager.DONT_KILL_APP),
379 eq(DpmMockContext.CALLER_USER_HANDLE),
380 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700381
Sudheer Shanka101c3532018-01-08 16:28:42 -0800382 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
383 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
384
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700385 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700386
387 // Make sure it's active admin1.
388 assertTrue(dpm.isAdminActive(admin1));
389 assertFalse(dpm.isAdminActive(admin2));
390 assertFalse(dpm.isAdminActive(admin3));
391
392 // But not admin1 for a different user.
393
394 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
395 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
396 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
397
398 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
399 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
400
401 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
402
403 // Next, add one more admin.
404 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700405 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700406 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700407
408 dpm.setActiveAdmin(admin2, /* replace =*/ false);
409
410 // Now we have two admins.
411 assertTrue(dpm.isAdminActive(admin1));
412 assertTrue(dpm.isAdminActive(admin2));
413 assertFalse(dpm.isAdminActive(admin3));
414
415 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
416 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100417 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700418 eq(admin1.getPackageName()),
419 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
420 eq(PackageManager.DONT_KILL_APP),
421 eq(DpmMockContext.CALLER_USER_HANDLE),
422 anyString());
423
Sudheer Shanka101c3532018-01-08 16:28:42 -0800424 // times(2) because it was previously called for admin1 which is in the same package
425 // as admin2.
426 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
427 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
428
Makoto Onukif76b06a2015-09-22 15:03:44 -0700429 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100430 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
431 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700432
433 // 5. Add the same admin1 again with replace, which should succeed.
434 dpm.setActiveAdmin(admin1, /* replace =*/ true);
435
436 // TODO make sure it's replaced.
437
438 // 6. Test getActiveAdmins()
439 List<ComponentName> admins = dpm.getActiveAdmins();
440 assertEquals(2, admins.size());
441 assertEquals(admin1, admins.get(0));
442 assertEquals(admin2, admins.get(1));
443
Sudheer Shanka101c3532018-01-08 16:28:42 -0800444 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
445 // replaced
446 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
447
Makoto Onukif76b06a2015-09-22 15:03:44 -0700448 // Another user has no admins.
449 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
450
451 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
452 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
453
454 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
455 }
456
Makoto Onukid932f762015-09-29 16:53:38 -0700457 public void testSetActiveAdmin_multiUsers() throws Exception {
458
459 final int ANOTHER_USER_ID = 100;
460 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
461
Pavel Grafov75c0a892017-05-18 17:28:27 +0100462 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700463
464 // Set up pacakge manager for the other user.
465 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700466
467 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
468
469 dpm.setActiveAdmin(admin1, /* replace =*/ false);
470
471 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
472 dpm.setActiveAdmin(admin2, /* replace =*/ false);
473
474
475 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
476 assertTrue(dpm.isAdminActive(admin1));
477 assertFalse(dpm.isAdminActive(admin2));
478
479 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
480 assertFalse(dpm.isAdminActive(admin1));
481 assertTrue(dpm.isAdminActive(admin2));
482 }
483
Makoto Onukif76b06a2015-09-22 15:03:44 -0700484 /**
485 * Test for:
486 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800487 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700488 */
489 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
490 // 1. Make sure the caller has proper permissions.
491 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
492
493 dpm.setActiveAdmin(admin1, /* replace =*/ false);
494 assertTrue(dpm.isAdminActive(admin1));
495
496 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100497 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
498 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700499 }
500
501 /**
502 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800503 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
504 * BIND_DEVICE_ADMIN.
505 */
506 public void testSetActiveAdmin_permissionCheck() throws Exception {
507 // 1. Make sure the caller has proper permissions.
508 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
509
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100510 assertExpectException(IllegalArgumentException.class,
511 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
512 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800513 assertFalse(dpm.isAdminActive(adminNoPerm));
514
515 // Change the target API level to MNC. Now it can be set as DA.
516 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
517 VERSION_CODES.M);
518 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
519 assertTrue(dpm.isAdminActive(adminNoPerm));
520
521 // TODO Test the "load from the file" case where DA will still be loaded even without
522 // BIND_DEVICE_ADMIN and target API is N.
523 }
524
525 /**
526 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700527 * {@link DevicePolicyManager#removeActiveAdmin}
528 */
529 public void testRemoveActiveAdmin_SecurityException() {
530 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
531
532 // Add admin.
533
534 dpm.setActiveAdmin(admin1, /* replace =*/ false);
535
536 assertTrue(dpm.isAdminActive(admin1));
537
538 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
539
540 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100541 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
542 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700543
544 // Try to remove active admin with a different caller userid should fail too, without
545 // having MANAGE_DEVICE_ADMINS.
546 mContext.callerPermissions.clear();
547
Makoto Onukid932f762015-09-29 16:53:38 -0700548 // Change the caller, and call into DPMS directly with a different user-id.
549
Makoto Onukif76b06a2015-09-22 15:03:44 -0700550 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100551 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
552 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700553 }
554
555 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800556 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
557 * (because we can't send the remove broadcast).
558 */
559 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
560 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
561
562 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
563
564 // Add admin.
565
566 dpm.setActiveAdmin(admin1, /* replace =*/ false);
567
568 assertTrue(dpm.isAdminActive(admin1));
569
570 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
571
572 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100573 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800574 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100575 assertExpectException(IllegalStateException.class,
576 /* messageRegex= */ "User must be running and unlocked",
577 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800578
579 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800580 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
581 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800582
583 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100584 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800585 .thenReturn(true);
586
587 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700588 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800589 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
590 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800591 }
592
593 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700594 * Test for:
595 * {@link DevicePolicyManager#removeActiveAdmin}
596 */
Makoto Onukid932f762015-09-29 16:53:38 -0700597 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700598 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
599
600 // Add admin1.
601
602 dpm.setActiveAdmin(admin1, /* replace =*/ false);
603
604 assertTrue(dpm.isAdminActive(admin1));
605 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
606
607 // Different user, but should work, because caller has proper permissions.
608 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700609
610 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700611 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700612
613 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700614 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800615 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
616 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700617
618 // TODO DO Still can't be removed in this case.
619 }
620
621 /**
622 * Test for:
623 * {@link DevicePolicyManager#removeActiveAdmin}
624 */
625 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
626 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
627 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
628
629 // Add admin1.
630
631 dpm.setActiveAdmin(admin1, /* replace =*/ false);
632
633 assertTrue(dpm.isAdminActive(admin1));
634 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
635
636 // Broadcast from saveSettingsLocked().
637 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
638 MockUtils.checkIntentAction(
639 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
640 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
641
642 // Remove. No permissions, but same user, so it'll work.
643 mContext.callerPermissions.clear();
644 dpm.removeActiveAdmin(admin1);
645
Makoto Onukif76b06a2015-09-22 15:03:44 -0700646 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
647 MockUtils.checkIntentAction(
648 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
649 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
650 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700651 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700652 eq(dpms.mHandler),
653 eq(Activity.RESULT_OK),
654 isNull(String.class),
655 isNull(Bundle.class));
656
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700657 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800658 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
659 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700660
661 // Again broadcast from saveSettingsLocked().
662 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
663 MockUtils.checkIntentAction(
664 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
665 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
666
667 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700668 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700669
Sudheer Shanka101c3532018-01-08 16:28:42 -0800670 public void testRemoveActiveAdmin_multipleAdminsInUser() {
671 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
672 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
673
674 // Add admin1.
675 dpm.setActiveAdmin(admin1, /* replace =*/ false);
676
677 assertTrue(dpm.isAdminActive(admin1));
678 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
679
680 // Add admin2.
681 dpm.setActiveAdmin(admin2, /* replace =*/ false);
682
683 assertTrue(dpm.isAdminActive(admin2));
684 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
685
686 // Broadcast from saveSettingsLocked().
687 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
688 MockUtils.checkIntentAction(
689 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
690 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
691
692 // Remove. No permissions, but same user, so it'll work.
693 mContext.callerPermissions.clear();
694 dpm.removeActiveAdmin(admin1);
695
696 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
697 MockUtils.checkIntentAction(
698 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
699 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
700 isNull(String.class),
701 any(BroadcastReceiver.class),
702 eq(dpms.mHandler),
703 eq(Activity.RESULT_OK),
704 isNull(String.class),
705 isNull(Bundle.class));
706
707 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
708 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800709 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800710 eq(DpmMockContext.CALLER_USER_HANDLE));
711
712 // Again broadcast from saveSettingsLocked().
713 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
714 MockUtils.checkIntentAction(
715 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
716 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
717 }
718
719 /**
720 * Test for:
721 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
722 */
723 public void testForceRemoveActiveAdmin() throws Exception {
724 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
725
726 // Add admin.
727 setupPackageInPackageManager(admin1.getPackageName(),
728 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
729 /* appId= */ 10138,
730 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
731 dpm.setActiveAdmin(admin1, /* replace =*/ false);
732 assertTrue(dpm.isAdminActive(admin1));
733
734 // Calling from a non-shell uid should fail with a SecurityException
735 mContext.binder.callingUid = 123456;
736 assertExpectException(SecurityException.class,
737 /* messageRegex =*/ "Non-shell user attempted to call",
738 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
739
740 mContext.binder.callingUid = Process.SHELL_UID;
741 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
742
743 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
744 // Verify
745 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
746 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
747 null, DpmMockContext.CALLER_USER_HANDLE);
748 }
749
Makoto Onukib643fb02015-09-22 15:03:44 -0700750 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000751 * Test for: @{link DevicePolicyManager#setActivePasswordState}
752 *
753 * Validates that when the password for a user changes, the notification broadcast intent
754 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
755 * addition to ones in the original user.
756 */
757 public void testSetActivePasswordState_sendToProfiles() throws Exception {
758 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
759
760 final int MANAGED_PROFILE_USER_ID = 78;
761 final int MANAGED_PROFILE_ADMIN_UID =
762 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
763
764 // Setup device owner.
765 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
766 mContext.packageName = admin1.getPackageName();
767 setupDeviceOwner();
768
769 // Add a managed profile belonging to the system user.
770 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
771
772 // Change the parent user's password.
773 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
774
775 // Both the device owner and the managed profile owner should receive this broadcast.
776 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
777 intent.setComponent(admin1);
778 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
779
780 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
781 MockUtils.checkIntent(intent),
782 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
783 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
784 MockUtils.checkIntent(intent),
785 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
786 }
787
788 /**
789 * Test for: @{link DevicePolicyManager#setActivePasswordState}
790 *
791 * Validates that when the password for a managed profile changes, the notification broadcast
792 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
793 * its parent.
794 */
795 public void testSetActivePasswordState_notSentToParent() throws Exception {
796 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
797
798 final int MANAGED_PROFILE_USER_ID = 78;
799 final int MANAGED_PROFILE_ADMIN_UID =
800 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
801
802 // Setup device owner.
803 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
804 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100805 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000806 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
807 setupDeviceOwner();
808
809 // Add a managed profile belonging to the system user.
810 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
811
812 // Change the profile's password.
813 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
814
815 // Both the device owner and the managed profile owner should receive this broadcast.
816 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
817 intent.setComponent(admin1);
818 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
819
820 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
821 MockUtils.checkIntent(intent),
822 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
823 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
824 MockUtils.checkIntent(intent),
825 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
826 }
827 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000828 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700829 */
830 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000831 setDeviceOwner();
832
833 // Try to set a profile owner on the same user, which should fail.
834 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
835 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100836 assertExpectException(IllegalStateException.class,
837 /* messageRegex= */ "already has a device owner",
838 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000839
840 // DO admin can't be deactivated.
841 dpm.removeActiveAdmin(admin1);
842 assertTrue(dpm.isAdminActive(admin1));
843
844 // TODO Test getDeviceOwnerName() too. To do so, we need to change
845 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
846 }
847
848 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700849 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800850 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700851 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
852 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
853
Makoto Onukid932f762015-09-29 16:53:38 -0700854 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700855 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
856
Makoto Onukid932f762015-09-29 16:53:38 -0700857 // Make sure admin1 is installed on system user.
858 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700859
Makoto Onukic8a5a552015-11-19 14:29:12 -0800860 // Check various get APIs.
861 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
862
Makoto Onukib643fb02015-09-22 15:03:44 -0700863 // DO needs to be an DA.
864 dpm.setActiveAdmin(admin1, /* replace =*/ false);
865
866 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700867 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700868
Makoto Onukic8a5a552015-11-19 14:29:12 -0800869 // getDeviceOwnerComponent should return the admin1 component.
870 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
871 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
872
873 // Check various get APIs.
874 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
875
876 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
877 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
878 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
879 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
880
881 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
882
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000883 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100884 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000885 eq(admin1.getPackageName()));
886
Makoto Onukib643fb02015-09-22 15:03:44 -0700887 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100888 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700889 eq(UserHandle.USER_SYSTEM), eq(false));
890
891 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
892 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
893 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
894
Makoto Onukic8a5a552015-11-19 14:29:12 -0800895 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700896 }
897
Makoto Onukic8a5a552015-11-19 14:29:12 -0800898 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
899 final int origCallingUser = mContext.binder.callingUid;
900 final List origPermissions = new ArrayList(mContext.callerPermissions);
901 mContext.callerPermissions.clear();
902
903 mContext.callerPermissions.add(permission.MANAGE_USERS);
904
905 mContext.binder.callingUid = Process.SYSTEM_UID;
906
907 // TODO Test getDeviceOwnerName() too. To do so, we need to change
908 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
909 if (hasDeviceOwner) {
910 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
911 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
912 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
913
914 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
915 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
916 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
917 } else {
918 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
919 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
920 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
921
922 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
923 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
924 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
925 }
926
927 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
928 if (hasDeviceOwner) {
929 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
930 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
931 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
932
933 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
934 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
935 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
936 } else {
937 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
938 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
939 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
940
941 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
942 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
943 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
944 }
945
946 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
947 // Still with MANAGE_USERS.
948 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
949 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
950 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
951
952 if (hasDeviceOwner) {
953 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
954 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
955 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
956 } else {
957 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
958 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
959 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
960 }
961
962 mContext.binder.callingUid = Process.SYSTEM_UID;
963 mContext.callerPermissions.remove(permission.MANAGE_USERS);
964 // System can still call "OnAnyUser" without MANAGE_USERS.
965 if (hasDeviceOwner) {
966 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
967 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
968 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
969
970 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
971 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
972 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
973 } else {
974 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
975 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
976 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
977
978 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
979 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
980 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
981 }
982
983 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
984 // Still no MANAGE_USERS.
985 if (hasDeviceOwner) {
986 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
987 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
988 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
989 } else {
990 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
991 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
992 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
993 }
994
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100995 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
996 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
997 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
998 dpm::getDeviceOwnerComponentOnAnyUser);
999 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1000 dpm::getDeviceOwnerUserId);
1001 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1002 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001003
1004 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1005 // Still no MANAGE_USERS.
1006 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1007 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1008 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1009
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001010 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1011 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1012 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1013 dpm::getDeviceOwnerComponentOnAnyUser);
1014 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1015 dpm::getDeviceOwnerUserId);
1016 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1017 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001018
1019 // Restore.
1020 mContext.binder.callingUid = origCallingUser;
1021 mContext.callerPermissions.addAll(origPermissions);
1022 }
1023
1024
Makoto Onukib643fb02015-09-22 15:03:44 -07001025 /**
1026 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1027 */
1028 public void testSetDeviceOwner_noSuchPackage() {
1029 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001030 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001031 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1032 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1033
1034 // Call from a process on the system user.
1035 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1036
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001037 assertExpectException(IllegalArgumentException.class,
1038 /* messageRegex= */ "Invalid component",
1039 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001040 }
1041
1042 public void testSetDeviceOwner_failures() throws Exception {
1043 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1044 }
1045
Makoto Onukia52562c2015-10-01 16:12:31 -07001046 public void testClearDeviceOwner() throws Exception {
1047 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001048 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001049 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1050 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1051
1052 // Set admin1 as a DA to the secondary user.
1053 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1054
1055 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1056
1057 // Set admin 1 as the DO to the system user.
1058
1059 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1060 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1061 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1062 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1063
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001064 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001065 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001066 eq(admin1.getPackageName()));
1067
Makoto Onukic8a5a552015-11-19 14:29:12 -08001068 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001069
Makoto Onuki90b89652016-01-28 14:44:18 -08001070 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001071 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001072 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001073
1074 assertTrue(dpm.isAdminActive(admin1));
1075 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1076
Makoto Onukia52562c2015-10-01 16:12:31 -07001077 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001078 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001079
1080 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001081 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1082 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001083
1084 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001085 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001086 assertExpectException(IllegalStateException.class,
1087 /* messageRegex= */ "User must be running and unlocked",
1088 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001089
Pavel Grafov75c0a892017-05-18 17:28:27 +01001090 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1091 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001092 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1093
1094 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001095 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001096
Pavel Grafov75c0a892017-05-18 17:28:27 +01001097 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001098 eq(false),
1099 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1100
Pavel Grafov75c0a892017-05-18 17:28:27 +01001101 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001102 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001103 eq(null),
1104 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001105
Sudheer Shanka101c3532018-01-08 16:28:42 -08001106 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1107 null, UserHandle.USER_SYSTEM);
1108
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001109 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001110
1111 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1112 // and once for clearing it.
1113 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1114 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1115 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001116 // TODO Check other calls.
1117 }
1118
1119 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1120 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001121 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001122 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1123 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1124
1125 // Set admin1 as a DA to the secondary user.
1126 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1127
1128 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1129
1130 // Set admin 1 as the DO to the system user.
1131
1132 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1133 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1134 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1135 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1136
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001137 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001138 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001139 eq(admin1.getPackageName()));
1140
Makoto Onukic8a5a552015-11-19 14:29:12 -08001141 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001142
1143 // Now call clear from the secondary user, which should throw.
1144 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1145
1146 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001147 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001148 eq(admin1.getPackageName()),
1149 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001150 assertExpectException(SecurityException.class,
1151 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1152 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001153
Makoto Onukic8a5a552015-11-19 14:29:12 -08001154 // DO shouldn't be removed.
1155 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001156 }
1157
Makoto Onukib643fb02015-09-22 15:03:44 -07001158 public void testSetProfileOwner() throws Exception {
1159 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001160
Makoto Onuki90b89652016-01-28 14:44:18 -08001161 // PO admin can't be deactivated.
1162 dpm.removeActiveAdmin(admin1);
1163 assertTrue(dpm.isAdminActive(admin1));
1164
Makoto Onuki803d6752015-10-30 12:58:39 -07001165 // Try setting DO on the same user, which should fail.
1166 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001167 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1168 runAsCaller(mServiceContext, dpms, dpm -> {
1169 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001170 assertExpectException(IllegalStateException.class,
1171 /* messageRegex= */ "already has a profile owner",
1172 () -> dpm.setDeviceOwner(admin2, "owner-name",
1173 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001174 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001175 }
1176
Makoto Onuki90b89652016-01-28 14:44:18 -08001177 public void testClearProfileOwner() throws Exception {
1178 setAsProfileOwner(admin1);
1179
1180 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1181
1182 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1183 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1184
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001185 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001186 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001187 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001188 assertExpectException(IllegalStateException.class,
1189 /* messageRegex= */ "User must be running and unlocked",
1190 () -> dpm.clearProfileOwner(admin1));
1191
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001192 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001193 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001194 dpm.clearProfileOwner(admin1);
1195
1196 // Check
1197 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001198 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001199 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1200 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001201 }
1202
Makoto Onukib643fb02015-09-22 15:03:44 -07001203 public void testSetProfileOwner_failures() throws Exception {
1204 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1205 }
1206
Makoto Onukia52562c2015-10-01 16:12:31 -07001207 public void testGetDeviceOwnerAdminLocked() throws Exception {
1208 checkDeviceOwnerWithMultipleDeviceAdmins();
1209 }
1210
1211 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1212 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1213 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1214 // make sure it gets the right component from the right user.
1215
1216 final int ANOTHER_USER_ID = 100;
1217 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1218
Pavel Grafov75c0a892017-05-18 17:28:27 +01001219 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001220
1221 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001222 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001223 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1224 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1225
1226 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1227
Pavel Grafov75c0a892017-05-18 17:28:27 +01001228 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001229
Makoto Onukia52562c2015-10-01 16:12:31 -07001230 // Make sure the admin packge is installed to each user.
1231 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1232 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1233
1234 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1235 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1236
1237 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1238
1239
1240 // Set active admins to the users.
1241 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1242 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1243
1244 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1245 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1246
1247 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1248
1249 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001250 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001251 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1252
Makoto Onukic8a5a552015-11-19 14:29:12 -08001253 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001254
1255 // Then check getDeviceOwnerAdminLocked().
1256 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1257 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1258 }
1259
1260 /**
1261 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001262 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1263 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001264 *
1265 * We didn't use to persist the DO component class name, but now we do, and the above method
1266 * finds the right component from a package name upon migration.
1267 */
1268 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001269 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001270 checkDeviceOwnerWithMultipleDeviceAdmins();
1271
1272 // Overwrite the device owner setting and clears the clas name.
1273 dpms.mOwners.setDeviceOwner(
1274 new ComponentName(admin2.getPackageName(), ""),
1275 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1276 dpms.mOwners.writeDeviceOwner();
1277
1278 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001279 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001280
1281 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001282 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001283 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001284 initializeDpms();
1285
1286 // Now the DO component name is a full name.
1287 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1288 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001289 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001290 }
1291
Makoto Onukib643fb02015-09-22 15:03:44 -07001292 public void testSetGetApplicationRestriction() {
1293 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001294 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001295
1296 {
1297 Bundle rest = new Bundle();
1298 rest.putString("KEY_STRING", "Foo1");
1299 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1300 }
1301
1302 {
1303 Bundle rest = new Bundle();
1304 rest.putString("KEY_STRING", "Foo2");
1305 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1306 }
1307
1308 {
1309 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1310 assertNotNull(returned);
1311 assertEquals(returned.size(), 1);
1312 assertEquals(returned.get("KEY_STRING"), "Foo1");
1313 }
1314
1315 {
1316 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1317 assertNotNull(returned);
1318 assertEquals(returned.size(), 1);
1319 assertEquals(returned.get("KEY_STRING"), "Foo2");
1320 }
1321
1322 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1323 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1324 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001325
Edman Anjosf9946772016-11-28 16:35:15 +01001326 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001327 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1328 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001329 *
1330 * @param packageName the name of the package to be setup
1331 * @param appId the application ID to be given to the package
1332 * @return the UID of the package as known by the mock package manager
1333 */
1334 private int setupPackageInPackageManager(final String packageName, final int appId)
1335 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001336 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001337 ApplicationInfo.FLAG_HAS_CODE);
1338 }
1339
1340 /**
1341 * Setup a package in the package manager mock. Useful for faking installed applications.
1342 *
1343 * @param packageName the name of the package to be setup
1344 * @param userId the user id where the package will be "installed"
1345 * @param appId the application ID to be given to the package
1346 * @param flags flags to set in the ApplicationInfo for this package
1347 * @return the UID of the package as known by the mock package manager
1348 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001349 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1350 int flags) throws Exception {
1351 final int uid = UserHandle.getUid(userId, appId);
1352 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001353 final PackageInfo pi = new PackageInfo();
1354 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001355 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001356 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001357 eq(packageName),
1358 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001359 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001360 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001361 eq(packageName),
1362 anyInt(),
1363 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001364 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001365 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001366 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001367 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001368 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001369 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001370 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001371 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001372 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001373 return uid;
1374 }
1375
Robin Lee7f5c91c2017-02-08 21:27:02 +00001376 public void testCertificateDisclosure() throws Exception {
1377 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1378 final UserHandle user = UserHandle.of(userId);
1379
1380 mContext.applicationInfo = new ApplicationInfo();
1381 mContext.callerPermissions.add(permission.MANAGE_USERS);
1382 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001383 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001384 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1385
Robin Leeabaa0692017-02-20 20:54:22 +00001386 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1387 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001388
1389 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1390 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1391
1392 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001393 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001394 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001395 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001396 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001397 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001398 .cancelAsUser(anyString(), anyInt(), eq(user));
1399
1400 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001401 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001402 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001403 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1404 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001405 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001406 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001407 .notifyAsUser(anyString(), anyInt(), argThat(
1408 new BaseMatcher<Notification>() {
1409 @Override
1410 public boolean matches(Object item) {
1411 final Notification noti = (Notification) item;
1412 return TEST_STRING.equals(
1413 noti.extras.getString(Notification.EXTRA_TITLE));
1414 }
1415 @Override
1416 public void describeTo(Description description) {
1417 description.appendText(
1418 "Notification{title=\"" + TEST_STRING + "\"}");
1419 }
1420 }), eq(user));
1421 }
1422
Edman Anjosf9946772016-11-28 16:35:15 +01001423 /**
1424 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1425 * privileges can acually be exercised by a delegate are not covered here.
1426 */
1427 public void testDelegation() throws Exception {
1428 setAsProfileOwner(admin1);
1429
1430 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1431
1432 // Given two packages
1433 final String CERT_DELEGATE = "com.delegate.certs";
1434 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1435 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1436 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1437 20989);
1438
1439 // On delegation
1440 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1441 mContext.packageName = admin1.getPackageName();
1442 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1443 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1444
1445 // DPMS correctly stores and retrieves the delegates
1446 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1447 assertEquals(2, policy.mDelegationMap.size());
1448 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1449 DELEGATION_CERT_INSTALL);
1450 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1451 DELEGATION_CERT_INSTALL);
1452 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1453 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1454 DELEGATION_APP_RESTRICTIONS);
1455 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1456 DELEGATION_APP_RESTRICTIONS);
1457 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1458
1459 // On calling install certificate APIs from an unauthorized process
1460 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1461 mContext.packageName = RESTRICTIONS_DELEGATE;
1462
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001463 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1464 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001465
1466 // On calling install certificate APIs from an authorized process
1467 mContext.binder.callingUid = CERT_DELEGATE_UID;
1468 mContext.packageName = CERT_DELEGATE;
1469
1470 // DPMS executes without a SecurityException
1471 try {
1472 dpm.installCaCert(null, null);
1473 } catch (SecurityException unexpected) {
1474 fail("Threw SecurityException on authorized access");
1475 } catch (NullPointerException expected) {
1476 }
1477
1478 // On removing a delegate
1479 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1480 mContext.packageName = admin1.getPackageName();
1481 dpm.setCertInstallerPackage(admin1, null);
1482
1483 // DPMS does not allow access to ex-delegate
1484 mContext.binder.callingUid = CERT_DELEGATE_UID;
1485 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001486 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1487 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001488
1489 // But still allows access to other existing delegates
1490 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1491 mContext.packageName = RESTRICTIONS_DELEGATE;
1492 try {
1493 dpm.getApplicationRestrictions(null, "pkg");
1494 } catch (SecurityException expected) {
1495 fail("Threw SecurityException on authorized access");
1496 }
1497 }
1498
Esteban Talaverabf60f722015-12-10 16:26:44 +00001499 public void testApplicationRestrictionsManagingApp() throws Exception {
1500 setAsProfileOwner(admin1);
1501
Rubin Xued1928a2016-02-11 17:23:06 +00001502 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001503 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001504 final String nonDelegateExceptionMessageRegex =
1505 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001506 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001507 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1508 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001509
Esteban Talaverabf60f722015-12-10 16:26:44 +00001510 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1511 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001512 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1513 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001514 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001515 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001516 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001517 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1518 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001519
1520 // Check via the profile owner that no restrictions were set.
1521 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001522 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001523 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1524
Rubin Xued1928a2016-02-11 17:23:06 +00001525 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001526 assertExpectException(PackageManager.NameNotFoundException.class,
1527 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1528 () -> dpm.setApplicationRestrictionsManagingPackage(
1529 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001530
Esteban Talaverabf60f722015-12-10 16:26:44 +00001531 // Let appRestrictionsManagerPackage manage app restrictions
1532 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1533 assertEquals(appRestrictionsManagerPackage,
1534 dpm.getApplicationRestrictionsManagingPackage(admin1));
1535
1536 // Now that package should be able to set and retrieve app restrictions.
1537 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001538 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001539 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1540 dpm.setApplicationRestrictions(null, "pkg1", rest);
1541 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1542 assertEquals(1, returned.size(), 1);
1543 assertEquals("Foo1", returned.get("KEY_STRING"));
1544
1545 // The same app running on a separate user shouldn't be able to manage app restrictions.
1546 mContext.binder.callingUid = UserHandle.getUid(
1547 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1548 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001549 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1550 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001551
1552 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1553 // too.
1554 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001555 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001556 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1557 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1558 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1559
1560 // Removing the ability for the package to manage app restrictions.
1561 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1562 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1563 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001564 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001565 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001566 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1567 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001568 }
1569
Makoto Onukia4f11972015-10-01 13:19:58 -07001570 public void testSetUserRestriction_asDo() throws Exception {
1571 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001572 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001573 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1574 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1575
1576 // First, set DO.
1577
1578 // Call from a process on the system user.
1579 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1580
1581 // Make sure admin1 is installed on system user.
1582 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001583
1584 // Call.
1585 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001586 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001587 UserHandle.USER_SYSTEM));
1588
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001589 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001590 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001591 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001592 DpmTestUtils.assertRestrictions(
1593 DpmTestUtils.newRestrictions(defaultRestrictions),
1594 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1595 );
1596 DpmTestUtils.assertRestrictions(
1597 DpmTestUtils.newRestrictions(defaultRestrictions),
1598 dpm.getUserRestrictions(admin1)
1599 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001600 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001601 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001602 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001603 eq(true) /* isDeviceOwner */,
1604 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001605 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001606 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001607
1608 for (String restriction : defaultRestrictions) {
1609 dpm.clearUserRestriction(admin1, restriction);
1610 }
1611
Esteban Talavera548a04b2016-12-20 15:22:30 +00001612 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001613 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001614
1615 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001616 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001617 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001618 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1619 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001620 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001621
Makoto Onukia4f11972015-10-01 13:19:58 -07001622 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001623 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001624 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001625 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1626 UserManager.DISALLOW_ADD_USER),
1627 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001628 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001629
Makoto Onuki068c54a2015-10-13 14:34:03 -07001630 DpmTestUtils.assertRestrictions(
1631 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001632 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001633 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1634 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001635 DpmTestUtils.assertRestrictions(
1636 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001637 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001638 dpm.getUserRestrictions(admin1)
1639 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001640
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001641 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001642 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001643 eq(UserHandle.USER_SYSTEM),
1644 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001645 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001646 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001647
Makoto Onuki068c54a2015-10-13 14:34:03 -07001648 DpmTestUtils.assertRestrictions(
1649 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1650 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1651 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001652 DpmTestUtils.assertRestrictions(
1653 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1654 dpm.getUserRestrictions(admin1)
1655 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001656
1657 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001658 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001659 eq(UserHandle.USER_SYSTEM),
1660 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001661 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001662 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001663
Esteban Talavera548a04b2016-12-20 15:22:30 +00001664 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001665
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001666 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1667 // DO sets them, the scope is global.
1668 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001669 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001670 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001671 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001672 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001673 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001674 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1675 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001676 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001677
1678 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1679 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001680 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681
1682 // More tests.
1683 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001684 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001685 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001686 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1687 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001688 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689
1690 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001691 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001692 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001693 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001694 UserManager.DISALLOW_ADD_USER),
1695 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001696 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001697
1698 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001699 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 eq(UserHandle.USER_SYSTEM),
1701 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001702 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001703 UserManager.DISALLOW_ADD_USER),
1704 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001705 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706
1707 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1708 // locally.
1709 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001710 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001711
1712 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1713 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1714 dpm.setCameraDisabled(admin2, true);
1715
Pavel Grafov75c0a892017-05-18 17:28:27 +01001716 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001717 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001718 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001719 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001720 UserManager.DISALLOW_ADD_USER),
1721 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001722 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001723 // TODO Make sure restrictions are written to the file.
1724 }
1725
1726 public void testSetUserRestriction_asPo() {
1727 setAsProfileOwner(admin1);
1728
Makoto Onuki068c54a2015-10-13 14:34:03 -07001729 DpmTestUtils.assertRestrictions(
1730 DpmTestUtils.newRestrictions(),
1731 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1732 .ensureUserRestrictions()
1733 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001734
1735 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001736 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001737 eq(DpmMockContext.CALLER_USER_HANDLE),
1738 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001739 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001740 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001741
Makoto Onukia4f11972015-10-01 13:19:58 -07001742 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001743 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001744 eq(DpmMockContext.CALLER_USER_HANDLE),
1745 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1746 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001747 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001748 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001749
Makoto Onuki068c54a2015-10-13 14:34:03 -07001750 DpmTestUtils.assertRestrictions(
1751 DpmTestUtils.newRestrictions(
1752 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1753 UserManager.DISALLOW_OUTGOING_CALLS
1754 ),
1755 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1756 .ensureUserRestrictions()
1757 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001758 DpmTestUtils.assertRestrictions(
1759 DpmTestUtils.newRestrictions(
1760 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1761 UserManager.DISALLOW_OUTGOING_CALLS
1762 ),
1763 dpm.getUserRestrictions(admin1)
1764 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001765
1766 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001767 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001768 eq(DpmMockContext.CALLER_USER_HANDLE),
1769 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001770 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001771 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001772
1773 DpmTestUtils.assertRestrictions(
1774 DpmTestUtils.newRestrictions(
1775 UserManager.DISALLOW_OUTGOING_CALLS
1776 ),
1777 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1778 .ensureUserRestrictions()
1779 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001780 DpmTestUtils.assertRestrictions(
1781 DpmTestUtils.newRestrictions(
1782 UserManager.DISALLOW_OUTGOING_CALLS
1783 ),
1784 dpm.getUserRestrictions(admin1)
1785 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001786
1787 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001788 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001789 eq(DpmMockContext.CALLER_USER_HANDLE),
1790 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001791 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001792 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001793
Makoto Onuki068c54a2015-10-13 14:34:03 -07001794 DpmTestUtils.assertRestrictions(
1795 DpmTestUtils.newRestrictions(),
1796 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1797 .ensureUserRestrictions()
1798 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001799 DpmTestUtils.assertRestrictions(
1800 DpmTestUtils.newRestrictions(),
1801 dpm.getUserRestrictions(admin1)
1802 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001803
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001804 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1805 // though when DO sets them they'll be applied globally.
1806 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001807 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001808 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001809 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001810 eq(DpmMockContext.CALLER_USER_HANDLE),
1811 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1812 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001813 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001814 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001815
1816 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001817 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001818 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001819 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001820 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001821 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001822 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001823
Makoto Onukia4f11972015-10-01 13:19:58 -07001824 // TODO Make sure restrictions are written to the file.
1825 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001826
Esteban Talavera548a04b2016-12-20 15:22:30 +00001827
1828 public void testDefaultEnabledUserRestrictions() throws Exception {
1829 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1830 mContext.callerPermissions.add(permission.MANAGE_USERS);
1831 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1832 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1833
1834 // First, set DO.
1835
1836 // Call from a process on the system user.
1837 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1838
1839 // Make sure admin1 is installed on system user.
1840 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1841
1842 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1843 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1844 UserHandle.USER_SYSTEM));
1845
1846 // Check that the user restrictions that are enabled by default are set. Then unset them.
1847 String[] defaultRestrictions = UserRestrictionsUtils
1848 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1849 assertTrue(defaultRestrictions.length > 0);
1850 DpmTestUtils.assertRestrictions(
1851 DpmTestUtils.newRestrictions(defaultRestrictions),
1852 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1853 );
1854 DpmTestUtils.assertRestrictions(
1855 DpmTestUtils.newRestrictions(defaultRestrictions),
1856 dpm.getUserRestrictions(admin1)
1857 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001858 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001859 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001860 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001861 eq(true) /* isDeviceOwner */,
1862 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001863 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001864 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001865
1866 for (String restriction : defaultRestrictions) {
1867 dpm.clearUserRestriction(admin1, restriction);
1868 }
1869
1870 assertNoDeviceOwnerRestrictions();
1871
1872 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001873 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001874 initializeDpms();
1875 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1876 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1877
1878 assertNoDeviceOwnerRestrictions();
1879
1880 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1881 // is set as it wasn't enabled during setDeviceOwner.
1882 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1883 assertFalse(UserRestrictionsUtils
1884 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1885 UserRestrictionsUtils
1886 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1887 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001888 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001889 initializeDpms();
1890 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1891 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1892
1893 DpmTestUtils.assertRestrictions(
1894 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1895 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1896 );
1897 DpmTestUtils.assertRestrictions(
1898 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1899 dpm.getUserRestrictions(admin1)
1900 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001901 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001902 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001903 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001904 eq(true) /* isDeviceOwner */,
1905 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001906 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001907 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001908
1909 // Remove the restriction.
1910 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1911
1912 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1913 initializeDpms();
1914 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1915 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1916 assertNoDeviceOwnerRestrictions();
1917 } finally {
1918 UserRestrictionsUtils
1919 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1920 }
1921 }
1922
1923 private void assertNoDeviceOwnerRestrictions() {
1924 DpmTestUtils.assertRestrictions(
1925 DpmTestUtils.newRestrictions(),
1926 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1927 );
1928 DpmTestUtils.assertRestrictions(
1929 DpmTestUtils.newRestrictions(),
1930 dpm.getUserRestrictions(admin1)
1931 );
1932 }
1933
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001934 public void testGetMacAddress() throws Exception {
1935 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1936 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1937 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1938
1939 // In this test, change the caller user to "system".
1940 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1941
1942 // Make sure admin1 is installed on system user.
1943 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1944
1945 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001946 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1947 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001948
1949 // DO needs to be an DA.
1950 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1951 assertTrue(dpm.isAdminActive(admin1));
1952
1953 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001954 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1955 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001956
1957 // Test 3. Caller has PO, but not DO.
1958 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001959 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1960 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001961
1962 // Remove PO.
1963 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001964 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001965 // Test 4, Caller is DO now.
1966 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1967
1968 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001969 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001970
1971 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001972 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001973 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001974
1975 // 4-3. With a real MAC address.
1976 final WifiInfo wi = new WifiInfo();
1977 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001978 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001979 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001980 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001981
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001982 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001983 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1984 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1985
1986 // In this test, change the caller user to "system".
1987 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1988
1989 // Make sure admin1 is installed on system user.
1990 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1991
1992 // Set admin1 as DA.
1993 dpm.setActiveAdmin(admin1, false);
1994 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001995 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1996 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001997
1998 // Set admin1 as PO.
1999 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002000 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2001 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002002
2003 // Remove PO and add DO.
2004 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002005 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002006 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2007
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002008 // admin1 is DO.
2009 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002010 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002011 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002012 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2013 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002014
2015 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002016 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002017 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002018 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2019 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002020
2021 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002022 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002023 dpm.reboot(admin1);
2024 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002025
2026 public void testSetGetSupportText() {
2027 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2028 dpm.setActiveAdmin(admin1, true);
2029 dpm.setActiveAdmin(admin2, true);
2030 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2031
2032 // Null default support messages.
2033 {
2034 assertNull(dpm.getLongSupportMessage(admin1));
2035 assertNull(dpm.getShortSupportMessage(admin1));
2036 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2037 assertNull(dpm.getShortSupportMessageForUser(admin1,
2038 DpmMockContext.CALLER_USER_HANDLE));
2039 assertNull(dpm.getLongSupportMessageForUser(admin1,
2040 DpmMockContext.CALLER_USER_HANDLE));
2041 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2042 }
2043
2044 // Only system can call the per user versions.
2045 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002046 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2047 () -> dpm.getShortSupportMessageForUser(admin1,
2048 DpmMockContext.CALLER_USER_HANDLE));
2049 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2050 () -> dpm.getLongSupportMessageForUser(admin1,
2051 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002052 }
2053
2054 // Can't set message for admin in another uid.
2055 {
2056 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002057 assertExpectException(SecurityException.class,
2058 /* messageRegex= */ "is not owned by uid",
2059 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002060 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2061 }
2062
2063 // Set/Get short returns what it sets and other admins text isn't changed.
2064 {
2065 final String supportText = "Some text to test with.";
2066 dpm.setShortSupportMessage(admin1, supportText);
2067 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2068 assertNull(dpm.getLongSupportMessage(admin1));
2069 assertNull(dpm.getShortSupportMessage(admin2));
2070
2071 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2072 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2073 DpmMockContext.CALLER_USER_HANDLE));
2074 assertNull(dpm.getShortSupportMessageForUser(admin2,
2075 DpmMockContext.CALLER_USER_HANDLE));
2076 assertNull(dpm.getLongSupportMessageForUser(admin1,
2077 DpmMockContext.CALLER_USER_HANDLE));
2078 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2079
2080 dpm.setShortSupportMessage(admin1, null);
2081 assertNull(dpm.getShortSupportMessage(admin1));
2082 }
2083
2084 // Set/Get long returns what it sets and other admins text isn't changed.
2085 {
2086 final String supportText = "Some text to test with.\nWith more text.";
2087 dpm.setLongSupportMessage(admin1, supportText);
2088 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2089 assertNull(dpm.getShortSupportMessage(admin1));
2090 assertNull(dpm.getLongSupportMessage(admin2));
2091
2092 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2093 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2094 DpmMockContext.CALLER_USER_HANDLE));
2095 assertNull(dpm.getLongSupportMessageForUser(admin2,
2096 DpmMockContext.CALLER_USER_HANDLE));
2097 assertNull(dpm.getShortSupportMessageForUser(admin1,
2098 DpmMockContext.CALLER_USER_HANDLE));
2099 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2100
2101 dpm.setLongSupportMessage(admin1, null);
2102 assertNull(dpm.getLongSupportMessage(admin1));
2103 }
2104 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002105
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002106 public void testSetGetMeteredDataDisabled() throws Exception {
2107 setAsProfileOwner(admin1);
2108
2109 final ArrayList<String> emptyList = new ArrayList<>();
2110 assertEquals(emptyList, dpm.getMeteredDataDisabled(admin1));
2111
2112 // Setup
2113 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2114 final String package1 = "com.example.one";
2115 final String package2 = "com.example.two";
2116 pkgsToRestrict.add(package1);
2117 pkgsToRestrict.add(package2);
2118 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2119 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
2120 List<String> excludedPkgs = dpm.setMeteredDataDisabled(admin1, pkgsToRestrict);
2121
2122 // Verify
2123 assertEquals(emptyList, excludedPkgs);
2124 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabled(admin1));
2125 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2126 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2127 eq(DpmMockContext.CALLER_USER_HANDLE));
2128
2129 // Setup
2130 pkgsToRestrict.remove(package1);
2131 excludedPkgs = dpm.setMeteredDataDisabled(admin1, pkgsToRestrict);
2132
2133 // Verify
2134 assertEquals(emptyList, excludedPkgs);
2135 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabled(admin1));
2136 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2137 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2138 eq(DpmMockContext.CALLER_USER_HANDLE));
2139 }
2140
2141 public void testSetGetMeteredDataDisabled_deviceAdmin() {
2142 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2143 dpm.setActiveAdmin(admin1, true);
2144 assertTrue(dpm.isAdminActive(admin1));
2145 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2146
2147 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
2148 () -> dpm.setMeteredDataDisabled(admin1, new ArrayList<>()));
2149 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
2150 () -> dpm.getMeteredDataDisabled(admin1));
2151 }
2152
phweiss73145f42017-01-17 19:06:38 +01002153 public void testCreateAdminSupportIntent() throws Exception {
2154 // Setup device owner.
2155 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2156 setupDeviceOwner();
2157
2158 // Nonexisting permission returns null
2159 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2160 assertNull(intent);
2161
2162 // Existing permission that is not set returns null
2163 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2164 assertNull(intent);
2165
2166 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002167 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002168 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2169 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2170 .thenReturn(true);
2171 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2172 assertNull(intent);
2173
2174 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002175 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002176 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2177 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2178 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2179 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2180 assertNotNull(intent);
2181 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2182 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2183 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002184 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002185 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2186 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2187
2188 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2189 // user restrictions
2190
2191 // Camera is not disabled
2192 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2193 assertNull(intent);
2194
2195 // Camera is disabled
2196 dpm.setCameraDisabled(admin1, true);
2197 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2198 assertNotNull(intent);
2199 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2200 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2201
2202 // Screen capture is not disabled
2203 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2204 assertNull(intent);
2205
2206 // Screen capture is disabled
2207 dpm.setScreenCaptureDisabled(admin1, true);
2208 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2209 assertNotNull(intent);
2210 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2211 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2212
2213 // Same checks for different user
2214 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2215 // Camera should be disabled by device owner
2216 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2217 assertNotNull(intent);
2218 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2219 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2220 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2221 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2222 // ScreenCapture should not be disabled by device owner
2223 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2224 assertNull(intent);
2225 }
2226
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002227 /**
2228 * Test for:
2229 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002230 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002231 * {@link DevicePolicyManager#isAffiliatedUser}
2232 */
2233 public void testUserAffiliation() throws Exception {
2234 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2235 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2236 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2237
2238 // Check that the system user is unaffiliated.
2239 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2240 assertFalse(dpm.isAffiliatedUser());
2241
2242 // Set a device owner on the system user. Check that the system user becomes affiliated.
2243 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2244 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2245 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2246 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002247 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002248
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002249 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002250 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2251 setAsProfileOwner(admin2);
2252 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002253 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002254
2255 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2256 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002257 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002258 userAffiliationIds.add("red");
2259 userAffiliationIds.add("green");
2260 userAffiliationIds.add("blue");
2261 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002262 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002263 assertFalse(dpm.isAffiliatedUser());
2264
2265 // Have the device owner specify a set of affiliation ids that do not intersect with those
2266 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002267 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002268 deviceAffiliationIds.add("cyan");
2269 deviceAffiliationIds.add("yellow");
2270 deviceAffiliationIds.add("magenta");
2271 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2272 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002273 MoreAsserts.assertContentsInAnyOrder(
2274 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002275 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2276 assertFalse(dpm.isAffiliatedUser());
2277
2278 // Have the profile owner specify a set of affiliation ids that intersect with those
2279 // specified by the device owner. Check that the test user becomes affiliated.
2280 userAffiliationIds.add("yellow");
2281 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002282 MoreAsserts.assertContentsInAnyOrder(
2283 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002284 assertTrue(dpm.isAffiliatedUser());
2285
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002286 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002287 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002288 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002289 assertFalse(dpm.isAffiliatedUser());
2290
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002291 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2292 dpm.setAffiliationIds(admin2, userAffiliationIds);
2293 assertTrue(dpm.isAffiliatedUser());
2294 dpm.clearProfileOwner(admin2);
2295 assertFalse(dpm.isAffiliatedUser());
2296
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002297 // Check that the system user remains affiliated.
2298 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2299 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002300
2301 // Clear the device owner - the user becomes unaffiliated.
2302 clearDeviceOwner();
2303 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002304 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002305
2306 public void testGetUserProvisioningState_defaultResult() {
2307 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2308 }
2309
2310 public void testSetUserProvisioningState_permission() throws Exception {
2311 setupProfileOwner();
2312 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2313
2314 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2315 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2316 }
2317
2318 public void testSetUserProvisioningState_unprivileged() throws Exception {
2319 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002320 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2321 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2322 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002323 }
2324
2325 public void testSetUserProvisioningState_noManagement() {
2326 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002327 assertExpectException(IllegalStateException.class,
2328 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2329 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2330 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002331 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2332 }
2333
2334 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2335 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2336 setupDeviceOwner();
2337 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2338
2339 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2340 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2341 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2342 }
2343
2344 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2345 throws Exception {
2346 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2347 setupDeviceOwner();
2348 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2349
2350 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2351 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2352 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2353 }
2354
2355 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2356 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2357 setupDeviceOwner();
2358 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2359
2360 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2361 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2362 }
2363
2364 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2365 throws Exception {
2366 setupProfileOwner();
2367 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2368
2369 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2370 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2371 DevicePolicyManager.STATE_USER_UNMANAGED);
2372 }
2373
2374 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2375 throws Exception {
2376 setupProfileOwner();
2377 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2378
2379 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2380 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2381 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2382 }
2383
2384 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2385 setupProfileOwner();
2386 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2387
2388 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2389 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2390 }
2391
2392 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2393 setupProfileOwner();
2394 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2395
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002396 assertExpectException(IllegalStateException.class,
2397 /* messageRegex= */ "Cannot move to user provisioning state",
2398 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2399 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2400 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002401 }
2402
2403 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2404 throws Exception {
2405 setupProfileOwner();
2406 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2407
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002408 assertExpectException(IllegalStateException.class,
2409 /* messageRegex= */ "Cannot move to user provisioning state",
2410 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2411 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2412 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002413 }
2414
2415 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2416 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2417 for (int state : states) {
2418 dpm.setUserProvisioningState(state, userId);
2419 assertEquals(state, dpm.getUserProvisioningState());
2420 }
2421 }
2422
2423 private void setupProfileOwner() throws Exception {
2424 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2425
2426 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2427 dpm.setActiveAdmin(admin1, false);
2428 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2429
2430 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2431 }
2432
2433 private void setupDeviceOwner() throws Exception {
2434 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2435
2436 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2437 dpm.setActiveAdmin(admin1, false);
2438 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2439
2440 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2441 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002442
2443 public void testSetMaximumTimeToLock() {
2444 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2445
2446 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2447 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2448
Pavel Grafov75c0a892017-05-18 17:28:27 +01002449 reset(getServices().powerManagerInternal);
2450 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002451
2452 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002453 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2454 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002455 reset(getServices().powerManagerInternal);
2456 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002457
2458 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002459 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2460 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002461 reset(getServices().powerManagerInternal);
2462 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002463
2464 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002465 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2466 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002467 reset(getServices().powerManagerInternal);
2468 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002469
2470 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002471 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2472 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002473 reset(getServices().powerManagerInternal);
2474 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002475
2476 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002477 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2478 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002479 reset(getServices().powerManagerInternal);
2480 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002481
2482 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002483 reset(getServices().powerManagerInternal);
2484 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002485
Pavel Grafov28939982017-10-03 15:11:52 +01002486 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2487 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2488 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002489 reset(getServices().powerManagerInternal);
2490 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002491
2492 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002493 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2494 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002495 reset(getServices().powerManagerInternal);
2496 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002497
Pavel Grafov28939982017-10-03 15:11:52 +01002498 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002499 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002500 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2501 verifyStayOnWhilePluggedCleared(false);
2502 }
2503
2504 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2505 // uses separate challenge.
2506 public void testSetMaximumTimeToLockProfile() throws Exception {
2507 final int PROFILE_USER = 15;
2508 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2509 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2510 mContext.binder.callingUid = PROFILE_ADMIN;
2511 final DevicePolicyManagerInternal dpmi =
2512 LocalServices.getService(DevicePolicyManagerInternal.class);
2513
2514 dpm.setMaximumTimeToLock(admin1, 0);
2515
2516 reset(getServices().powerManagerInternal);
2517 reset(getServices().settings);
2518
2519 // First add timeout for the profile.
2520 dpm.setMaximumTimeToLock(admin1, 10);
2521 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2522
2523 reset(getServices().powerManagerInternal);
2524 reset(getServices().settings);
2525
2526 // Add separate challenge
2527 when(getServices().lockPatternUtils
2528 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2529 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2530
2531 verifyScreenTimeoutCall(10L, PROFILE_USER);
2532 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2533
2534 reset(getServices().powerManagerInternal);
2535 reset(getServices().settings);
2536
2537 // Remove the timeout.
2538 dpm.setMaximumTimeToLock(admin1, 0);
2539 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2540 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2541
2542 reset(getServices().powerManagerInternal);
2543 reset(getServices().settings);
2544
2545 // Add it back.
2546 dpm.setMaximumTimeToLock(admin1, 10);
2547 verifyScreenTimeoutCall(10L, PROFILE_USER);
2548 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2549
2550 reset(getServices().powerManagerInternal);
2551 reset(getServices().settings);
2552
2553 // Remove separate challenge.
2554 reset(getServices().lockPatternUtils);
2555 when(getServices().lockPatternUtils
2556 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2557 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2558
2559 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2560 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2561
2562 reset(getServices().powerManagerInternal);
2563 reset(getServices().settings);
2564
2565 // Remove the timeout.
2566 dpm.setMaximumTimeToLock(admin1, 0);
2567 verifyScreenTimeoutCall(null, PROFILE_USER);
2568 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002569 }
2570
Michal Karpinski943aabd2016-10-06 11:09:25 +01002571 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2572 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2573 setupDeviceOwner();
2574 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2575
Michal Karpinskid084ca52017-01-18 15:54:18 +00002576 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2577 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2578 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2579 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2580 - ONE_MINUTE;
2581
2582 // verify that the minimum timeout cannot be modified on user builds (system property is
2583 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002584 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002585
2586 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2587 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2588 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2589
Pavel Grafov75c0a892017-05-18 17:28:27 +01002590 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002591
2592 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002593 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002594
Michal Karpinskid084ca52017-01-18 15:54:18 +00002595 // reset to default (0 means the admin is not participating, so default should be returned)
2596 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002597
2598 // aggregation should be the default if unset by any admin
2599 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2600 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2601
2602 // admin not participating by default
2603 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2604
2605 //clamping from the top
2606 dpm.setRequiredStrongAuthTimeout(admin1,
2607 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2608 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2609 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2610 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2611 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2612
Michal Karpinskid084ca52017-01-18 15:54:18 +00002613 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002614 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2615 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2616 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2617 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2618
2619 // clamping from the bottom
2620 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2621 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2622 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2623
Michal Karpinskid084ca52017-01-18 15:54:18 +00002624 // values within range
2625 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2626 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2627 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2628
2629 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2630 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2631 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002632
2633 // reset to default
2634 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2635 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2636 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2637 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2638
2639 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002640 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2641 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002642 }
2643
Pavel Grafov28939982017-10-03 15:11:52 +01002644 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002645 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002646 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002647 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002648 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002649 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002650 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002651 }
Pavel Grafov28939982017-10-03 15:11:52 +01002652 }
2653
2654 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002655 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2656 // UnfinishedVerificationException.
2657 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002658
Esteban Talavera01576862016-12-15 11:16:44 +00002659 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002660 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002661 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002662 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002663 .thenReturn(false);
2664 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002665 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2666 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002667 .thenReturn(true);
2668 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2669
2670 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002671 }
Victor Chang3e794af2016-03-04 13:48:17 +00002672
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002673 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2674 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002675 mContext.packageName = admin1.getPackageName();
2676 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002677 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2678 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2679 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2680 false);
2681 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2682 }
2683
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002684 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2685 setup_DeviceAdminFeatureOff();
2686 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2687 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2688 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2689 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2690 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2691 assertCheckProvisioningPreCondition(
2692 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2693 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2694 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2695 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2696 }
2697
Esteban Talavera01576862016-12-15 11:16:44 +00002698 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002699 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002700 .thenReturn(false);
2701 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002702 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2703 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002704 .thenReturn(true);
2705 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2706
2707 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002708 }
Victor Chang3e794af2016-03-04 13:48:17 +00002709
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002710 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2711 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002712 mContext.packageName = admin1.getPackageName();
2713 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002714 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2715 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2716 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2717 false);
2718 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2719
2720 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002721 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002722 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2723 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2724 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2725 true);
2726 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2727 }
2728
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002729 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2730 setup_ManagedProfileFeatureOff();
2731 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2732 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2733 DevicePolicyManager.CODE_OK);
2734 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2735 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2736 assertCheckProvisioningPreCondition(
2737 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2738 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2739 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2740 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2741
2742 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002743 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002744 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2745 DevicePolicyManager.CODE_OK);
2746 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2747 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2748 assertCheckProvisioningPreCondition(
2749 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2750 DevicePolicyManager.CODE_OK);
2751 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2752 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2753 }
2754
Esteban Talavera01576862016-12-15 11:16:44 +00002755 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002756 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002757 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002758 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2759 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002760 .thenReturn(true);
2761 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2762
2763 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002764 }
Victor Chang3e794af2016-03-04 13:48:17 +00002765
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002766 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2767 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002768 mContext.packageName = admin1.getPackageName();
2769 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002770 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2771 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2772 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2773 false /* because of non-split user */);
2774 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2775 false /* because of non-split user */);
2776 }
2777
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002778 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002779 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002780 setup_nonSplitUser_firstBoot_primaryUser();
2781 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2782 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2783 DevicePolicyManager.CODE_OK);
2784 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2785 DevicePolicyManager.CODE_OK);
2786 assertCheckProvisioningPreCondition(
2787 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2788 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2789 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2790 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2791 }
2792
Esteban Talavera01576862016-12-15 11:16:44 +00002793 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002794 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002795 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002796 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2797 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002798 .thenReturn(true);
2799 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2800
2801 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002802 }
Victor Chang3e794af2016-03-04 13:48:17 +00002803
Nicolas Prevot45d29072017-01-18 16:11:19 +00002804 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2805 setDeviceOwner();
2806 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2807 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2808 }
2809
2810 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2811 setup_nonSplitUser_withDo_primaryUser();
2812 final int MANAGED_PROFILE_USER_ID = 18;
2813 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2814 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002815 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002816 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002817 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002818 true)).thenReturn(true);
2819 }
2820
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002821 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2822 throws Exception {
2823 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002824 mContext.packageName = admin1.getPackageName();
2825 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002826 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2827 false/* because of completed device setup */);
2828 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2829 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2830 false/* because of non-split user */);
2831 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2832 false/* because of non-split user */);
2833 }
2834
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002835 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2836 throws Exception {
2837 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2838 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2839 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2840 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2841 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2842 DevicePolicyManager.CODE_OK);
2843 assertCheckProvisioningPreCondition(
2844 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2845 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2846 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2847 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2848 }
2849
Nicolas Prevot45d29072017-01-18 16:11:19 +00002850 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2851 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002852 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002853 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2854
2855 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2856 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002857 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002858
2859 // COMP mode is allowed.
2860 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2861 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002862 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002863
Nicolas Prevot45d29072017-01-18 16:11:19 +00002864 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002865 assertCheckProvisioningPreCondition(
2866 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002867 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002868 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002869 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2870 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2871 }
Esteban Talavera01576862016-12-15 11:16:44 +00002872
Nicolas Prevot45d29072017-01-18 16:11:19 +00002873 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2874 setup_nonSplitUser_withDo_primaryUser();
2875 mContext.packageName = admin1.getPackageName();
2876 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2877 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2878 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002879 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002880 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2881 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2882 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002883 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002884 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2885 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2886 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2887 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2888 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002889 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002890 assertCheckProvisioningPreCondition(
2891 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002892 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002893 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002894 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2895 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2896 }
Esteban Talavera01576862016-12-15 11:16:44 +00002897
Nicolas Prevot45d29072017-01-18 16:11:19 +00002898 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2899 throws Exception {
2900 setup_nonSplitUser_withDo_primaryUser();
2901 mContext.packageName = admin1.getPackageName();
2902 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002903 // The DO should not be allowed to initiate provisioning if the restriction is set by
2904 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002905 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002906 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2907 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2908 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002909 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002910 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2911 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2912 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2913 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2914 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002915 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2916
2917 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002918 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002919 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002920 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002921 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2922 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2923 }
2924
2925 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2926 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2927 mContext.packageName = admin1.getPackageName();
2928 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2929
2930 // We can delete the managed profile to create a new one, so provisioning is allowed.
2931 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2932 DevicePolicyManager.CODE_OK);
2933 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2934 assertCheckProvisioningPreCondition(
2935 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2936 DpmMockContext.ANOTHER_PACKAGE_NAME,
2937 DevicePolicyManager.CODE_OK);
2938 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2939 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2940 }
2941
2942 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2943 throws Exception {
2944 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2945 mContext.packageName = admin1.getPackageName();
2946 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002947 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002948 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2949 eq(UserHandle.SYSTEM)))
2950 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002951 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002952 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2953 eq(UserHandle.SYSTEM)))
2954 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002955
2956 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002957 assertCheckProvisioningPreCondition(
2958 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2959 DpmMockContext.ANOTHER_PACKAGE_NAME,
2960 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2961 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2962 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002963
2964 // But the device owner can still do it because it has set the restriction itself.
2965 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2966 DevicePolicyManager.CODE_OK);
2967 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002968 }
2969
2970 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002971 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002972 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002973 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2974 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002975 .thenReturn(false);
2976 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2977
2978 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002979 }
Victor Chang3e794af2016-03-04 13:48:17 +00002980
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002981 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2982 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002983 mContext.packageName = admin1.getPackageName();
2984 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002985 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2986 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2987 false /* because canAddMoreManagedProfiles returns false */);
2988 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2989 true);
2990 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2991 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002992 }
2993
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002994 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2995 throws Exception {
2996 setup_splitUser_firstBoot_systemUser();
2997 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2998 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2999 DevicePolicyManager.CODE_OK);
3000 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003001 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003002 assertCheckProvisioningPreCondition(
3003 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3004 DevicePolicyManager.CODE_OK);
3005 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3006 DevicePolicyManager.CODE_SYSTEM_USER);
3007 }
3008
Esteban Talavera01576862016-12-15 11:16:44 +00003009 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003010 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003011 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003012 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3013 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003014 .thenReturn(false);
3015 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3016
3017 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003018 }
Victor Chang3e794af2016-03-04 13:48:17 +00003019
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003020 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3021 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003022 mContext.packageName = admin1.getPackageName();
3023 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003024 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3025 true/* it's undefined behavior. Can be changed into false in the future */);
3026 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3027 false /* because canAddMoreManagedProfiles returns false */);
3028 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3029 true/* it's undefined behavior. Can be changed into false in the future */);
3030 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3031 false/* because calling uid is system user */);
3032 }
3033
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003034 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3035 throws Exception {
3036 setup_splitUser_afterDeviceSetup_systemUser();
3037 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3038 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3039 DevicePolicyManager.CODE_OK);
3040 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003041 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003042 assertCheckProvisioningPreCondition(
3043 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3044 DevicePolicyManager.CODE_OK);
3045 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3046 DevicePolicyManager.CODE_SYSTEM_USER);
3047 }
3048
Esteban Talavera01576862016-12-15 11:16:44 +00003049 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003050 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003051 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003052 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3053 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003054 true)).thenReturn(true);
3055 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3056
3057 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003058 }
Victor Chang3e794af2016-03-04 13:48:17 +00003059
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003060 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3061 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003062 mContext.packageName = admin1.getPackageName();
3063 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003064 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3065 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3066 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3067 true);
3068 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003069 }
3070
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003071 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003072 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003073 setup_splitUser_firstBoot_primaryUser();
3074 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3075 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3076 DevicePolicyManager.CODE_OK);
3077 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3078 DevicePolicyManager.CODE_OK);
3079 assertCheckProvisioningPreCondition(
3080 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3081 DevicePolicyManager.CODE_OK);
3082 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3083 DevicePolicyManager.CODE_OK);
3084 }
3085
Esteban Talavera01576862016-12-15 11:16:44 +00003086 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003087 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003088 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003089 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3090 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003091 true)).thenReturn(true);
3092 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3093
3094 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003095 }
Victor Chang3e794af2016-03-04 13:48:17 +00003096
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003097 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3098 throws Exception {
3099 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003100 mContext.packageName = admin1.getPackageName();
3101 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003102 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3103 true/* it's undefined behavior. Can be changed into false in the future */);
3104 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3105 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3106 true/* it's undefined behavior. Can be changed into false in the future */);
3107 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3108 false/* because user setup completed */);
3109 }
3110
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003111 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003112 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003113 setup_splitUser_afterDeviceSetup_primaryUser();
3114 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3115 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3116 DevicePolicyManager.CODE_OK);
3117 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3118 DevicePolicyManager.CODE_OK);
3119 assertCheckProvisioningPreCondition(
3120 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3121 DevicePolicyManager.CODE_OK);
3122 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3123 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3124 }
3125
Esteban Talavera01576862016-12-15 11:16:44 +00003126 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003127 setDeviceOwner();
3128
Pavel Grafov75c0a892017-05-18 17:28:27 +01003129 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003130 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003131 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3132 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003133 .thenReturn(false);
3134 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3135
3136 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003137 }
Victor Chang3e794af2016-03-04 13:48:17 +00003138
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003139 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3140 throws Exception {
3141 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003142 mContext.packageName = admin1.getPackageName();
3143 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003144 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3145 false /* can't provision managed profile on system user */);
3146 }
3147
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003148 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003149 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003150 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3151 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3152 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3153 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3154 }
3155
3156 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003157 setDeviceOwner();
3158
Pavel Grafov75c0a892017-05-18 17:28:27 +01003159 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003160 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003161 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3162 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003163 true)).thenReturn(true);
3164 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3165
3166 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003167 }
Victor Chang3e794af2016-03-04 13:48:17 +00003168
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003169 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3170 throws Exception {
3171 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003172 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3173 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003174 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3175 }
3176
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003177 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003178 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003179 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3180 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003181
3182 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003183 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3184 DevicePolicyManager.CODE_OK);
3185 }
3186
3187 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003188 setDeviceOwner();
3189
Pavel Grafov75c0a892017-05-18 17:28:27 +01003190 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003191 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003192 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3193 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003194 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3195 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003196 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003197 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003198 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003199 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003200 true)).thenReturn(true);
3201 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3202
3203 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003204 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003205
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003206 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3207 throws Exception {
3208 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003209 mContext.packageName = admin1.getPackageName();
3210 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003211 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3212 }
3213
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003214 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3215 throws Exception {
3216 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3217 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3218 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3219 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3220 }
3221
3222 public void testCheckProvisioningPreCondition_permission() {
3223 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003224 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3225 () -> dpm.checkProvisioningPreCondition(
3226 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003227 }
3228
Victor Chang3577ed22016-08-25 18:49:26 +01003229 public void testForceUpdateUserSetupComplete_permission() {
3230 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003231 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3232 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003233 }
3234
3235 public void testForceUpdateUserSetupComplete_systemUser() {
3236 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3237 // GIVEN calling from user 20
3238 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003239 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3240 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003241 }
3242
3243 public void testForceUpdateUserSetupComplete_userbuild() {
3244 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3245 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3246
3247 final int userId = UserHandle.USER_SYSTEM;
3248 // GIVEN userComplete is false in SettingsProvider
3249 setUserSetupCompleteForUser(false, userId);
3250
3251 // GIVEN userComplete is true in DPM
3252 DevicePolicyManagerService.DevicePolicyData userData =
3253 new DevicePolicyManagerService.DevicePolicyData(userId);
3254 userData.mUserSetupComplete = true;
3255 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3256
3257 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003258 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003259
3260 assertTrue(dpms.hasUserSetupCompleted());
3261
3262 dpm.forceUpdateUserSetupComplete();
3263
3264 // THEN the state in dpms is not changed
3265 assertTrue(dpms.hasUserSetupCompleted());
3266 }
3267
3268 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3269 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3270 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3271
3272 final int userId = UserHandle.USER_SYSTEM;
3273 // GIVEN userComplete is false in SettingsProvider
3274 setUserSetupCompleteForUser(false, userId);
3275
3276 // GIVEN userComplete is true in DPM
3277 DevicePolicyManagerService.DevicePolicyData userData =
3278 new DevicePolicyManagerService.DevicePolicyData(userId);
3279 userData.mUserSetupComplete = true;
3280 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3281
3282 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003283 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003284
3285 assertTrue(dpms.hasUserSetupCompleted());
3286
3287 dpm.forceUpdateUserSetupComplete();
3288
3289 // THEN the state in dpms is not changed
3290 assertFalse(dpms.hasUserSetupCompleted());
3291 }
3292
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003293 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003294 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003295 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003296
3297 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3298 runAsCaller(mAdmin1Context, dpms, dpm -> {
3299 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3300 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003301 }
3302
3303 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3304 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3305 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003306
3307 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3308 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003309 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003310 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3311 .thenReturn(true);
3312
3313 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003314 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003315
3316 // Enabling logging should not change the timestamp.
3317 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003318 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003319 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003320 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003321 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003322 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003323
3324 // Retrieving the logs should update the timestamp.
3325 final long beforeRetrieval = System.currentTimeMillis();
3326 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003327 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003328 final long afterRetrieval = System.currentTimeMillis();
3329 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3330 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3331
3332 // Retrieving the pre-boot logs should update the timestamp.
3333 Thread.sleep(2);
3334 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003335 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003336 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3337
3338 // Checking the timestamp again should not change it.
3339 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003340 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003341
3342 // Retrieving the logs again should update the timestamp.
3343 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003344 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003345 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3346
3347 // Disabling logging should not change the timestamp.
3348 Thread.sleep(2);
3349 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003350 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003351
3352 // Restarting the DPMS should not lose the timestamp.
3353 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003354 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003355
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003356 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3357 mContext.binder.callingUid = 1234567;
3358 mContext.callerPermissions.add(permission.MANAGE_USERS);
3359 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3360 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3361
3362 // System can retrieve the timestamp.
3363 mContext.binder.clearCallingIdentity();
3364 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3365
3366 // Removing the device owner should clear the timestamp.
3367 clearDeviceOwner();
3368 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003369 }
3370
yuemingw0de748d2017-11-15 19:22:27 +00003371 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3372 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3373 setupDeviceOwner();
3374 assertExpectException(SecurityException.class, null, () ->
3375 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3376 }
3377
3378 public void testSetSystemSettingFailWithPO() throws Exception {
3379 setupProfileOwner();
3380 assertExpectException(SecurityException.class, null, () ->
3381 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"));
3382 }
3383
3384 public void testSetSystemSetting() throws Exception {
3385 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3386 setupDeviceOwner();
3387 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3388 verify(getServices().settings).settingsSystemPutString(
3389 Settings.System.SCREEN_BRIGHTNESS, "0");
3390 }
3391
yuemingwe43cdf72017-10-12 16:52:11 +01003392 public void testSetTime() throws Exception {
3393 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3394 setupDeviceOwner();
3395 dpm.setTime(admin1, 0);
3396 verify(getServices().alarmManager).setTime(0);
3397 }
3398
3399 public void testSetTimeFailWithPO() throws Exception {
3400 setupProfileOwner();
3401 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3402 }
3403
3404 public void testSetTimeWithAutoTimeOn() throws Exception {
3405 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3406 setupDeviceOwner();
3407 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3408 .thenReturn(1);
3409 assertFalse(dpm.setTime(admin1, 0));
3410 }
3411
3412 public void testSetTimeZone() throws Exception {
3413 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3414 setupDeviceOwner();
3415 dpm.setTimeZone(admin1, "Asia/Shanghai");
3416 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3417 }
3418
3419 public void testSetTimeZoneFailWithPO() throws Exception {
3420 setupProfileOwner();
3421 assertExpectException(SecurityException.class, null,
3422 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3423 }
3424
3425 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3426 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3427 setupDeviceOwner();
3428 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3429 .thenReturn(1);
3430 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3431 }
3432
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003433 public void testGetLastBugReportRequestTime() throws Exception {
3434 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3435 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003436
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003437 mContext.packageName = admin1.getPackageName();
3438 mContext.applicationInfo = new ApplicationInfo();
3439 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3440 .thenReturn(Color.WHITE);
3441 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3442 anyObject())).thenReturn(Color.WHITE);
3443
Esteban Talaverad36dd152016-12-15 08:51:45 +00003444 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3445 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003446 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003447
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003448 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003449 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003450
3451 // Requesting a bug report should update the timestamp.
3452 final long beforeRequest = System.currentTimeMillis();
3453 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003454 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003455 final long afterRequest = System.currentTimeMillis();
3456 assertTrue(bugReportRequestTime >= beforeRequest);
3457 assertTrue(bugReportRequestTime <= afterRequest);
3458
3459 // Checking the timestamp again should not change it.
3460 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003461 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003462
3463 // Restarting the DPMS should not lose the timestamp.
3464 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003465 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003466
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003467 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3468 mContext.binder.callingUid = 1234567;
3469 mContext.callerPermissions.add(permission.MANAGE_USERS);
3470 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3471 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3472
3473 // System can retrieve the timestamp.
3474 mContext.binder.clearCallingIdentity();
3475 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3476
3477 // Removing the device owner should clear the timestamp.
3478 clearDeviceOwner();
3479 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003480 }
3481
3482 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3483 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3484 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003485 mContext.packageName = admin1.getPackageName();
3486 mContext.applicationInfo = new ApplicationInfo();
3487 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3488 .thenReturn(Color.WHITE);
3489 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3490 anyObject())).thenReturn(Color.WHITE);
3491
3492 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3493 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003494 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003495 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003496 .thenReturn(true);
3497
3498 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003499 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003500
3501 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3502 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003503 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003504
3505 // Enabling logging should not change the timestamp.
3506 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003507 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003508
3509 // Retrieving the logs should update the timestamp.
3510 final long beforeRetrieval = System.currentTimeMillis();
3511 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003512 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003513 final long afterRetrieval = System.currentTimeMillis();
3514 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3515 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3516
3517 // Checking the timestamp again should not change it.
3518 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003519 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003520
3521 // Retrieving the logs again should update the timestamp.
3522 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003523 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003524 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3525
3526 // Disabling logging should not change the timestamp.
3527 Thread.sleep(2);
3528 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003529 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003530
3531 // Restarting the DPMS should not lose the timestamp.
3532 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003533 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3534
3535 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3536 mContext.binder.callingUid = 1234567;
3537 mContext.callerPermissions.add(permission.MANAGE_USERS);
3538 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3539 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3540
3541 // System can retrieve the timestamp.
3542 mContext.binder.clearCallingIdentity();
3543 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3544
3545 // Removing the device owner should clear the timestamp.
3546 clearDeviceOwner();
3547 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003548 }
3549
Tony Mak2f26b792016-11-28 17:54:51 +00003550 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3551 // Setup device owner.
3552 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3553 setupDeviceOwner();
3554
3555 // Only device owner is setup, the result list should be empty.
3556 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3557 MoreAsserts.assertEmpty(targetUsers);
3558
3559 // Setup a managed profile managed by the same admin.
3560 final int MANAGED_PROFILE_USER_ID = 15;
3561 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3562 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3563
3564 // Add a secondary user, it should never talk with.
3565 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003566 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003567
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003568 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3569 // other.
3570 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3571 MoreAsserts.assertEmpty(targetUsers);
3572
3573 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3574 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3575 MoreAsserts.assertEmpty(targetUsers);
3576
3577 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003578 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003579 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3580 dpm.setAffiliationIds(admin1, userAffiliationIds);
3581
3582 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3583 dpm.setAffiliationIds(admin1, userAffiliationIds);
3584
Tony Mak2f26b792016-11-28 17:54:51 +00003585 // Calling from device owner admin, the result list should just contain the managed
3586 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003587 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003588 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3589 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3590
3591 // Calling from managed profile admin, the result list should just contain the system
3592 // user id.
3593 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3594 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3595 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003596
3597 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003598 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003599
3600 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3601 // to each other.
3602 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3603 MoreAsserts.assertEmpty(targetUsers);
3604
3605 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3606 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3607 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003608 }
3609
3610 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3611 // Setup a device owner.
3612 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3613 setupDeviceOwner();
3614
3615 // Set up a managed profile managed by different package.
3616 final int MANAGED_PROFILE_USER_ID = 15;
3617 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3618 final ComponentName adminDifferentPackage =
3619 new ComponentName("another.package", "whatever.class");
3620 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3621
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003622 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003623 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003624 dpm.setAffiliationIds(admin1, userAffiliationIds);
3625
3626 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3627 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3628
Tony Mak2f26b792016-11-28 17:54:51 +00003629 // Calling from device owner admin, we should get zero bind device admin target users as
3630 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003631 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003632 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3633 MoreAsserts.assertEmpty(targetUsers);
3634
3635 // Calling from managed profile admin, we should still get zero target users for the same
3636 // reason.
3637 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3638 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3639 MoreAsserts.assertEmpty(targetUsers);
3640 }
3641
Charles Hee078db72017-10-19 18:03:20 +01003642 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003643 // Setup a device owner.
3644 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3645 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003646 // Lock task policy is updated when loading user data.
3647 verify(getServices().iactivityManager).updateLockTaskPackages(
3648 UserHandle.USER_SYSTEM, new String[0]);
3649 verify(getServices().iactivityManager).updateLockTaskFeatures(
3650 UserHandle.USER_SYSTEM, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003651
3652 // Set up a managed profile managed by different package (package name shouldn't matter)
3653 final int MANAGED_PROFILE_USER_ID = 15;
3654 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3655 final ComponentName adminDifferentPackage =
3656 new ComponentName("another.package", "whatever.class");
3657 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Charles Hee078db72017-10-19 18:03:20 +01003658 verify(getServices().iactivityManager).updateLockTaskPackages(
3659 MANAGED_PROFILE_USER_ID, new String[0]);
3660 verify(getServices().iactivityManager).updateLockTaskFeatures(
3661 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003662
3663 // The DO can still set lock task packages
3664 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3665 final String[] doPackages = {"doPackage1", "doPackage2"};
3666 dpm.setLockTaskPackages(admin1, doPackages);
3667 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3668 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3669 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Charles Hee078db72017-10-19 18:03:20 +01003670 verify(getServices().iactivityManager).updateLockTaskPackages(
3671 UserHandle.USER_SYSTEM, doPackages);
3672 // And the DO can still set lock task features
3673 final int doFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3674 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3675 dpm.setLockTaskFeatures(admin1, doFlags);
3676 verify(getServices().iactivityManager).updateLockTaskFeatures(
3677 UserHandle.USER_SYSTEM, doFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003678
3679 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3680 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3681 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003682 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3683 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3684 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3685 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003686 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
Charles Hee078db72017-10-19 18:03:20 +01003687 // And it shouldn't be able to setLockTaskFeatures.
3688 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3689 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3690 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3691 () -> dpm.setLockTaskFeatures(adminDifferentPackage, poFlags));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003692
3693 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003694 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003695 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3696 dpm.setAffiliationIds(admin1, userAffiliationIds);
3697
3698 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3699 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3700
3701 // Now the managed profile can set lock task packages.
3702 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3703 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3704 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3705 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003706 verify(getServices().iactivityManager).updateLockTaskPackages(
3707 MANAGED_PROFILE_USER_ID, poPackages);
3708 // And it can set lock task features.
3709 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
3710 verify(getServices().iactivityManager).updateLockTaskFeatures(
3711 MANAGED_PROFILE_USER_ID, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003712
3713 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003714 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003715 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3716 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003717 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3718 MANAGED_PROFILE_USER_ID, new String[0]);
3719 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3720 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003721
3722 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3723 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3724 }
3725
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003726 public void testIsDeviceManaged() throws Exception {
3727 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3728 setupDeviceOwner();
3729
3730 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3731 // find out that the device has a device owner.
3732 assertTrue(dpm.isDeviceManaged());
3733 mContext.binder.callingUid = 1234567;
3734 mContext.callerPermissions.add(permission.MANAGE_USERS);
3735 assertTrue(dpm.isDeviceManaged());
3736 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3737 mContext.binder.clearCallingIdentity();
3738 assertTrue(dpm.isDeviceManaged());
3739
3740 clearDeviceOwner();
3741
3742 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3743 // not have a device owner.
3744 mContext.binder.callingUid = 1234567;
3745 mContext.callerPermissions.add(permission.MANAGE_USERS);
3746 assertFalse(dpm.isDeviceManaged());
3747 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3748 mContext.binder.clearCallingIdentity();
3749 assertFalse(dpm.isDeviceManaged());
3750 }
3751
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003752 public void testDeviceOwnerOrganizationName() throws Exception {
3753 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3754 setupDeviceOwner();
3755
3756 dpm.setOrganizationName(admin1, "organization");
3757
3758 // Device owner can retrieve organization managing the device.
3759 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3760
3761 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3762 mContext.binder.callingUid = 1234567;
3763 mContext.callerPermissions.add(permission.MANAGE_USERS);
3764 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3765 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3766
3767 // System can retrieve organization managing the device.
3768 mContext.binder.clearCallingIdentity();
3769 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3770
3771 // Removing the device owner clears the organization managing the device.
3772 clearDeviceOwner();
3773 assertNull(dpm.getDeviceOwnerOrganizationName());
3774 }
3775
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003776 public void testWipeDataManagedProfile() throws Exception {
3777 final int MANAGED_PROFILE_USER_ID = 15;
3778 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3779 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3780 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3781
3782 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003783 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003784 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003785 // Get mock reason string since we throw an IAE with empty string input.
3786 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3787 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003788
3789 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003790 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003791 MANAGED_PROFILE_USER_ID);
3792 }
3793
3794 public void testWipeDataManagedProfileDisallowed() throws Exception {
3795 final int MANAGED_PROFILE_USER_ID = 15;
3796 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3797 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3798
3799 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003800 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003801 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3802
Pavel Grafov75c0a892017-05-18 17:28:27 +01003803 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003804 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3805 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3806 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003807 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3808 thenReturn("Just a test string.");
3809
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003810 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003811 // The PO is not allowed to remove the profile if the user restriction was set on the
3812 // profile by the system
3813 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3814 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003815 }
3816
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003817 public void testWipeDataDeviceOwner() throws Exception {
3818 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003819 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003820 UserManager.DISALLOW_FACTORY_RESET,
3821 UserHandle.SYSTEM))
3822 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003823 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3824 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003825
3826 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003827 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003828 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3829 /*wipeEuicc=*/ eq(false));
3830 }
3831
3832 public void testWipeEuiccDataEnabled() throws Exception {
3833 setDeviceOwner();
3834 when(getServices().userManager.getUserRestrictionSource(
3835 UserManager.DISALLOW_FACTORY_RESET,
3836 UserHandle.SYSTEM))
3837 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003838 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3839 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003840
3841 dpm.wipeData(WIPE_EUICC);
3842 verify(getServices().recoverySystem).rebootWipeUserData(
3843 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3844 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003845 }
3846
3847 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3848 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003849 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003850 UserManager.DISALLOW_FACTORY_RESET,
3851 UserHandle.SYSTEM))
3852 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003853 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3854 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003855 // The DO is not allowed to wipe the device if the user restriction was set
3856 // by the system
3857 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3858 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003859 }
3860
3861 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3862 final int MANAGED_PROFILE_USER_ID = 15;
3863 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3864 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3865
3866 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003867 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003868 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3869
Pavel Grafov75c0a892017-05-18 17:28:27 +01003870 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003871 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3872 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3873 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3874
3875 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3876 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3877
3878 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3879 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3880 // Failed password attempts on the parent user are taken into account, as there isn't a
3881 // separate work challenge.
3882 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3883 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3884 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3885
3886 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3887 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003888 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003889 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003890 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003891 }
3892
3893 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3894 throws Exception {
3895 final int MANAGED_PROFILE_USER_ID = 15;
3896 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3897 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3898
3899 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003900 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003901 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3902
Pavel Grafov75c0a892017-05-18 17:28:27 +01003903 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003904 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3905 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3906 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3907
3908 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3909 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3910
3911 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3912 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3913 // Failed password attempts on the parent user are taken into account, as there isn't a
3914 // separate work challenge.
3915 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3916 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3917 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3918
3919 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3920 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003921 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003922 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003923 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003924 }
3925
3926 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3927 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003928 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003929 UserManager.DISALLOW_FACTORY_RESET,
3930 UserHandle.SYSTEM))
3931 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3932
3933 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3934
3935 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3936 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3937 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3938 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3939 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3940
3941 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3942 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003943 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003944 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3945 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003946 }
3947
3948 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3949 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003950 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003951 UserManager.DISALLOW_FACTORY_RESET,
3952 UserHandle.SYSTEM))
3953 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3954
3955 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3956
3957 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3958 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3959 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3960 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3961 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3962
3963 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003964 verifyZeroInteractions(getServices().recoverySystem);
3965 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003966 .removeUserEvenWhenDisallowed(anyInt());
3967 }
3968
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003969 public void testGetPermissionGrantState() throws Exception {
3970 final String permission = "some.permission";
3971 final String app1 = "com.example.app1";
3972 final String app2 = "com.example.app2";
3973
Pavel Grafov75c0a892017-05-18 17:28:27 +01003974 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003975 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003976 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003977 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003978 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003979 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3980 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003981 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003982 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003983 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003984 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003985 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003986 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3987
3988 // System can retrieve permission grant state.
3989 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003990 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003991 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3992 dpm.getPermissionGrantState(null, app1, permission));
3993 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3994 dpm.getPermissionGrantState(null, app2, permission));
3995
3996 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003997 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3998 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003999 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4000 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004001
4002 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004003 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4004 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004005 setAsProfileOwner(admin1);
4006 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4007 dpm.getPermissionGrantState(admin1, app1, permission));
4008 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4009 dpm.getPermissionGrantState(admin1, app2, permission));
4010 }
4011
Rubin Xuaab7a412016-12-30 21:13:29 +00004012 public void testResetPasswordWithToken() throws Exception {
4013 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4014 setupDeviceOwner();
4015 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004016 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4017 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4018
Rubin Xuaab7a412016-12-30 21:13:29 +00004019 // test adding a token
4020 final byte[] token = new byte[32];
4021 final long handle = 123456;
4022 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01004023 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004024 .thenReturn(handle);
4025 assertTrue(dpm.setResetPasswordToken(admin1, token));
4026
4027 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004028 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004029 .thenReturn(true);
4030 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4031
4032 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004033 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01004034 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
4035 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004036 eq(UserHandle.USER_SYSTEM)))
4037 .thenReturn(true);
4038 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4039
4040 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004041 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004042 .thenReturn(true);
4043 assertTrue(dpm.clearResetPasswordToken(admin1));
4044 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004045
Alexandru-Andrei Rotaru7f31bb02017-09-07 16:29:48 +01004046 public void testSetPasswordBlacklistCannotBeCalledByNonAdmin() throws Exception {
4047 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4048 () -> dpm.setPasswordBlacklist(admin1, null, null));
4049 verifyZeroInteractions(getServices().passwordBlacklist);
4050 }
4051
4052 public void testClearingPasswordBlacklistDoesNotCreateNewBlacklist() throws Exception {
4053 setupProfileOwner();
4054 dpm.setPasswordBlacklist(admin1, null, null);
4055 verifyZeroInteractions(getServices().passwordBlacklist);
4056 }
4057
4058 public void testSetPasswordBlacklistCreatesNewBlacklist() throws Exception {
4059 final String name = "myblacklist";
4060 final List<String> explicit = Arrays.asList("password", "letmein");
4061 setupProfileOwner();
4062 dpm.setPasswordBlacklist(admin1, name, explicit);
4063 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, explicit);
4064 }
4065
4066 public void testSetPasswordBlacklistOnlyConvertsExplicitToLowerCase() throws Exception {
4067 final List<String> mixedCase = Arrays.asList("password", "LETMEIN", "FooTBAll");
4068 final List<String> lowerCase = Arrays.asList("password", "letmein", "football");
4069 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4070 setupDeviceOwner();
4071 final String name = "Name of the Blacklist";
4072 dpm.setPasswordBlacklist(admin1, name, mixedCase);
4073 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, lowerCase);
4074 }
4075
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004076 public void testIsActivePasswordSufficient() throws Exception {
4077 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4078 mContext.packageName = admin1.getPackageName();
4079 setupDeviceOwner();
4080
4081 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4082 dpm.setPasswordMinimumLength(admin1, 8);
4083 dpm.setPasswordMinimumLetters(admin1, 6);
4084 dpm.setPasswordMinimumLowerCase(admin1, 3);
4085 dpm.setPasswordMinimumUpperCase(admin1, 1);
4086 dpm.setPasswordMinimumNonLetter(admin1, 1);
4087 dpm.setPasswordMinimumNumeric(admin1, 1);
4088 dpm.setPasswordMinimumSymbols(admin1, 0);
4089
Rubin Xucc391c22018-01-02 20:37:35 +00004090 reset(mContext.spiedContext);
4091
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004092 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4093 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4094 8, 2,
4095 6, 1,
4096 0, 1);
4097
4098 setActivePasswordState(passwordMetricsNoSymbols);
4099 assertTrue(dpm.isActivePasswordSufficient());
4100
4101 initializeDpms();
4102 reset(mContext.spiedContext);
4103 assertTrue(dpm.isActivePasswordSufficient());
4104
4105 // This call simulates the user entering the password for the first time after a reboot.
4106 // This causes password metrics to be reloaded into memory. Until this happens,
4107 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4108 // even if the DPC changes password requirements so that the password no longer meets the
4109 // requirements. This is a known limitation of the current implementation of
4110 // isActivePasswordSufficient() - see b/34218769.
4111 setActivePasswordState(passwordMetricsNoSymbols);
4112 assertTrue(dpm.isActivePasswordSufficient());
4113
4114 dpm.setPasswordMinimumSymbols(admin1, 1);
4115 // This assertion would fail if we had not called setActivePasswordState() again after
4116 // initializeDpms() - see previous comment.
4117 assertFalse(dpm.isActivePasswordSufficient());
4118
4119 initializeDpms();
4120 reset(mContext.spiedContext);
4121 assertFalse(dpm.isActivePasswordSufficient());
4122
4123 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4124 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4125 7, 2,
4126 5, 1,
4127 1, 2);
4128
4129 setActivePasswordState(passwordMetricsWithSymbols);
4130 assertTrue(dpm.isActivePasswordSufficient());
4131 }
4132
Pavel Grafov75c0a892017-05-18 17:28:27 +01004133 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4134 throws Exception {
4135 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004136 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004137
Pavel Grafov75c0a892017-05-18 17:28:27 +01004138 dpm.setActivePasswordState(passwordMetrics, userHandle);
4139 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004140
Rubin Xucc391c22018-01-02 20:37:35 +00004141 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4142 // reportPasswordChanged()
4143 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
4144 MockUtils.checkIntentAction(
4145 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4146 MockUtils.checkUserHandle(userHandle));
4147
Pavel Grafov75c0a892017-05-18 17:28:27 +01004148 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4149 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004150 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004151
4152 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4153 MockUtils.checkIntent(intent),
4154 MockUtils.checkUserHandle(userHandle));
4155
4156 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4157 // let it finish with system uid, otherwise it will throw and crash.
4158 flushTasks();
4159
4160 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004161 }
4162
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004163 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4164 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4165 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4166 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4167 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4168 DpmMockContext.SYSTEM_UID);
4169 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4170 DpmMockContext.SYSTEM_UID);
4171
4172 // Set up a device owner.
4173 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004174 setupDeviceOwner();
4175
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004176 // First and second user set IMEs manually.
4177 mContext.binder.callingUid = firstUserSystemUid;
4178 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4179 mContext.binder.callingUid = secondUserSystemUid;
4180 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004181
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004182 // Device owner changes IME for first user.
4183 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004184 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004185 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004186 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004187 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004188 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004189 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004190 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4191 mContext.binder.callingUid = firstUserSystemUid;
4192 assertTrue(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 // Second user changes IME manually.
4197 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4198 mContext.binder.callingUid = firstUserSystemUid;
4199 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4200 mContext.binder.callingUid = secondUserSystemUid;
4201 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004202
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004203 // First user changes IME manually.
4204 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4205 mContext.binder.callingUid = firstUserSystemUid;
4206 assertFalse(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 // Device owner changes IME for first user again.
4211 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004212 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004213 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004214 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004215 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004216 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004217 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4218 mContext.binder.callingUid = firstUserSystemUid;
4219 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4220 mContext.binder.callingUid = secondUserSystemUid;
4221 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004222
4223 // Restarting the DPMS should not lose information.
4224 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004225 mContext.binder.callingUid = firstUserSystemUid;
4226 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4227 mContext.binder.callingUid = secondUserSystemUid;
4228 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004229
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004230 // Device owner can find out whether it set the current IME itself.
4231 mContext.binder.callingUid = deviceOwnerUid;
4232 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004233
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004234 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004235 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004236 mContext.binder.callingUid = firstUserSystemUid;
4237 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4238 mContext.binder.callingUid = secondUserSystemUid;
4239 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004240 }
4241
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004242 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4243 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4244 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4245 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4246 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4247 DpmMockContext.SYSTEM_UID);
4248 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4249 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004250
4251 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004252 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004253 setupProfileOwner();
4254
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004255 // First and second user set IMEs manually.
4256 mContext.binder.callingUid = firstUserSystemUid;
4257 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4258 mContext.binder.callingUid = secondUserSystemUid;
4259 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004260
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004261 // Profile owner changes IME for second user.
4262 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004263 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004264 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004265 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004266 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004267 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004268 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004269 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4270 mContext.binder.callingUid = firstUserSystemUid;
4271 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4272 mContext.binder.callingUid = secondUserSystemUid;
4273 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004274
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004275 // First user changes IME manually.
4276 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4277 mContext.binder.callingUid = firstUserSystemUid;
4278 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4279 mContext.binder.callingUid = secondUserSystemUid;
4280 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004281
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004282 // Second user changes IME manually.
4283 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4284 mContext.binder.callingUid = firstUserSystemUid;
4285 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4286 mContext.binder.callingUid = secondUserSystemUid;
4287 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004288
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004289 // Profile owner changes IME for second user again.
4290 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004291 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004292 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004293 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004294 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004295 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004296 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4297 mContext.binder.callingUid = firstUserSystemUid;
4298 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4299 mContext.binder.callingUid = secondUserSystemUid;
4300 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004301
4302 // Restarting the DPMS should not lose information.
4303 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004304 mContext.binder.callingUid = firstUserSystemUid;
4305 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4306 mContext.binder.callingUid = secondUserSystemUid;
4307 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004308
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004309 // Profile owner can find out whether it set the current IME itself.
4310 mContext.binder.callingUid = profileOwnerUid;
4311 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004312
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004313 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004314 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004315 mContext.binder.callingUid = firstUserSystemUid;
4316 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4317 mContext.binder.callingUid = secondUserSystemUid;
4318 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004319 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004320
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004321 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4322 throws Exception {
4323 // Set up a device owner.
4324 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4325 setupDeviceOwner();
4326 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4327 }
4328
4329 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4330 throws Exception {
4331 // Set up a profile owner.
4332 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4333 setupProfileOwner();
4334 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4335 }
4336
4337 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4338 int adminUid) throws Exception {
4339 mContext.binder.callingUid = adminUid;
4340 final int userId = UserHandle.getUserId(adminUid);
4341
4342 final String packageName = "some.package";
4343 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4344 admin1, Collections.singletonList(packageName)));
4345 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4346
4347 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4348 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4349
4350 // Attempt to set to empty list (which means no listener is whitelisted)
4351 mContext.binder.callingUid = adminUid;
4352 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004353 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004354 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4355
4356 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4357 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4358 }
4359
4360 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4361 // Set up a managed profile
4362 final int MANAGED_PROFILE_USER_ID = 15;
4363 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4364 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4365 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4366
4367 final String permittedListener = "some.package";
4368 setupPackageInPackageManager(
4369 permittedListener,
4370 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4371 /*appId=*/ 12345, /*flags=*/ 0);
4372
4373 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4374 admin1, Collections.singletonList(permittedListener)));
4375
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004376 // isNotificationListenerServicePermitted should throw if not called from System.
4377 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4378 () -> dpms.isNotificationListenerServicePermitted(
4379 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004380
4381 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4382 assertTrue(dpms.isNotificationListenerServicePermitted(
4383 permittedListener, MANAGED_PROFILE_USER_ID));
4384 }
4385
4386 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4387 throws Exception {
4388 // Set up a managed profile
4389 final int MANAGED_PROFILE_USER_ID = 15;
4390 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4391 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4392 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4393
4394 final String permittedListener = "permitted.package";
4395 int appId = 12345;
4396 setupPackageInPackageManager(
4397 permittedListener,
4398 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4399 appId, /*flags=*/ 0);
4400
4401 final String notPermittedListener = "not.permitted.package";
4402 setupPackageInPackageManager(
4403 notPermittedListener,
4404 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4405 ++appId, /*flags=*/ 0);
4406
4407 final String systemListener = "system.package";
4408 setupPackageInPackageManager(
4409 systemListener,
4410 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4411 ++appId, ApplicationInfo.FLAG_SYSTEM);
4412
4413 // By default all packages are allowed
4414 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4415
4416 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4417 assertTrue(dpms.isNotificationListenerServicePermitted(
4418 permittedListener, MANAGED_PROFILE_USER_ID));
4419 assertTrue(dpms.isNotificationListenerServicePermitted(
4420 notPermittedListener, MANAGED_PROFILE_USER_ID));
4421 assertTrue(dpms.isNotificationListenerServicePermitted(
4422 systemListener, MANAGED_PROFILE_USER_ID));
4423
4424 // Setting only one package in the whitelist
4425 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4426 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4427 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004428 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004429 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4430 assertEquals(1, permittedListeners.size());
4431 assertEquals(permittedListener, permittedListeners.get(0));
4432
4433 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4434 assertTrue(dpms.isNotificationListenerServicePermitted(
4435 permittedListener, MANAGED_PROFILE_USER_ID));
4436 assertFalse(dpms.isNotificationListenerServicePermitted(
4437 notPermittedListener, MANAGED_PROFILE_USER_ID));
4438 // System packages are always allowed (even if not in the whitelist)
4439 assertTrue(dpms.isNotificationListenerServicePermitted(
4440 systemListener, MANAGED_PROFILE_USER_ID));
4441
4442 // Setting an empty whitelist - only system listeners allowed
4443 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4444 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004445 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004446 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4447
4448 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4449 assertFalse(dpms.isNotificationListenerServicePermitted(
4450 permittedListener, MANAGED_PROFILE_USER_ID));
4451 assertFalse(dpms.isNotificationListenerServicePermitted(
4452 notPermittedListener, MANAGED_PROFILE_USER_ID));
4453 // System packages are always allowed (even if not in the whitelist)
4454 assertTrue(dpms.isNotificationListenerServicePermitted(
4455 systemListener, MANAGED_PROFILE_USER_ID));
4456
4457 // Setting a null whitelist - all listeners allowed
4458 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4459 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4460 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4461
4462 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4463 assertTrue(dpms.isNotificationListenerServicePermitted(
4464 permittedListener, MANAGED_PROFILE_USER_ID));
4465 assertTrue(dpms.isNotificationListenerServicePermitted(
4466 notPermittedListener, MANAGED_PROFILE_USER_ID));
4467 assertTrue(dpms.isNotificationListenerServicePermitted(
4468 systemListener, MANAGED_PROFILE_USER_ID));
4469 }
4470
4471 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4472 throws Exception {
4473 // Set up a managed profile
4474 final int MANAGED_PROFILE_USER_ID = 15;
4475 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4476 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4477 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4478
4479 final String nonSystemPackage = "non.system.package";
4480 int appId = 12345;
4481 setupPackageInPackageManager(
4482 nonSystemPackage,
4483 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4484 appId, /*flags=*/ 0);
4485
4486 final String systemListener = "system.package";
4487 setupPackageInPackageManager(
4488 systemListener,
4489 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4490 ++appId, ApplicationInfo.FLAG_SYSTEM);
4491
4492 // By default all packages are allowed (for all profiles)
4493 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4494
4495 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4496 assertTrue(dpms.isNotificationListenerServicePermitted(
4497 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4498 assertTrue(dpms.isNotificationListenerServicePermitted(
4499 systemListener, MANAGED_PROFILE_USER_ID));
4500 assertTrue(dpms.isNotificationListenerServicePermitted(
4501 nonSystemPackage, UserHandle.USER_SYSTEM));
4502 assertTrue(dpms.isNotificationListenerServicePermitted(
4503 systemListener, UserHandle.USER_SYSTEM));
4504
4505 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4506 // all allowed in primary profile
4507 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4508 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004509 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004510 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4511
4512 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4513 assertFalse(dpms.isNotificationListenerServicePermitted(
4514 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4515 assertTrue(dpms.isNotificationListenerServicePermitted(
4516 systemListener, MANAGED_PROFILE_USER_ID));
4517 assertTrue(dpms.isNotificationListenerServicePermitted(
4518 nonSystemPackage, UserHandle.USER_SYSTEM));
4519 assertTrue(dpms.isNotificationListenerServicePermitted(
4520 systemListener, UserHandle.USER_SYSTEM));
4521 }
4522
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004523 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004524 mServiceContext.packageName = mRealTestContext.getPackageName();
4525 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4526 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004527 setDeviceOwner();
4528
Pavel Grafov75c0a892017-05-18 17:28:27 +01004529 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004530 }
4531
4532 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004533 mServiceContext.packageName = mRealTestContext.getPackageName();
4534 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4535 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004536 setAsProfileOwner(admin1);
4537
Pavel Grafov75c0a892017-05-18 17:28:27 +01004538 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4539 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004540 }
4541
4542 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004543 mServiceContext.packageName = mRealTestContext.getPackageName();
4544 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4545 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004546 setAsProfileOwner(admin1);
4547
Pavel Grafov75c0a892017-05-18 17:28:27 +01004548 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4549 caller.packageName = "com.example.delegate";
4550 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4551 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004552
Pavel Grafov75c0a892017-05-18 17:28:27 +01004553 // Make caller a delegated cert installer.
4554 runAsCaller(mAdmin1Context, dpms,
4555 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004556
4557 verifyCanGetOwnerInstalledCaCerts(null, caller);
4558 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004559 }
4560
Rubin Xucc391c22018-01-02 20:37:35 +00004561 public void testDisallowSharingIntoProfileSetRestriction() {
4562 Bundle restriction = new Bundle();
4563 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4564
4565 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4566 RestrictionsListener listener = new RestrictionsListener(mContext);
4567 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4568 new Bundle());
4569 verifyDataSharingChangedBroadcast();
4570 }
4571
4572 public void testDisallowSharingIntoProfileClearRestriction() {
4573 Bundle restriction = new Bundle();
4574 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4575
4576 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4577 RestrictionsListener listener = new RestrictionsListener(mContext);
4578 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4579 restriction);
4580 verifyDataSharingChangedBroadcast();
4581 }
4582
4583 public void testDisallowSharingIntoProfileUnchanged() {
4584 RestrictionsListener listener = new RestrictionsListener(mContext);
4585 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4586 new Bundle());
4587 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4588 }
4589
4590 private void verifyDataSharingChangedBroadcast() {
4591 Intent expectedIntent = new Intent(
4592 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4593 expectedIntent.setPackage("com.android.managedprovisioning");
4594 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4595 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4596 MockUtils.checkIntent(expectedIntent),
4597 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4598 }
4599
Robin Lee2c68dad2017-03-17 12:50:24 +00004600 private void verifyCanGetOwnerInstalledCaCerts(
4601 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004602 final String alias = "cert";
4603 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004604
4605 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004606 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004607 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4608 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004609 }
4610 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4611
4612 // caller: device admin or delegated certificate installer
4613 callerContext.applicationInfo = new ApplicationInfo();
4614 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4615
4616 // system_server
4617 final DpmMockContext serviceContext = mContext;
4618 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004619 getServices().addPackageContext(callerUser, admin1Context);
4620 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004621
4622 // Install a CA cert.
4623 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004624 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004625 .thenReturn(alias);
4626 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004627 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004628 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004629 });
4630
Pavel Grafov75c0a892017-05-18 17:28:27 +01004631 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4632 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4633 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004634 flushTasks();
4635
Robin Lee2c68dad2017-03-17 12:50:24 +00004636 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4637
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004638 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004639 runAsCaller(admin1Context, dpms, (dpm) -> {
4640 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004641 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004642 ownerInstalledCaCerts.addAll(installedCaCerts);
4643 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004644
4645 // Restarting the DPMS should not lose information.
4646 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004647 runAsCaller(admin1Context, dpms, (dpm) ->
4648 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004649
4650 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004651 runAsCaller(serviceContext, dpms, (dpm) -> {
4652 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004653
Robin Lee2c68dad2017-03-17 12:50:24 +00004654 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004655 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004656 });
4657
Pavel Grafov75c0a892017-05-18 17:28:27 +01004658 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4659 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4660 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004661 flushTasks();
4662
4663 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4664 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004665 runAsCaller(admin1Context, dpms, (dpm) -> {
4666 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4667 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004668 }
4669
Robin Lee2c68dad2017-03-17 12:50:24 +00004670 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4671 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004672 final String alias = "cert";
4673 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004674
4675 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004676 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004677 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4678 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004679 }
4680 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4681
4682 // caller: device admin or delegated certificate installer
4683 callerContext.applicationInfo = new ApplicationInfo();
4684 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4685
4686 // system_server
4687 final DpmMockContext serviceContext = mContext;
4688 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004689 getServices().addPackageContext(callerUser, admin1Context);
4690 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004691
4692 // Install a CA cert as caller
4693 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004694 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004695 .thenReturn(alias);
4696 assertTrue(dpm.installCaCert(callerName, caCert));
4697 });
4698
4699 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004700 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004701 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004702 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4703 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4704 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004705 flushTasks();
4706
Robin Lee2c68dad2017-03-17 12:50:24 +00004707 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004708 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004709
4710 runAsCaller(serviceContext, dpms, (dpm) -> {
4711 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4712 assertNotNull(ownerInstalledCaCerts);
4713 assertTrue(ownerInstalledCaCerts.isEmpty());
4714 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004715 }
4716
Eran Messeri94d56762017-12-21 20:50:54 +00004717 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4718 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4719 Arrays.sort(gotFlags);
4720 Arrays.sort(expectedFlags);
4721 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4722 }
4723
4724 public void testTranslationOfIdAttestationFlag() {
4725 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4726 int[] correspondingAttUtilsTypes = new int[]{
4727 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4728 AttestationUtils.ID_TYPE_MEID};
4729
4730 // Test translation of zero flags
4731 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4732
4733 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4734 // non-null array
4735 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4736
4737 // Test translation of a single flag
4738 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4739 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4740 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4741
4742 // Test translation of two flags
4743 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4744 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4745 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4746 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4747
4748 // Test translation of all three flags
4749 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4750 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4751 AttestationUtils.ID_TYPE_MEID});
4752 // Test translation of all three flags
4753 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4754 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4755 AttestationUtils.ID_TYPE_MEID});
4756 }
4757
Victor Chang3e794af2016-03-04 13:48:17 +00004758 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004759 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004760 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4761 dpms.notifyChangeToContentObserver(
4762 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4763 }
4764
4765 private void assertProvisioningAllowed(String action, boolean expected) {
4766 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4767 dpm.isProvisioningAllowed(action));
4768 }
Tony Mak2f26b792016-11-28 17:54:51 +00004769
Nicolas Prevot45d29072017-01-18 16:11:19 +00004770 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4771 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004772 final String previousPackageName = mContext.packageName;
4773 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004774
4775 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4776 mContext.packageName = packageName;
4777 mMockContext.binder.callingUid = uid;
4778 assertProvisioningAllowed(action, expected);
4779
4780 // Set the previous package name / calling uid to go back to the initial state.
4781 mContext.packageName = previousPackageName;
4782 mMockContext.binder.callingUid = previousUid;
4783 }
4784
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004785 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004786 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4787 }
4788
4789 private void assertCheckProvisioningPreCondition(
4790 String action, String packageName, int provisioningCondition) {
4791 assertEquals("checkProvisioningPreCondition("
4792 + action + ", " + packageName + ") returning unexpected result",
4793 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004794 }
4795
Tony Mak2f26b792016-11-28 17:54:51 +00004796 /**
4797 * Setup a managed profile with the specified admin and its uid.
4798 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4799 * @param adminUid uid of the admin package.
4800 * @param copyFromAdmin package information for {@code admin} will be built based on this
4801 * component's information.
4802 */
4803 private void addManagedProfile(
4804 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4805 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004806 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004807 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4808 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4809 dpm.setActiveAdmin(admin, false, userId);
4810 assertTrue(dpm.setProfileOwner(admin, null, userId));
4811 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4812 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004813
4814 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004815 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004816 */
Robin Leeabaa0692017-02-20 20:54:22 +00004817 private static StringParceledListSlice asSlice(String[] s) {
4818 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004819 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004820
4821 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004822 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4823 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004824
Robin Lee2c68dad2017-03-17 12:50:24 +00004825 // We can't let exceptions happen on the background thread. Throw them here if they happen
4826 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004827 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004828 }
Victor Chang3e794af2016-03-04 13:48:17 +00004829}