blob: 741a16930fe095944b975a706248f30643a77097 [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
Lenka Trochtova16a91c02018-01-17 11:03:30 +01002188 // Try with POLICY_DISABLE_CAMERA, POLICY_DISABLE_SCREEN_CAPTURE and
2189 // POLICY_MANDATORY_BACKUPS, which are not user restrictions
phweiss73145f42017-01-17 19:06:38 +01002190
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
Lenka Trochtova16a91c02018-01-17 11:03:30 +01002213 // Backups are not mandatory
2214 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_MANDATORY_BACKUPS);
2215 assertNull(intent);
2216
2217 // Backups are mandatory
2218 ComponentName transportComponent = ComponentName.unflattenFromString(
2219 "android/com.android.internal.backup.LocalTransport");
2220 dpm.setMandatoryBackupTransport(admin1, transportComponent);
2221 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_MANDATORY_BACKUPS);
2222 assertNotNull(intent);
2223 assertEquals(DevicePolicyManager.POLICY_MANDATORY_BACKUPS,
2224 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2225
phweiss73145f42017-01-17 19:06:38 +01002226 // Same checks for different user
2227 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2228 // Camera should be disabled by device owner
2229 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2230 assertNotNull(intent);
2231 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2232 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2233 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2234 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2235 // ScreenCapture should not be disabled by device owner
2236 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2237 assertNull(intent);
2238 }
2239
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002240 /**
2241 * Test for:
2242 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002243 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002244 * {@link DevicePolicyManager#isAffiliatedUser}
2245 */
2246 public void testUserAffiliation() throws Exception {
2247 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2248 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2249 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2250
2251 // Check that the system user is unaffiliated.
2252 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2253 assertFalse(dpm.isAffiliatedUser());
2254
2255 // Set a device owner on the system user. Check that the system user becomes affiliated.
2256 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2257 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2258 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2259 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002260 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002261
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002262 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002263 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2264 setAsProfileOwner(admin2);
2265 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002266 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002267
2268 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2269 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002270 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002271 userAffiliationIds.add("red");
2272 userAffiliationIds.add("green");
2273 userAffiliationIds.add("blue");
2274 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002275 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002276 assertFalse(dpm.isAffiliatedUser());
2277
2278 // Have the device owner specify a set of affiliation ids that do not intersect with those
2279 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002280 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002281 deviceAffiliationIds.add("cyan");
2282 deviceAffiliationIds.add("yellow");
2283 deviceAffiliationIds.add("magenta");
2284 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2285 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002286 MoreAsserts.assertContentsInAnyOrder(
2287 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002288 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2289 assertFalse(dpm.isAffiliatedUser());
2290
2291 // Have the profile owner specify a set of affiliation ids that intersect with those
2292 // specified by the device owner. Check that the test user becomes affiliated.
2293 userAffiliationIds.add("yellow");
2294 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002295 MoreAsserts.assertContentsInAnyOrder(
2296 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002297 assertTrue(dpm.isAffiliatedUser());
2298
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002299 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002300 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002301 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002302 assertFalse(dpm.isAffiliatedUser());
2303
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002304 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2305 dpm.setAffiliationIds(admin2, userAffiliationIds);
2306 assertTrue(dpm.isAffiliatedUser());
2307 dpm.clearProfileOwner(admin2);
2308 assertFalse(dpm.isAffiliatedUser());
2309
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002310 // Check that the system user remains affiliated.
2311 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2312 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002313
2314 // Clear the device owner - the user becomes unaffiliated.
2315 clearDeviceOwner();
2316 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002317 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002318
2319 public void testGetUserProvisioningState_defaultResult() {
2320 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2321 }
2322
2323 public void testSetUserProvisioningState_permission() throws Exception {
2324 setupProfileOwner();
2325 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2326
2327 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2328 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2329 }
2330
2331 public void testSetUserProvisioningState_unprivileged() throws Exception {
2332 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002333 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2334 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2335 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002336 }
2337
2338 public void testSetUserProvisioningState_noManagement() {
2339 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002340 assertExpectException(IllegalStateException.class,
2341 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2342 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2343 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002344 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2345 }
2346
2347 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2348 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2349 setupDeviceOwner();
2350 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2351
2352 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2353 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2354 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2355 }
2356
2357 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2358 throws Exception {
2359 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2360 setupDeviceOwner();
2361 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2362
2363 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2364 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2365 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2366 }
2367
2368 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2369 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2370 setupDeviceOwner();
2371 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2372
2373 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2374 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2375 }
2376
2377 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2378 throws Exception {
2379 setupProfileOwner();
2380 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2381
2382 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2383 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2384 DevicePolicyManager.STATE_USER_UNMANAGED);
2385 }
2386
2387 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2388 throws Exception {
2389 setupProfileOwner();
2390 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2391
2392 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2393 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2394 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2395 }
2396
2397 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2398 setupProfileOwner();
2399 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2400
2401 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2402 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2403 }
2404
2405 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2406 setupProfileOwner();
2407 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2408
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002409 assertExpectException(IllegalStateException.class,
2410 /* messageRegex= */ "Cannot move to user provisioning state",
2411 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2412 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2413 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002414 }
2415
2416 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2417 throws Exception {
2418 setupProfileOwner();
2419 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2420
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002421 assertExpectException(IllegalStateException.class,
2422 /* messageRegex= */ "Cannot move to user provisioning state",
2423 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2424 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2425 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002426 }
2427
2428 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2429 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2430 for (int state : states) {
2431 dpm.setUserProvisioningState(state, userId);
2432 assertEquals(state, dpm.getUserProvisioningState());
2433 }
2434 }
2435
2436 private void setupProfileOwner() throws Exception {
2437 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2438
2439 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2440 dpm.setActiveAdmin(admin1, false);
2441 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2442
2443 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2444 }
2445
2446 private void setupDeviceOwner() throws Exception {
2447 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2448
2449 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2450 dpm.setActiveAdmin(admin1, false);
2451 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2452
2453 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2454 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002455
2456 public void testSetMaximumTimeToLock() {
2457 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2458
2459 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2460 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2461
Pavel Grafov75c0a892017-05-18 17:28:27 +01002462 reset(getServices().powerManagerInternal);
2463 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002464
2465 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002466 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2467 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002468 reset(getServices().powerManagerInternal);
2469 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002470
2471 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002472 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2473 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002474 reset(getServices().powerManagerInternal);
2475 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002476
2477 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002478 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2479 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002480 reset(getServices().powerManagerInternal);
2481 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002482
2483 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002484 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2485 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002486 reset(getServices().powerManagerInternal);
2487 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002488
2489 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002490 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2491 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002492 reset(getServices().powerManagerInternal);
2493 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002494
2495 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002496 reset(getServices().powerManagerInternal);
2497 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002498
Pavel Grafov28939982017-10-03 15:11:52 +01002499 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2500 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2501 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002502 reset(getServices().powerManagerInternal);
2503 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002504
2505 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002506 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2507 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002508 reset(getServices().powerManagerInternal);
2509 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002510
Pavel Grafov28939982017-10-03 15:11:52 +01002511 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002512 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002513 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2514 verifyStayOnWhilePluggedCleared(false);
2515 }
2516
2517 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2518 // uses separate challenge.
2519 public void testSetMaximumTimeToLockProfile() throws Exception {
2520 final int PROFILE_USER = 15;
2521 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2522 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2523 mContext.binder.callingUid = PROFILE_ADMIN;
2524 final DevicePolicyManagerInternal dpmi =
2525 LocalServices.getService(DevicePolicyManagerInternal.class);
2526
2527 dpm.setMaximumTimeToLock(admin1, 0);
2528
2529 reset(getServices().powerManagerInternal);
2530 reset(getServices().settings);
2531
2532 // First add timeout for the profile.
2533 dpm.setMaximumTimeToLock(admin1, 10);
2534 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2535
2536 reset(getServices().powerManagerInternal);
2537 reset(getServices().settings);
2538
2539 // Add separate challenge
2540 when(getServices().lockPatternUtils
2541 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2542 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2543
2544 verifyScreenTimeoutCall(10L, PROFILE_USER);
2545 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2546
2547 reset(getServices().powerManagerInternal);
2548 reset(getServices().settings);
2549
2550 // Remove the timeout.
2551 dpm.setMaximumTimeToLock(admin1, 0);
2552 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2553 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2554
2555 reset(getServices().powerManagerInternal);
2556 reset(getServices().settings);
2557
2558 // Add it back.
2559 dpm.setMaximumTimeToLock(admin1, 10);
2560 verifyScreenTimeoutCall(10L, PROFILE_USER);
2561 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2562
2563 reset(getServices().powerManagerInternal);
2564 reset(getServices().settings);
2565
2566 // Remove separate challenge.
2567 reset(getServices().lockPatternUtils);
2568 when(getServices().lockPatternUtils
2569 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2570 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2571
2572 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2573 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2574
2575 reset(getServices().powerManagerInternal);
2576 reset(getServices().settings);
2577
2578 // Remove the timeout.
2579 dpm.setMaximumTimeToLock(admin1, 0);
2580 verifyScreenTimeoutCall(null, PROFILE_USER);
2581 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002582 }
2583
Michal Karpinski943aabd2016-10-06 11:09:25 +01002584 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2585 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2586 setupDeviceOwner();
2587 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2588
Michal Karpinskid084ca52017-01-18 15:54:18 +00002589 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2590 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2591 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2592 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2593 - ONE_MINUTE;
2594
2595 // verify that the minimum timeout cannot be modified on user builds (system property is
2596 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002597 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002598
2599 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2600 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2601 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2602
Pavel Grafov75c0a892017-05-18 17:28:27 +01002603 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002604
2605 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002606 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002607
Michal Karpinskid084ca52017-01-18 15:54:18 +00002608 // reset to default (0 means the admin is not participating, so default should be returned)
2609 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002610
2611 // aggregation should be the default if unset by any admin
2612 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2613 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2614
2615 // admin not participating by default
2616 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2617
2618 //clamping from the top
2619 dpm.setRequiredStrongAuthTimeout(admin1,
2620 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2621 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2622 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2623 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2624 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2625
Michal Karpinskid084ca52017-01-18 15:54:18 +00002626 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002627 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2628 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2629 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2630 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2631
2632 // clamping from the bottom
2633 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2634 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2635 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2636
Michal Karpinskid084ca52017-01-18 15:54:18 +00002637 // values within range
2638 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2639 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2640 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2641
2642 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2643 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2644 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002645
2646 // reset to default
2647 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2648 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2649 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2650 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2651
2652 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002653 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2654 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002655 }
2656
Pavel Grafov28939982017-10-03 15:11:52 +01002657 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002658 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002659 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002660 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002661 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002662 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002663 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002664 }
Pavel Grafov28939982017-10-03 15:11:52 +01002665 }
2666
2667 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002668 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2669 // UnfinishedVerificationException.
2670 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002671
Esteban Talavera01576862016-12-15 11:16:44 +00002672 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002673 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002674 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002675 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002676 .thenReturn(false);
2677 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002678 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2679 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002680 .thenReturn(true);
2681 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2682
2683 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002684 }
Victor Chang3e794af2016-03-04 13:48:17 +00002685
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002686 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2687 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002688 mContext.packageName = admin1.getPackageName();
2689 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002690 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2691 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2692 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2693 false);
2694 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2695 }
2696
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002697 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2698 setup_DeviceAdminFeatureOff();
2699 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2700 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2701 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2702 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2703 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2704 assertCheckProvisioningPreCondition(
2705 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2706 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2707 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2708 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2709 }
2710
Esteban Talavera01576862016-12-15 11:16:44 +00002711 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002712 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002713 .thenReturn(false);
2714 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002715 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2716 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002717 .thenReturn(true);
2718 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2719
2720 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002721 }
Victor Chang3e794af2016-03-04 13:48:17 +00002722
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002723 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2724 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002725 mContext.packageName = admin1.getPackageName();
2726 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002727 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2728 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2729 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2730 false);
2731 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2732
2733 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002734 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002735 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2736 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2737 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2738 true);
2739 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2740 }
2741
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002742 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2743 setup_ManagedProfileFeatureOff();
2744 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2745 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2746 DevicePolicyManager.CODE_OK);
2747 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2748 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2749 assertCheckProvisioningPreCondition(
2750 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2751 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2752 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2753 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2754
2755 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002756 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002757 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2758 DevicePolicyManager.CODE_OK);
2759 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2760 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2761 assertCheckProvisioningPreCondition(
2762 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2763 DevicePolicyManager.CODE_OK);
2764 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2765 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2766 }
2767
Esteban Talavera01576862016-12-15 11:16:44 +00002768 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002769 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002770 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002771 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2772 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002773 .thenReturn(true);
2774 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2775
2776 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002777 }
Victor Chang3e794af2016-03-04 13:48:17 +00002778
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002779 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2780 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002781 mContext.packageName = admin1.getPackageName();
2782 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2784 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2786 false /* because of non-split user */);
2787 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2788 false /* because of non-split user */);
2789 }
2790
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002791 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002792 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002793 setup_nonSplitUser_firstBoot_primaryUser();
2794 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2795 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2796 DevicePolicyManager.CODE_OK);
2797 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2798 DevicePolicyManager.CODE_OK);
2799 assertCheckProvisioningPreCondition(
2800 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2801 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2802 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2803 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2804 }
2805
Esteban Talavera01576862016-12-15 11:16:44 +00002806 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002807 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002808 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002809 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2810 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002811 .thenReturn(true);
2812 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2813
2814 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002815 }
Victor Chang3e794af2016-03-04 13:48:17 +00002816
Nicolas Prevot45d29072017-01-18 16:11:19 +00002817 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2818 setDeviceOwner();
2819 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2820 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2821 }
2822
2823 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2824 setup_nonSplitUser_withDo_primaryUser();
2825 final int MANAGED_PROFILE_USER_ID = 18;
2826 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2827 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002828 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002829 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002830 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002831 true)).thenReturn(true);
2832 }
2833
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002834 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2835 throws Exception {
2836 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002837 mContext.packageName = admin1.getPackageName();
2838 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002839 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2840 false/* because of completed device setup */);
2841 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2842 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2843 false/* because of non-split user */);
2844 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2845 false/* because of non-split user */);
2846 }
2847
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002848 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2849 throws Exception {
2850 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2851 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2852 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2853 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2854 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2855 DevicePolicyManager.CODE_OK);
2856 assertCheckProvisioningPreCondition(
2857 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2858 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2859 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2860 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2861 }
2862
Nicolas Prevot45d29072017-01-18 16:11:19 +00002863 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2864 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002865 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002866 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2867
2868 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2869 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002870 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002871
2872 // COMP mode is allowed.
2873 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2874 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002875 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002876
Nicolas Prevot45d29072017-01-18 16:11:19 +00002877 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002878 assertCheckProvisioningPreCondition(
2879 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002880 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002881 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002882 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2883 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2884 }
Esteban Talavera01576862016-12-15 11:16:44 +00002885
Nicolas Prevot45d29072017-01-18 16:11:19 +00002886 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2887 setup_nonSplitUser_withDo_primaryUser();
2888 mContext.packageName = admin1.getPackageName();
2889 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2890 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2891 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002892 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002893 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2894 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2895 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002896 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002897 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2898 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2899 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2900 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2901 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002902 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002903 assertCheckProvisioningPreCondition(
2904 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002905 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002906 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002907 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2908 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2909 }
Esteban Talavera01576862016-12-15 11:16:44 +00002910
Nicolas Prevot45d29072017-01-18 16:11:19 +00002911 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2912 throws Exception {
2913 setup_nonSplitUser_withDo_primaryUser();
2914 mContext.packageName = admin1.getPackageName();
2915 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002916 // The DO should not be allowed to initiate provisioning if the restriction is set by
2917 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002918 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002919 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2920 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2921 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002922 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002923 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2924 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2925 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2926 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2927 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002928 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2929
2930 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002931 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002932 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002933 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002934 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2935 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2936 }
2937
2938 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2939 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2940 mContext.packageName = admin1.getPackageName();
2941 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2942
2943 // We can delete the managed profile to create a new one, so provisioning is allowed.
2944 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2945 DevicePolicyManager.CODE_OK);
2946 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2947 assertCheckProvisioningPreCondition(
2948 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2949 DpmMockContext.ANOTHER_PACKAGE_NAME,
2950 DevicePolicyManager.CODE_OK);
2951 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2952 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2953 }
2954
2955 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2956 throws Exception {
2957 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2958 mContext.packageName = admin1.getPackageName();
2959 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002960 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002961 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2962 eq(UserHandle.SYSTEM)))
2963 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002964 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002965 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2966 eq(UserHandle.SYSTEM)))
2967 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002968
2969 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002970 assertCheckProvisioningPreCondition(
2971 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2972 DpmMockContext.ANOTHER_PACKAGE_NAME,
2973 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2974 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2975 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002976
2977 // But the device owner can still do it because it has set the restriction itself.
2978 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2979 DevicePolicyManager.CODE_OK);
2980 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002981 }
2982
2983 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002984 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002985 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002986 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2987 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002988 .thenReturn(false);
2989 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2990
2991 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002992 }
Victor Chang3e794af2016-03-04 13:48:17 +00002993
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002994 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2995 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002996 mContext.packageName = admin1.getPackageName();
2997 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002998 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2999 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3000 false /* because canAddMoreManagedProfiles returns false */);
3001 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3002 true);
3003 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3004 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003005 }
3006
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003007 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3008 throws Exception {
3009 setup_splitUser_firstBoot_systemUser();
3010 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3011 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3012 DevicePolicyManager.CODE_OK);
3013 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003014 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003015 assertCheckProvisioningPreCondition(
3016 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3017 DevicePolicyManager.CODE_OK);
3018 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3019 DevicePolicyManager.CODE_SYSTEM_USER);
3020 }
3021
Esteban Talavera01576862016-12-15 11:16:44 +00003022 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003023 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003024 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003025 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3026 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003027 .thenReturn(false);
3028 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3029
3030 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003031 }
Victor Chang3e794af2016-03-04 13:48:17 +00003032
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003033 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3034 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003035 mContext.packageName = admin1.getPackageName();
3036 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003037 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3038 true/* it's undefined behavior. Can be changed into false in the future */);
3039 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3040 false /* because canAddMoreManagedProfiles returns false */);
3041 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3042 true/* it's undefined behavior. Can be changed into false in the future */);
3043 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3044 false/* because calling uid is system user */);
3045 }
3046
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003047 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3048 throws Exception {
3049 setup_splitUser_afterDeviceSetup_systemUser();
3050 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3051 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3052 DevicePolicyManager.CODE_OK);
3053 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003054 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003055 assertCheckProvisioningPreCondition(
3056 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3057 DevicePolicyManager.CODE_OK);
3058 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3059 DevicePolicyManager.CODE_SYSTEM_USER);
3060 }
3061
Esteban Talavera01576862016-12-15 11:16:44 +00003062 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003063 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003064 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003065 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3066 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003067 true)).thenReturn(true);
3068 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3069
3070 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003071 }
Victor Chang3e794af2016-03-04 13:48:17 +00003072
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003073 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3074 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003075 mContext.packageName = admin1.getPackageName();
3076 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003077 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3078 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3079 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3080 true);
3081 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003082 }
3083
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003084 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003085 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003086 setup_splitUser_firstBoot_primaryUser();
3087 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3088 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3089 DevicePolicyManager.CODE_OK);
3090 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3091 DevicePolicyManager.CODE_OK);
3092 assertCheckProvisioningPreCondition(
3093 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3094 DevicePolicyManager.CODE_OK);
3095 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3096 DevicePolicyManager.CODE_OK);
3097 }
3098
Esteban Talavera01576862016-12-15 11:16:44 +00003099 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003100 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003101 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003102 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3103 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003104 true)).thenReturn(true);
3105 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3106
3107 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003108 }
Victor Chang3e794af2016-03-04 13:48:17 +00003109
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003110 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3111 throws Exception {
3112 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003113 mContext.packageName = admin1.getPackageName();
3114 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003115 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3116 true/* it's undefined behavior. Can be changed into false in the future */);
3117 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3118 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3119 true/* it's undefined behavior. Can be changed into false in the future */);
3120 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3121 false/* because user setup completed */);
3122 }
3123
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003124 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003125 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003126 setup_splitUser_afterDeviceSetup_primaryUser();
3127 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3128 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3129 DevicePolicyManager.CODE_OK);
3130 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3131 DevicePolicyManager.CODE_OK);
3132 assertCheckProvisioningPreCondition(
3133 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3134 DevicePolicyManager.CODE_OK);
3135 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3136 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3137 }
3138
Esteban Talavera01576862016-12-15 11:16:44 +00003139 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003140 setDeviceOwner();
3141
Pavel Grafov75c0a892017-05-18 17:28:27 +01003142 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003143 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003144 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3145 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003146 .thenReturn(false);
3147 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3148
3149 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003150 }
Victor Chang3e794af2016-03-04 13:48:17 +00003151
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003152 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3153 throws Exception {
3154 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003155 mContext.packageName = admin1.getPackageName();
3156 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003157 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3158 false /* can't provision managed profile on system user */);
3159 }
3160
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003161 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003162 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003163 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3164 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3165 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3166 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3167 }
3168
3169 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003170 setDeviceOwner();
3171
Pavel Grafov75c0a892017-05-18 17:28:27 +01003172 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003173 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003174 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3175 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003176 true)).thenReturn(true);
3177 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3178
3179 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003180 }
Victor Chang3e794af2016-03-04 13:48:17 +00003181
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003182 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3183 throws Exception {
3184 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003185 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3186 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003187 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3188 }
3189
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003190 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003191 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003192 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3193 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003194
3195 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003196 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3197 DevicePolicyManager.CODE_OK);
3198 }
3199
3200 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003201 setDeviceOwner();
3202
Pavel Grafov75c0a892017-05-18 17:28:27 +01003203 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003204 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003205 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3206 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003207 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3208 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003209 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003210 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003211 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003212 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003213 true)).thenReturn(true);
3214 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3215
3216 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003217 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003218
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003219 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3220 throws Exception {
3221 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003222 mContext.packageName = admin1.getPackageName();
3223 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003224 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3225 }
3226
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003227 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3228 throws Exception {
3229 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3230 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3231 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3232 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3233 }
3234
3235 public void testCheckProvisioningPreCondition_permission() {
3236 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003237 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3238 () -> dpm.checkProvisioningPreCondition(
3239 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003240 }
3241
Victor Chang3577ed22016-08-25 18:49:26 +01003242 public void testForceUpdateUserSetupComplete_permission() {
3243 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003244 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3245 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003246 }
3247
3248 public void testForceUpdateUserSetupComplete_systemUser() {
3249 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3250 // GIVEN calling from user 20
3251 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003252 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3253 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003254 }
3255
3256 public void testForceUpdateUserSetupComplete_userbuild() {
3257 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3258 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3259
3260 final int userId = UserHandle.USER_SYSTEM;
3261 // GIVEN userComplete is false in SettingsProvider
3262 setUserSetupCompleteForUser(false, userId);
3263
3264 // GIVEN userComplete is true in DPM
3265 DevicePolicyManagerService.DevicePolicyData userData =
3266 new DevicePolicyManagerService.DevicePolicyData(userId);
3267 userData.mUserSetupComplete = true;
3268 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3269
3270 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003271 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003272
3273 assertTrue(dpms.hasUserSetupCompleted());
3274
3275 dpm.forceUpdateUserSetupComplete();
3276
3277 // THEN the state in dpms is not changed
3278 assertTrue(dpms.hasUserSetupCompleted());
3279 }
3280
3281 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3282 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3283 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3284
3285 final int userId = UserHandle.USER_SYSTEM;
3286 // GIVEN userComplete is false in SettingsProvider
3287 setUserSetupCompleteForUser(false, userId);
3288
3289 // GIVEN userComplete is true in DPM
3290 DevicePolicyManagerService.DevicePolicyData userData =
3291 new DevicePolicyManagerService.DevicePolicyData(userId);
3292 userData.mUserSetupComplete = true;
3293 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3294
3295 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003296 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003297
3298 assertTrue(dpms.hasUserSetupCompleted());
3299
3300 dpm.forceUpdateUserSetupComplete();
3301
3302 // THEN the state in dpms is not changed
3303 assertFalse(dpms.hasUserSetupCompleted());
3304 }
3305
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003306 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003307 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003308 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003309
3310 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3311 runAsCaller(mAdmin1Context, dpms, dpm -> {
3312 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3313 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003314 }
3315
3316 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3317 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3318 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003319
3320 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3321 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003322 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003323 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3324 .thenReturn(true);
3325
3326 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003327 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003328
3329 // Enabling logging should not change the timestamp.
3330 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003331 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003332 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003333 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003334 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003335 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003336
3337 // Retrieving the logs should update the timestamp.
3338 final long beforeRetrieval = System.currentTimeMillis();
3339 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003340 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003341 final long afterRetrieval = System.currentTimeMillis();
3342 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3343 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3344
3345 // Retrieving the pre-boot logs should update the timestamp.
3346 Thread.sleep(2);
3347 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003348 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003349 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3350
3351 // Checking the timestamp again should not change it.
3352 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003353 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003354
3355 // Retrieving the logs again should update the timestamp.
3356 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003357 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003358 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3359
3360 // Disabling logging should not change the timestamp.
3361 Thread.sleep(2);
3362 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003363 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003364
3365 // Restarting the DPMS should not lose the timestamp.
3366 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003367 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003368
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003369 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3370 mContext.binder.callingUid = 1234567;
3371 mContext.callerPermissions.add(permission.MANAGE_USERS);
3372 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3373 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3374
3375 // System can retrieve the timestamp.
3376 mContext.binder.clearCallingIdentity();
3377 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3378
3379 // Removing the device owner should clear the timestamp.
3380 clearDeviceOwner();
3381 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003382 }
3383
yuemingw0de748d2017-11-15 19:22:27 +00003384 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3385 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3386 setupDeviceOwner();
3387 assertExpectException(SecurityException.class, null, () ->
3388 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3389 }
3390
3391 public void testSetSystemSettingFailWithPO() throws Exception {
3392 setupProfileOwner();
3393 assertExpectException(SecurityException.class, null, () ->
3394 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"));
3395 }
3396
3397 public void testSetSystemSetting() throws Exception {
3398 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3399 setupDeviceOwner();
3400 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3401 verify(getServices().settings).settingsSystemPutString(
3402 Settings.System.SCREEN_BRIGHTNESS, "0");
3403 }
3404
yuemingwe43cdf72017-10-12 16:52:11 +01003405 public void testSetTime() throws Exception {
3406 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3407 setupDeviceOwner();
3408 dpm.setTime(admin1, 0);
3409 verify(getServices().alarmManager).setTime(0);
3410 }
3411
3412 public void testSetTimeFailWithPO() throws Exception {
3413 setupProfileOwner();
3414 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3415 }
3416
3417 public void testSetTimeWithAutoTimeOn() throws Exception {
3418 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3419 setupDeviceOwner();
3420 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3421 .thenReturn(1);
3422 assertFalse(dpm.setTime(admin1, 0));
3423 }
3424
3425 public void testSetTimeZone() throws Exception {
3426 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3427 setupDeviceOwner();
3428 dpm.setTimeZone(admin1, "Asia/Shanghai");
3429 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3430 }
3431
3432 public void testSetTimeZoneFailWithPO() throws Exception {
3433 setupProfileOwner();
3434 assertExpectException(SecurityException.class, null,
3435 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3436 }
3437
3438 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3439 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3440 setupDeviceOwner();
3441 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3442 .thenReturn(1);
3443 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3444 }
3445
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003446 public void testGetLastBugReportRequestTime() throws Exception {
3447 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3448 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003449
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003450 mContext.packageName = admin1.getPackageName();
3451 mContext.applicationInfo = new ApplicationInfo();
3452 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3453 .thenReturn(Color.WHITE);
3454 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3455 anyObject())).thenReturn(Color.WHITE);
3456
Esteban Talaverad36dd152016-12-15 08:51:45 +00003457 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3458 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003459 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003460
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003461 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003462 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003463
3464 // Requesting a bug report should update the timestamp.
3465 final long beforeRequest = System.currentTimeMillis();
3466 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003467 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003468 final long afterRequest = System.currentTimeMillis();
3469 assertTrue(bugReportRequestTime >= beforeRequest);
3470 assertTrue(bugReportRequestTime <= afterRequest);
3471
3472 // Checking the timestamp again should not change it.
3473 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003474 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003475
3476 // Restarting the DPMS should not lose the timestamp.
3477 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003478 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003479
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003480 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3481 mContext.binder.callingUid = 1234567;
3482 mContext.callerPermissions.add(permission.MANAGE_USERS);
3483 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3484 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3485
3486 // System can retrieve the timestamp.
3487 mContext.binder.clearCallingIdentity();
3488 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3489
3490 // Removing the device owner should clear the timestamp.
3491 clearDeviceOwner();
3492 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003493 }
3494
3495 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3496 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3497 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003498 mContext.packageName = admin1.getPackageName();
3499 mContext.applicationInfo = new ApplicationInfo();
3500 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3501 .thenReturn(Color.WHITE);
3502 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3503 anyObject())).thenReturn(Color.WHITE);
3504
3505 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3506 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003507 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003508 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003509 .thenReturn(true);
3510
3511 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003512 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003513
3514 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3515 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003516 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003517
3518 // Enabling logging should not change the timestamp.
3519 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003520 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003521
3522 // Retrieving the logs should update the timestamp.
3523 final long beforeRetrieval = System.currentTimeMillis();
3524 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003525 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003526 final long afterRetrieval = System.currentTimeMillis();
3527 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3528 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3529
3530 // Checking the timestamp again should not change it.
3531 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003532 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003533
3534 // Retrieving the logs again should update the timestamp.
3535 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003536 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003537 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3538
3539 // Disabling logging should not change the timestamp.
3540 Thread.sleep(2);
3541 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003542 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003543
3544 // Restarting the DPMS should not lose the timestamp.
3545 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003546 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3547
3548 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3549 mContext.binder.callingUid = 1234567;
3550 mContext.callerPermissions.add(permission.MANAGE_USERS);
3551 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3552 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3553
3554 // System can retrieve the timestamp.
3555 mContext.binder.clearCallingIdentity();
3556 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3557
3558 // Removing the device owner should clear the timestamp.
3559 clearDeviceOwner();
3560 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003561 }
3562
Tony Mak2f26b792016-11-28 17:54:51 +00003563 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3564 // Setup device owner.
3565 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3566 setupDeviceOwner();
3567
3568 // Only device owner is setup, the result list should be empty.
3569 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3570 MoreAsserts.assertEmpty(targetUsers);
3571
3572 // Setup a managed profile managed by the same admin.
3573 final int MANAGED_PROFILE_USER_ID = 15;
3574 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3575 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3576
3577 // Add a secondary user, it should never talk with.
3578 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003579 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003580
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003581 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3582 // other.
3583 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3584 MoreAsserts.assertEmpty(targetUsers);
3585
3586 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3587 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3588 MoreAsserts.assertEmpty(targetUsers);
3589
3590 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003591 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003592 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3593 dpm.setAffiliationIds(admin1, userAffiliationIds);
3594
3595 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3596 dpm.setAffiliationIds(admin1, userAffiliationIds);
3597
Tony Mak2f26b792016-11-28 17:54:51 +00003598 // Calling from device owner admin, the result list should just contain the managed
3599 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003600 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003601 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3602 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3603
3604 // Calling from managed profile admin, the result list should just contain the system
3605 // user id.
3606 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3607 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3608 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003609
3610 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003611 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003612
3613 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3614 // to each other.
3615 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3616 MoreAsserts.assertEmpty(targetUsers);
3617
3618 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3619 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3620 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003621 }
3622
3623 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3624 // Setup a device owner.
3625 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3626 setupDeviceOwner();
3627
3628 // Set up a managed profile managed by different package.
3629 final int MANAGED_PROFILE_USER_ID = 15;
3630 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3631 final ComponentName adminDifferentPackage =
3632 new ComponentName("another.package", "whatever.class");
3633 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3634
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003635 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003636 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003637 dpm.setAffiliationIds(admin1, userAffiliationIds);
3638
3639 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3640 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3641
Tony Mak2f26b792016-11-28 17:54:51 +00003642 // Calling from device owner admin, we should get zero bind device admin target users as
3643 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003644 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003645 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3646 MoreAsserts.assertEmpty(targetUsers);
3647
3648 // Calling from managed profile admin, we should still get zero target users for the same
3649 // reason.
3650 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3651 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3652 MoreAsserts.assertEmpty(targetUsers);
3653 }
3654
Jason Parks3c13b642017-11-28 15:39:43 -06003655 private void verifyLockTaskState(int userId) throws Exception {
3656 verifyLockTaskState(userId, new String[0], DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
3657 }
3658
3659 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3660 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
3661 verify(getServices().iactivityManager).updateLockTaskFeatures(userId, flags);
3662 }
3663
3664 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3665 int flags) throws Exception {
3666 mContext.binder.callingUid = uid;
3667 dpm.setLockTaskPackages(who, packages);
3668 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3669 for (String p : packages) {
3670 assertTrue(dpm.isLockTaskPermitted(p));
3671 }
3672 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3673 // Test to see if set lock task features can be set
3674 dpm.setLockTaskFeatures(who, flags);
3675 verifyLockTaskState(userId, packages, flags);
3676 }
3677
3678 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3679 int flags) throws Exception {
3680 mContext.binder.callingUid = uid;
3681 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3682 () -> dpm.setLockTaskPackages(who, packages));
3683 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3684 () -> dpm.getLockTaskPackages(who));
3685 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3686 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3687 () -> dpm.setLockTaskFeatures(who, flags));
3688 }
3689
Charles Hee078db72017-10-19 18:03:20 +01003690 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003691 // Setup a device owner.
3692 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3693 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003694 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003695 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003696
3697 // Set up a managed profile managed by different package (package name shouldn't matter)
3698 final int MANAGED_PROFILE_USER_ID = 15;
3699 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3700 final ComponentName adminDifferentPackage =
3701 new ComponentName("another.package", "whatever.class");
3702 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003703 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3704
3705 // Setup a PO on the secondary user
3706 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3707 setAsProfileOwner(admin3);
3708 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003709
3710 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003711 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003712 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Charles Hee078db72017-10-19 18:03:20 +01003713 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
Jason Parks3c13b642017-11-28 15:39:43 -06003714 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3715
3716 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3717 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3718 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3719 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003720
3721 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3722 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3723 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003724 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3725 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
Jason Parks3c13b642017-11-28 15:39:43 -06003726 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003727
3728 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003729 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003730 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3731 dpm.setAffiliationIds(admin1, userAffiliationIds);
3732
3733 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3734 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3735
3736 // Now the managed profile can set lock task packages.
3737 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3738 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3739 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3740 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003741 // And it can set lock task features.
3742 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003743 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003744
3745 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003746 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003747 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3748 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003749 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3750 MANAGED_PROFILE_USER_ID, new String[0]);
3751 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3752 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003753
Jason Parks3c13b642017-11-28 15:39:43 -06003754 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003755 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3756 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003757
3758 }
3759
3760 public void testLockTaskPolicyForProfileOwner() throws Exception {
3761 // Setup a PO
3762 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3763 setAsProfileOwner(admin1);
3764 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3765
3766 final String[] poPackages = {"poPackage1", "poPackage2"};
3767 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3768 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3769 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3770 poPackages, poFlags);
3771
3772 // Set up a managed profile managed by different package (package name shouldn't matter)
3773 final int MANAGED_PROFILE_USER_ID = 15;
3774 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3775 final ComponentName adminDifferentPackage =
3776 new ComponentName("another.package", "whatever.class");
3777 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3778 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3779
3780 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3781 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3782 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3783 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3784 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3785 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003786 }
3787
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003788 public void testIsDeviceManaged() throws Exception {
3789 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3790 setupDeviceOwner();
3791
3792 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3793 // find out that the device has a device owner.
3794 assertTrue(dpm.isDeviceManaged());
3795 mContext.binder.callingUid = 1234567;
3796 mContext.callerPermissions.add(permission.MANAGE_USERS);
3797 assertTrue(dpm.isDeviceManaged());
3798 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3799 mContext.binder.clearCallingIdentity();
3800 assertTrue(dpm.isDeviceManaged());
3801
3802 clearDeviceOwner();
3803
3804 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3805 // not have a device owner.
3806 mContext.binder.callingUid = 1234567;
3807 mContext.callerPermissions.add(permission.MANAGE_USERS);
3808 assertFalse(dpm.isDeviceManaged());
3809 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3810 mContext.binder.clearCallingIdentity();
3811 assertFalse(dpm.isDeviceManaged());
3812 }
3813
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003814 public void testDeviceOwnerOrganizationName() throws Exception {
3815 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3816 setupDeviceOwner();
3817
3818 dpm.setOrganizationName(admin1, "organization");
3819
3820 // Device owner can retrieve organization managing the device.
3821 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3822
3823 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3824 mContext.binder.callingUid = 1234567;
3825 mContext.callerPermissions.add(permission.MANAGE_USERS);
3826 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3827 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3828
3829 // System can retrieve organization managing the device.
3830 mContext.binder.clearCallingIdentity();
3831 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3832
3833 // Removing the device owner clears the organization managing the device.
3834 clearDeviceOwner();
3835 assertNull(dpm.getDeviceOwnerOrganizationName());
3836 }
3837
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003838 public void testWipeDataManagedProfile() throws Exception {
3839 final int MANAGED_PROFILE_USER_ID = 15;
3840 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3841 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3842 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3843
3844 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003845 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003846 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003847 // Get mock reason string since we throw an IAE with empty string input.
3848 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3849 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003850
3851 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003852 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003853 MANAGED_PROFILE_USER_ID);
3854 }
3855
3856 public void testWipeDataManagedProfileDisallowed() throws Exception {
3857 final int MANAGED_PROFILE_USER_ID = 15;
3858 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3859 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3860
3861 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003862 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003863 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3864
Pavel Grafov75c0a892017-05-18 17:28:27 +01003865 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003866 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3867 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3868 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003869 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3870 thenReturn("Just a test string.");
3871
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003872 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003873 // The PO is not allowed to remove the profile if the user restriction was set on the
3874 // profile by the system
3875 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3876 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003877 }
3878
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003879 public void testWipeDataDeviceOwner() throws Exception {
3880 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003881 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003882 UserManager.DISALLOW_FACTORY_RESET,
3883 UserHandle.SYSTEM))
3884 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003885 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3886 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003887
3888 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003889 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003890 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3891 /*wipeEuicc=*/ eq(false));
3892 }
3893
3894 public void testWipeEuiccDataEnabled() throws Exception {
3895 setDeviceOwner();
3896 when(getServices().userManager.getUserRestrictionSource(
3897 UserManager.DISALLOW_FACTORY_RESET,
3898 UserHandle.SYSTEM))
3899 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003900 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3901 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003902
3903 dpm.wipeData(WIPE_EUICC);
3904 verify(getServices().recoverySystem).rebootWipeUserData(
3905 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3906 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003907 }
3908
3909 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3910 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003911 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003912 UserManager.DISALLOW_FACTORY_RESET,
3913 UserHandle.SYSTEM))
3914 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003915 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3916 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003917 // The DO is not allowed to wipe the device if the user restriction was set
3918 // by the system
3919 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3920 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003921 }
3922
3923 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3924 final int MANAGED_PROFILE_USER_ID = 15;
3925 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3926 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3927
3928 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003929 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003930 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3931
Pavel Grafov75c0a892017-05-18 17:28:27 +01003932 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003933 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3934 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3935 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3936
3937 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3938 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3939
3940 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3941 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3942 // Failed password attempts on the parent user are taken into account, as there isn't a
3943 // separate work challenge.
3944 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3945 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3946 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3947
3948 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3949 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003950 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003951 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003952 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003953 }
3954
3955 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3956 throws Exception {
3957 final int MANAGED_PROFILE_USER_ID = 15;
3958 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3959 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3960
3961 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003962 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003963 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3964
Pavel Grafov75c0a892017-05-18 17:28:27 +01003965 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003966 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3967 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3968 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3969
3970 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3971 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3972
3973 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3974 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3975 // Failed password attempts on the parent user are taken into account, as there isn't a
3976 // separate work challenge.
3977 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3978 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3979 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3980
3981 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3982 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003983 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003984 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003985 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003986 }
3987
3988 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3989 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003990 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003991 UserManager.DISALLOW_FACTORY_RESET,
3992 UserHandle.SYSTEM))
3993 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3994
3995 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3996
3997 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3998 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3999 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4000 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4001 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4002
4003 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4004 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004005 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004006 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4007 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004008 }
4009
4010 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4011 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004012 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004013 UserManager.DISALLOW_FACTORY_RESET,
4014 UserHandle.SYSTEM))
4015 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4016
4017 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4018
4019 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4020 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4021 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4022 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4023 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4024
4025 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004026 verifyZeroInteractions(getServices().recoverySystem);
4027 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004028 .removeUserEvenWhenDisallowed(anyInt());
4029 }
4030
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004031 public void testGetPermissionGrantState() throws Exception {
4032 final String permission = "some.permission";
4033 final String app1 = "com.example.app1";
4034 final String app2 = "com.example.app2";
4035
Pavel Grafov75c0a892017-05-18 17:28:27 +01004036 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004037 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004038 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004039 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004040 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004041 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4042 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004043 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004044 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004045 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004046 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004047 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004048 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4049
4050 // System can retrieve permission grant state.
4051 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004052 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004053 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4054 dpm.getPermissionGrantState(null, app1, permission));
4055 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4056 dpm.getPermissionGrantState(null, app2, permission));
4057
4058 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004059 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4060 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004061 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4062 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004063
4064 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004065 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4066 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004067 setAsProfileOwner(admin1);
4068 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4069 dpm.getPermissionGrantState(admin1, app1, permission));
4070 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4071 dpm.getPermissionGrantState(admin1, app2, permission));
4072 }
4073
Rubin Xuaab7a412016-12-30 21:13:29 +00004074 public void testResetPasswordWithToken() throws Exception {
4075 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4076 setupDeviceOwner();
4077 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004078 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4079 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4080
Rubin Xuaab7a412016-12-30 21:13:29 +00004081 // test adding a token
4082 final byte[] token = new byte[32];
4083 final long handle = 123456;
4084 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01004085 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004086 .thenReturn(handle);
4087 assertTrue(dpm.setResetPasswordToken(admin1, token));
4088
4089 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004090 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004091 .thenReturn(true);
4092 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4093
4094 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004095 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01004096 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
4097 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004098 eq(UserHandle.USER_SYSTEM)))
4099 .thenReturn(true);
4100 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4101
4102 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004103 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004104 .thenReturn(true);
4105 assertTrue(dpm.clearResetPasswordToken(admin1));
4106 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004107
Alexandru-Andrei Rotaru7f31bb02017-09-07 16:29:48 +01004108 public void testSetPasswordBlacklistCannotBeCalledByNonAdmin() throws Exception {
4109 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4110 () -> dpm.setPasswordBlacklist(admin1, null, null));
4111 verifyZeroInteractions(getServices().passwordBlacklist);
4112 }
4113
4114 public void testClearingPasswordBlacklistDoesNotCreateNewBlacklist() throws Exception {
4115 setupProfileOwner();
4116 dpm.setPasswordBlacklist(admin1, null, null);
4117 verifyZeroInteractions(getServices().passwordBlacklist);
4118 }
4119
4120 public void testSetPasswordBlacklistCreatesNewBlacklist() throws Exception {
4121 final String name = "myblacklist";
4122 final List<String> explicit = Arrays.asList("password", "letmein");
4123 setupProfileOwner();
4124 dpm.setPasswordBlacklist(admin1, name, explicit);
4125 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, explicit);
4126 }
4127
4128 public void testSetPasswordBlacklistOnlyConvertsExplicitToLowerCase() throws Exception {
4129 final List<String> mixedCase = Arrays.asList("password", "LETMEIN", "FooTBAll");
4130 final List<String> lowerCase = Arrays.asList("password", "letmein", "football");
4131 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4132 setupDeviceOwner();
4133 final String name = "Name of the Blacklist";
4134 dpm.setPasswordBlacklist(admin1, name, mixedCase);
4135 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, lowerCase);
4136 }
4137
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004138 public void testIsActivePasswordSufficient() throws Exception {
4139 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4140 mContext.packageName = admin1.getPackageName();
4141 setupDeviceOwner();
4142
4143 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4144 dpm.setPasswordMinimumLength(admin1, 8);
4145 dpm.setPasswordMinimumLetters(admin1, 6);
4146 dpm.setPasswordMinimumLowerCase(admin1, 3);
4147 dpm.setPasswordMinimumUpperCase(admin1, 1);
4148 dpm.setPasswordMinimumNonLetter(admin1, 1);
4149 dpm.setPasswordMinimumNumeric(admin1, 1);
4150 dpm.setPasswordMinimumSymbols(admin1, 0);
4151
Rubin Xucc391c22018-01-02 20:37:35 +00004152 reset(mContext.spiedContext);
4153
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004154 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4155 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4156 8, 2,
4157 6, 1,
4158 0, 1);
4159
4160 setActivePasswordState(passwordMetricsNoSymbols);
4161 assertTrue(dpm.isActivePasswordSufficient());
4162
4163 initializeDpms();
4164 reset(mContext.spiedContext);
4165 assertTrue(dpm.isActivePasswordSufficient());
4166
4167 // This call simulates the user entering the password for the first time after a reboot.
4168 // This causes password metrics to be reloaded into memory. Until this happens,
4169 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4170 // even if the DPC changes password requirements so that the password no longer meets the
4171 // requirements. This is a known limitation of the current implementation of
4172 // isActivePasswordSufficient() - see b/34218769.
4173 setActivePasswordState(passwordMetricsNoSymbols);
4174 assertTrue(dpm.isActivePasswordSufficient());
4175
4176 dpm.setPasswordMinimumSymbols(admin1, 1);
4177 // This assertion would fail if we had not called setActivePasswordState() again after
4178 // initializeDpms() - see previous comment.
4179 assertFalse(dpm.isActivePasswordSufficient());
4180
4181 initializeDpms();
4182 reset(mContext.spiedContext);
4183 assertFalse(dpm.isActivePasswordSufficient());
4184
4185 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4186 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4187 7, 2,
4188 5, 1,
4189 1, 2);
4190
4191 setActivePasswordState(passwordMetricsWithSymbols);
4192 assertTrue(dpm.isActivePasswordSufficient());
4193 }
4194
Pavel Grafov75c0a892017-05-18 17:28:27 +01004195 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4196 throws Exception {
4197 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004198 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004199
Pavel Grafov75c0a892017-05-18 17:28:27 +01004200 dpm.setActivePasswordState(passwordMetrics, userHandle);
4201 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004202
Rubin Xucc391c22018-01-02 20:37:35 +00004203 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4204 // reportPasswordChanged()
4205 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
4206 MockUtils.checkIntentAction(
4207 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4208 MockUtils.checkUserHandle(userHandle));
4209
Pavel Grafov75c0a892017-05-18 17:28:27 +01004210 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4211 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004212 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004213
4214 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4215 MockUtils.checkIntent(intent),
4216 MockUtils.checkUserHandle(userHandle));
4217
4218 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4219 // let it finish with system uid, otherwise it will throw and crash.
4220 flushTasks();
4221
4222 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004223 }
4224
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004225 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4226 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4227 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4228 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4229 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4230 DpmMockContext.SYSTEM_UID);
4231 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4232 DpmMockContext.SYSTEM_UID);
4233
4234 // Set up a device owner.
4235 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004236 setupDeviceOwner();
4237
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004238 // First and second user set IMEs manually.
4239 mContext.binder.callingUid = firstUserSystemUid;
4240 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4241 mContext.binder.callingUid = secondUserSystemUid;
4242 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004243
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004244 // Device owner changes IME for first user.
4245 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004246 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004247 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004248 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004249 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004250 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004251 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004252 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4253 mContext.binder.callingUid = firstUserSystemUid;
4254 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4255 mContext.binder.callingUid = secondUserSystemUid;
4256 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004257
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004258 // Second user changes IME manually.
4259 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4260 mContext.binder.callingUid = firstUserSystemUid;
4261 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4262 mContext.binder.callingUid = secondUserSystemUid;
4263 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004264
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004265 // First user changes IME manually.
4266 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4267 mContext.binder.callingUid = firstUserSystemUid;
4268 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4269 mContext.binder.callingUid = secondUserSystemUid;
4270 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004271
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004272 // Device owner changes IME for first user again.
4273 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004274 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004275 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004276 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004277 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004278 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004279 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4280 mContext.binder.callingUid = firstUserSystemUid;
4281 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4282 mContext.binder.callingUid = secondUserSystemUid;
4283 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004284
4285 // Restarting the DPMS should not lose information.
4286 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004287 mContext.binder.callingUid = firstUserSystemUid;
4288 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4289 mContext.binder.callingUid = secondUserSystemUid;
4290 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004291
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004292 // Device owner can find out whether it set the current IME itself.
4293 mContext.binder.callingUid = deviceOwnerUid;
4294 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004295
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004296 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004297 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004298 mContext.binder.callingUid = firstUserSystemUid;
4299 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4300 mContext.binder.callingUid = secondUserSystemUid;
4301 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004302 }
4303
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004304 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4305 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4306 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4307 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4308 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4309 DpmMockContext.SYSTEM_UID);
4310 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4311 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004312
4313 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004314 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004315 setupProfileOwner();
4316
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004317 // First and second user set IMEs manually.
4318 mContext.binder.callingUid = firstUserSystemUid;
4319 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4320 mContext.binder.callingUid = secondUserSystemUid;
4321 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004322
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004323 // Profile owner changes IME for second user.
4324 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004325 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004326 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004327 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004328 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004329 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004330 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004331 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4332 mContext.binder.callingUid = firstUserSystemUid;
4333 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4334 mContext.binder.callingUid = secondUserSystemUid;
4335 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004336
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004337 // First user changes IME manually.
4338 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4339 mContext.binder.callingUid = firstUserSystemUid;
4340 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4341 mContext.binder.callingUid = secondUserSystemUid;
4342 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004343
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004344 // Second user changes IME manually.
4345 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4346 mContext.binder.callingUid = firstUserSystemUid;
4347 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4348 mContext.binder.callingUid = secondUserSystemUid;
4349 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004350
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004351 // Profile owner changes IME for second user again.
4352 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004353 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004354 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004355 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004356 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004357 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004358 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4359 mContext.binder.callingUid = firstUserSystemUid;
4360 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4361 mContext.binder.callingUid = secondUserSystemUid;
4362 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004363
4364 // Restarting the DPMS should not lose information.
4365 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004366 mContext.binder.callingUid = firstUserSystemUid;
4367 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4368 mContext.binder.callingUid = secondUserSystemUid;
4369 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004370
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004371 // Profile owner can find out whether it set the current IME itself.
4372 mContext.binder.callingUid = profileOwnerUid;
4373 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004374
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004375 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004376 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004377 mContext.binder.callingUid = firstUserSystemUid;
4378 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4379 mContext.binder.callingUid = secondUserSystemUid;
4380 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004381 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004382
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004383 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4384 throws Exception {
4385 // Set up a device owner.
4386 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4387 setupDeviceOwner();
4388 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4389 }
4390
4391 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4392 throws Exception {
4393 // Set up a profile owner.
4394 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4395 setupProfileOwner();
4396 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4397 }
4398
4399 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4400 int adminUid) throws Exception {
4401 mContext.binder.callingUid = adminUid;
4402 final int userId = UserHandle.getUserId(adminUid);
4403
4404 final String packageName = "some.package";
4405 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4406 admin1, Collections.singletonList(packageName)));
4407 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4408
4409 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4410 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4411
4412 // Attempt to set to empty list (which means no listener is whitelisted)
4413 mContext.binder.callingUid = adminUid;
4414 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004415 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004416 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4417
4418 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4419 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4420 }
4421
4422 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4423 // Set up a managed profile
4424 final int MANAGED_PROFILE_USER_ID = 15;
4425 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4426 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4427 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4428
4429 final String permittedListener = "some.package";
4430 setupPackageInPackageManager(
4431 permittedListener,
4432 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4433 /*appId=*/ 12345, /*flags=*/ 0);
4434
4435 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4436 admin1, Collections.singletonList(permittedListener)));
4437
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004438 // isNotificationListenerServicePermitted should throw if not called from System.
4439 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4440 () -> dpms.isNotificationListenerServicePermitted(
4441 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004442
4443 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4444 assertTrue(dpms.isNotificationListenerServicePermitted(
4445 permittedListener, MANAGED_PROFILE_USER_ID));
4446 }
4447
4448 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4449 throws Exception {
4450 // Set up a managed profile
4451 final int MANAGED_PROFILE_USER_ID = 15;
4452 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4453 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4454 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4455
4456 final String permittedListener = "permitted.package";
4457 int appId = 12345;
4458 setupPackageInPackageManager(
4459 permittedListener,
4460 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4461 appId, /*flags=*/ 0);
4462
4463 final String notPermittedListener = "not.permitted.package";
4464 setupPackageInPackageManager(
4465 notPermittedListener,
4466 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4467 ++appId, /*flags=*/ 0);
4468
4469 final String systemListener = "system.package";
4470 setupPackageInPackageManager(
4471 systemListener,
4472 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4473 ++appId, ApplicationInfo.FLAG_SYSTEM);
4474
4475 // By default all packages are allowed
4476 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4477
4478 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4479 assertTrue(dpms.isNotificationListenerServicePermitted(
4480 permittedListener, MANAGED_PROFILE_USER_ID));
4481 assertTrue(dpms.isNotificationListenerServicePermitted(
4482 notPermittedListener, MANAGED_PROFILE_USER_ID));
4483 assertTrue(dpms.isNotificationListenerServicePermitted(
4484 systemListener, MANAGED_PROFILE_USER_ID));
4485
4486 // Setting only one package in the whitelist
4487 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4488 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4489 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004490 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004491 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4492 assertEquals(1, permittedListeners.size());
4493 assertEquals(permittedListener, permittedListeners.get(0));
4494
4495 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4496 assertTrue(dpms.isNotificationListenerServicePermitted(
4497 permittedListener, MANAGED_PROFILE_USER_ID));
4498 assertFalse(dpms.isNotificationListenerServicePermitted(
4499 notPermittedListener, MANAGED_PROFILE_USER_ID));
4500 // System packages are always allowed (even if not in the whitelist)
4501 assertTrue(dpms.isNotificationListenerServicePermitted(
4502 systemListener, MANAGED_PROFILE_USER_ID));
4503
4504 // Setting an empty whitelist - only system listeners allowed
4505 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4506 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004507 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004508 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4509
4510 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4511 assertFalse(dpms.isNotificationListenerServicePermitted(
4512 permittedListener, MANAGED_PROFILE_USER_ID));
4513 assertFalse(dpms.isNotificationListenerServicePermitted(
4514 notPermittedListener, MANAGED_PROFILE_USER_ID));
4515 // System packages are always allowed (even if not in the whitelist)
4516 assertTrue(dpms.isNotificationListenerServicePermitted(
4517 systemListener, MANAGED_PROFILE_USER_ID));
4518
4519 // Setting a null whitelist - all listeners allowed
4520 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4521 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4522 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4523
4524 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4525 assertTrue(dpms.isNotificationListenerServicePermitted(
4526 permittedListener, MANAGED_PROFILE_USER_ID));
4527 assertTrue(dpms.isNotificationListenerServicePermitted(
4528 notPermittedListener, MANAGED_PROFILE_USER_ID));
4529 assertTrue(dpms.isNotificationListenerServicePermitted(
4530 systemListener, MANAGED_PROFILE_USER_ID));
4531 }
4532
4533 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4534 throws Exception {
4535 // Set up a managed profile
4536 final int MANAGED_PROFILE_USER_ID = 15;
4537 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4538 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4539 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4540
4541 final String nonSystemPackage = "non.system.package";
4542 int appId = 12345;
4543 setupPackageInPackageManager(
4544 nonSystemPackage,
4545 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4546 appId, /*flags=*/ 0);
4547
4548 final String systemListener = "system.package";
4549 setupPackageInPackageManager(
4550 systemListener,
4551 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4552 ++appId, ApplicationInfo.FLAG_SYSTEM);
4553
4554 // By default all packages are allowed (for all profiles)
4555 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4556
4557 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4558 assertTrue(dpms.isNotificationListenerServicePermitted(
4559 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4560 assertTrue(dpms.isNotificationListenerServicePermitted(
4561 systemListener, MANAGED_PROFILE_USER_ID));
4562 assertTrue(dpms.isNotificationListenerServicePermitted(
4563 nonSystemPackage, UserHandle.USER_SYSTEM));
4564 assertTrue(dpms.isNotificationListenerServicePermitted(
4565 systemListener, UserHandle.USER_SYSTEM));
4566
4567 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4568 // all allowed in primary profile
4569 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4570 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004571 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004572 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4573
4574 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4575 assertFalse(dpms.isNotificationListenerServicePermitted(
4576 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4577 assertTrue(dpms.isNotificationListenerServicePermitted(
4578 systemListener, MANAGED_PROFILE_USER_ID));
4579 assertTrue(dpms.isNotificationListenerServicePermitted(
4580 nonSystemPackage, UserHandle.USER_SYSTEM));
4581 assertTrue(dpms.isNotificationListenerServicePermitted(
4582 systemListener, UserHandle.USER_SYSTEM));
4583 }
4584
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004585 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004586 mServiceContext.packageName = mRealTestContext.getPackageName();
4587 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4588 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004589 setDeviceOwner();
4590
Pavel Grafov75c0a892017-05-18 17:28:27 +01004591 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004592 }
4593
4594 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004595 mServiceContext.packageName = mRealTestContext.getPackageName();
4596 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4597 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004598 setAsProfileOwner(admin1);
4599
Pavel Grafov75c0a892017-05-18 17:28:27 +01004600 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4601 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004602 }
4603
4604 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004605 mServiceContext.packageName = mRealTestContext.getPackageName();
4606 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4607 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004608 setAsProfileOwner(admin1);
4609
Pavel Grafov75c0a892017-05-18 17:28:27 +01004610 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4611 caller.packageName = "com.example.delegate";
4612 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4613 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004614
Pavel Grafov75c0a892017-05-18 17:28:27 +01004615 // Make caller a delegated cert installer.
4616 runAsCaller(mAdmin1Context, dpms,
4617 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004618
4619 verifyCanGetOwnerInstalledCaCerts(null, caller);
4620 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004621 }
4622
Rubin Xucc391c22018-01-02 20:37:35 +00004623 public void testDisallowSharingIntoProfileSetRestriction() {
4624 Bundle restriction = new Bundle();
4625 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4626
4627 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4628 RestrictionsListener listener = new RestrictionsListener(mContext);
4629 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4630 new Bundle());
4631 verifyDataSharingChangedBroadcast();
4632 }
4633
4634 public void testDisallowSharingIntoProfileClearRestriction() {
4635 Bundle restriction = new Bundle();
4636 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4637
4638 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4639 RestrictionsListener listener = new RestrictionsListener(mContext);
4640 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4641 restriction);
4642 verifyDataSharingChangedBroadcast();
4643 }
4644
4645 public void testDisallowSharingIntoProfileUnchanged() {
4646 RestrictionsListener listener = new RestrictionsListener(mContext);
4647 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4648 new Bundle());
4649 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4650 }
4651
4652 private void verifyDataSharingChangedBroadcast() {
4653 Intent expectedIntent = new Intent(
4654 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4655 expectedIntent.setPackage("com.android.managedprovisioning");
4656 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4657 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4658 MockUtils.checkIntent(expectedIntent),
4659 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4660 }
4661
Robin Lee2c68dad2017-03-17 12:50:24 +00004662 private void verifyCanGetOwnerInstalledCaCerts(
4663 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004664 final String alias = "cert";
4665 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004666
4667 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004668 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004669 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4670 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004671 }
4672 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4673
4674 // caller: device admin or delegated certificate installer
4675 callerContext.applicationInfo = new ApplicationInfo();
4676 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4677
4678 // system_server
4679 final DpmMockContext serviceContext = mContext;
4680 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004681 getServices().addPackageContext(callerUser, admin1Context);
4682 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004683
4684 // Install a CA cert.
4685 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004686 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004687 .thenReturn(alias);
4688 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004689 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004690 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004691 });
4692
Pavel Grafov75c0a892017-05-18 17:28:27 +01004693 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4694 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4695 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004696 flushTasks();
4697
Robin Lee2c68dad2017-03-17 12:50:24 +00004698 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4699
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004700 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004701 runAsCaller(admin1Context, dpms, (dpm) -> {
4702 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004703 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004704 ownerInstalledCaCerts.addAll(installedCaCerts);
4705 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004706
4707 // Restarting the DPMS should not lose information.
4708 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004709 runAsCaller(admin1Context, dpms, (dpm) ->
4710 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004711
4712 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004713 runAsCaller(serviceContext, dpms, (dpm) -> {
4714 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004715
Robin Lee2c68dad2017-03-17 12:50:24 +00004716 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004717 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004718 });
4719
Pavel Grafov75c0a892017-05-18 17:28:27 +01004720 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4721 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4722 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004723 flushTasks();
4724
4725 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4726 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004727 runAsCaller(admin1Context, dpms, (dpm) -> {
4728 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4729 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004730 }
4731
Robin Lee2c68dad2017-03-17 12:50:24 +00004732 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4733 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004734 final String alias = "cert";
4735 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004736
4737 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004738 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004739 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4740 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004741 }
4742 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4743
4744 // caller: device admin or delegated certificate installer
4745 callerContext.applicationInfo = new ApplicationInfo();
4746 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4747
4748 // system_server
4749 final DpmMockContext serviceContext = mContext;
4750 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004751 getServices().addPackageContext(callerUser, admin1Context);
4752 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004753
4754 // Install a CA cert as caller
4755 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004756 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004757 .thenReturn(alias);
4758 assertTrue(dpm.installCaCert(callerName, caCert));
4759 });
4760
4761 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004762 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004763 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004764 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4765 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4766 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004767 flushTasks();
4768
Robin Lee2c68dad2017-03-17 12:50:24 +00004769 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004770 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004771
4772 runAsCaller(serviceContext, dpms, (dpm) -> {
4773 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4774 assertNotNull(ownerInstalledCaCerts);
4775 assertTrue(ownerInstalledCaCerts.isEmpty());
4776 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004777 }
4778
Eran Messeri94d56762017-12-21 20:50:54 +00004779 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4780 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4781 Arrays.sort(gotFlags);
4782 Arrays.sort(expectedFlags);
4783 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4784 }
4785
4786 public void testTranslationOfIdAttestationFlag() {
4787 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4788 int[] correspondingAttUtilsTypes = new int[]{
4789 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4790 AttestationUtils.ID_TYPE_MEID};
4791
4792 // Test translation of zero flags
4793 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4794
4795 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4796 // non-null array
4797 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4798
4799 // Test translation of a single flag
4800 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4801 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4802 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4803
4804 // Test translation of two flags
4805 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4806 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4807 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4808 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4809
4810 // Test translation of all three flags
4811 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4812 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4813 AttestationUtils.ID_TYPE_MEID});
4814 // Test translation of all three flags
4815 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4816 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4817 AttestationUtils.ID_TYPE_MEID});
4818 }
4819
Victor Chang3e794af2016-03-04 13:48:17 +00004820 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004821 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004822 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4823 dpms.notifyChangeToContentObserver(
4824 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4825 }
4826
4827 private void assertProvisioningAllowed(String action, boolean expected) {
4828 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4829 dpm.isProvisioningAllowed(action));
4830 }
Tony Mak2f26b792016-11-28 17:54:51 +00004831
Nicolas Prevot45d29072017-01-18 16:11:19 +00004832 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4833 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004834 final String previousPackageName = mContext.packageName;
4835 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004836
4837 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4838 mContext.packageName = packageName;
4839 mMockContext.binder.callingUid = uid;
4840 assertProvisioningAllowed(action, expected);
4841
4842 // Set the previous package name / calling uid to go back to the initial state.
4843 mContext.packageName = previousPackageName;
4844 mMockContext.binder.callingUid = previousUid;
4845 }
4846
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004847 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004848 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4849 }
4850
4851 private void assertCheckProvisioningPreCondition(
4852 String action, String packageName, int provisioningCondition) {
4853 assertEquals("checkProvisioningPreCondition("
4854 + action + ", " + packageName + ") returning unexpected result",
4855 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004856 }
4857
Tony Mak2f26b792016-11-28 17:54:51 +00004858 /**
4859 * Setup a managed profile with the specified admin and its uid.
4860 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4861 * @param adminUid uid of the admin package.
4862 * @param copyFromAdmin package information for {@code admin} will be built based on this
4863 * component's information.
4864 */
4865 private void addManagedProfile(
4866 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4867 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004868 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004869 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4870 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4871 dpm.setActiveAdmin(admin, false, userId);
4872 assertTrue(dpm.setProfileOwner(admin, null, userId));
4873 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4874 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004875
4876 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004877 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004878 */
Robin Leeabaa0692017-02-20 20:54:22 +00004879 private static StringParceledListSlice asSlice(String[] s) {
4880 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004881 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004882
4883 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004884 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4885 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004886
Robin Lee2c68dad2017-03-17 12:50:24 +00004887 // We can't let exceptions happen on the background thread. Throw them here if they happen
4888 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004889 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004890 }
Victor Chang3e794af2016-03-04 13:48:17 +00004891}