blob: 58ac7d28eadee416a2cb7afcd29ef38d4e3544f4 [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;
47import static org.mockito.Mockito.verifyZeroInteractions;
48import static org.mockito.Mockito.when;
49import static org.mockito.hamcrest.MockitoHamcrest.argThat;
50
Makoto Onukif76b06a2015-09-22 15:03:44 -070051import android.Manifest.permission;
52import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000053import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070054import android.app.admin.DeviceAdminReceiver;
55import android.app.admin.DevicePolicyManager;
56import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010057import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070058import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070059import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000060import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000061import android.content.pm.ApplicationInfo;
62import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070063import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010064import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000065import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000066import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010067import android.graphics.Color;
68import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080069import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080070import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070071import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080072import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070073import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070074import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010075import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080076import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010077import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000078import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000079import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080080import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000081import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010082import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070083import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070084
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010085import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000086import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000087import com.android.server.LocalServices;
88import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000089import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000090
Robin Lee7f5c91c2017-02-08 21:27:02 +000091import org.hamcrest.BaseMatcher;
92import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070093import org.mockito.invocation.InvocationOnMock;
94import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095
Makoto Onukic8a5a552015-11-19 14:29:12 -080096import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000097import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000098import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070099import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700101import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100102import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000103import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700104
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700105/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700106 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000107 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108 m FrameworksServicesTests &&
109 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000110 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800112 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113
114 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000115 *
116 * , or:
117 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000119@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100120@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000122 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
123 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
124 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100125 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
126 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000127
Pavel Grafov75c0a892017-05-18 17:28:27 +0100128 // TODO replace all instances of this with explicit {@link #mServiceContext}.
129 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700130 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100131
132 private DpmMockContext mServiceContext;
133 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700134 public DevicePolicyManager dpm;
135 public DevicePolicyManagerServiceTestable dpms;
136
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100137 /*
138 * The CA cert below is the content of cacert.pem as generated by:
139 *
140 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
141 */
142 private static final String TEST_CA =
143 "-----BEGIN CERTIFICATE-----\n" +
144 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
145 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
146 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
147 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
148 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
149 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
150 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
151 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
152 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
153 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
154 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
155 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
156 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
157 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
158 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
159 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
160 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
161 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
162 "wQ==\n" +
163 "-----END CERTIFICATE-----\n";
164
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700165 @Override
166 protected void setUp() throws Exception {
167 super.setUp();
168
169 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100170 mServiceContext = mContext;
171 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
172 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700173 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100174 doReturn(Collections.singletonList(new ResolveInfo()))
175 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
176 any(Intent.class),
177 anyInt(),
178 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700179
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800180 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100181 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800182
Makoto Onukia52562c2015-10-01 16:12:31 -0700183 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700184
Makoto Onukid932f762015-09-29 16:53:38 -0700185 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
186 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
187 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800188 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700189
Pavel Grafov75c0a892017-05-18 17:28:27 +0100190 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
191 mAdmin1Context.packageName = admin1.getPackageName();
192 mAdmin1Context.applicationInfo = new ApplicationInfo();
193 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
194
Makoto Onukib643fb02015-09-22 15:03:44 -0700195 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700196 }
197
Robin Lee2c68dad2017-03-17 12:50:24 +0000198 @Override
199 protected void tearDown() throws Exception {
200 flushTasks();
201 super.tearDown();
202 }
203
Makoto Onukia52562c2015-10-01 16:12:31 -0700204 private void initializeDpms() {
205 // Need clearCallingIdentity() to pass permission checks.
206 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100207 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700208
Pavel Grafov75c0a892017-05-18 17:28:27 +0100209 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
210 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
211 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700212
Pavel Grafov75c0a892017-05-18 17:28:27 +0100213 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700214
Pavel Grafov75c0a892017-05-18 17:28:27 +0100215 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700216 }
217
Makoto Onukib643fb02015-09-22 15:03:44 -0700218 private void setUpUserManager() {
219 // Emulate UserManager.set/getApplicationRestriction().
220 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
221
222 // UM.setApplicationRestrictions() will save to appRestrictions.
223 doAnswer(new Answer<Void>() {
224 @Override
225 public Void answer(InvocationOnMock invocation) throws Throwable {
226 String pkg = (String) invocation.getArguments()[0];
227 Bundle bundle = (Bundle) invocation.getArguments()[1];
228 UserHandle user = (UserHandle) invocation.getArguments()[2];
229
230 appRestrictions.put(Pair.create(pkg, user), bundle);
231
232 return null;
233 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100234 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100235 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700236
237 // UM.getApplicationRestrictions() will read from appRestrictions.
238 doAnswer(new Answer<Bundle>() {
239 @Override
240 public Bundle answer(InvocationOnMock invocation) throws Throwable {
241 String pkg = (String) invocation.getArguments()[0];
242 UserHandle user = (UserHandle) invocation.getArguments()[1];
243
244 return appRestrictions.get(Pair.create(pkg, user));
245 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100246 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700247 anyString(), any(UserHandle.class));
248
Makoto Onukid932f762015-09-29 16:53:38 -0700249 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100250 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700251 }
252
253 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100254 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700255
Pavel Grafov75c0a892017-05-18 17:28:27 +0100256 mServiceContext.binder.callingUid =
257 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
258 runAsCaller(mServiceContext, dpms, dpm -> {
259 // PO needs to be a DA.
260 dpm.setActiveAdmin(admin, /*replace=*/ false);
261 // Fire!
262 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
263 // Check
264 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
265 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700266
Pavel Grafov75c0a892017-05-18 17:28:27 +0100267 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700268 }
269
270 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100271 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700272 .thenReturn(false);
273
274 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100275 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700276
277 // If the device has no DPMS feature, it shouldn't register the local service.
278 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
279 }
280
281 /**
282 * Caller doesn't have proper permissions.
283 */
284 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700285 // 1. Failure cases.
286
287 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100288 assertExpectException(SecurityException.class, /* messageRegex= */ null,
289 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700290
291 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
292 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100293
294 assertExpectException(SecurityException.class, /* messageRegex= */ null,
295 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700296 }
297
Makoto Onukif76b06a2015-09-22 15:03:44 -0700298 /**
299 * Test for:
300 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800301 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700302 * {@link DevicePolicyManager#isAdminActive}
303 * {@link DevicePolicyManager#isAdminActiveAsUser}
304 * {@link DevicePolicyManager#getActiveAdmins}
305 * {@link DevicePolicyManager#getActiveAdminsAsUser}
306 */
307 public void testSetActiveAdmin() throws Exception {
308 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700309 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
310
Makoto Onukif76b06a2015-09-22 15:03:44 -0700311 // 2. Call the API.
312 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700313
314 // 3. Verify internal calls.
315
316 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700317 verify(mContext.spiedContext).sendBroadcastAsUser(
318 MockUtils.checkIntentAction(
319 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
320 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
321 verify(mContext.spiedContext).sendBroadcastAsUser(
322 MockUtils.checkIntentAction(
323 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700324 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
325
Pavel Grafov75c0a892017-05-18 17:28:27 +0100326 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700327 eq(admin1.getPackageName()),
328 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
329 eq(PackageManager.DONT_KILL_APP),
330 eq(DpmMockContext.CALLER_USER_HANDLE),
331 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700332
333 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700334
335 // Make sure it's active admin1.
336 assertTrue(dpm.isAdminActive(admin1));
337 assertFalse(dpm.isAdminActive(admin2));
338 assertFalse(dpm.isAdminActive(admin3));
339
340 // But not admin1 for a different user.
341
342 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
343 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
344 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
345
346 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
347 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
348
349 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
350
351 // Next, add one more admin.
352 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700353 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700354 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700355
356 dpm.setActiveAdmin(admin2, /* replace =*/ false);
357
358 // Now we have two admins.
359 assertTrue(dpm.isAdminActive(admin1));
360 assertTrue(dpm.isAdminActive(admin2));
361 assertFalse(dpm.isAdminActive(admin3));
362
363 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
364 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100365 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700366 eq(admin1.getPackageName()),
367 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
368 eq(PackageManager.DONT_KILL_APP),
369 eq(DpmMockContext.CALLER_USER_HANDLE),
370 anyString());
371
372 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100373 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
374 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700375
376 // 5. Add the same admin1 again with replace, which should succeed.
377 dpm.setActiveAdmin(admin1, /* replace =*/ true);
378
379 // TODO make sure it's replaced.
380
381 // 6. Test getActiveAdmins()
382 List<ComponentName> admins = dpm.getActiveAdmins();
383 assertEquals(2, admins.size());
384 assertEquals(admin1, admins.get(0));
385 assertEquals(admin2, admins.get(1));
386
387 // Another user has no admins.
388 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
389
390 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
391 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
392
393 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
394 }
395
Makoto Onukid932f762015-09-29 16:53:38 -0700396 public void testSetActiveAdmin_multiUsers() throws Exception {
397
398 final int ANOTHER_USER_ID = 100;
399 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
400
Pavel Grafov75c0a892017-05-18 17:28:27 +0100401 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700402
403 // Set up pacakge manager for the other user.
404 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700405
406 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
407
408 dpm.setActiveAdmin(admin1, /* replace =*/ false);
409
410 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
411 dpm.setActiveAdmin(admin2, /* replace =*/ false);
412
413
414 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
415 assertTrue(dpm.isAdminActive(admin1));
416 assertFalse(dpm.isAdminActive(admin2));
417
418 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
419 assertFalse(dpm.isAdminActive(admin1));
420 assertTrue(dpm.isAdminActive(admin2));
421 }
422
Makoto Onukif76b06a2015-09-22 15:03:44 -0700423 /**
424 * Test for:
425 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800426 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700427 */
428 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
429 // 1. Make sure the caller has proper permissions.
430 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
431
432 dpm.setActiveAdmin(admin1, /* replace =*/ false);
433 assertTrue(dpm.isAdminActive(admin1));
434
435 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100436 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
437 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700438 }
439
440 /**
441 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800442 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
443 * BIND_DEVICE_ADMIN.
444 */
445 public void testSetActiveAdmin_permissionCheck() throws Exception {
446 // 1. Make sure the caller has proper permissions.
447 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
448
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100449 assertExpectException(IllegalArgumentException.class,
450 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
451 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800452 assertFalse(dpm.isAdminActive(adminNoPerm));
453
454 // Change the target API level to MNC. Now it can be set as DA.
455 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
456 VERSION_CODES.M);
457 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
458 assertTrue(dpm.isAdminActive(adminNoPerm));
459
460 // TODO Test the "load from the file" case where DA will still be loaded even without
461 // BIND_DEVICE_ADMIN and target API is N.
462 }
463
464 /**
465 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700466 * {@link DevicePolicyManager#removeActiveAdmin}
467 */
468 public void testRemoveActiveAdmin_SecurityException() {
469 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
470
471 // Add admin.
472
473 dpm.setActiveAdmin(admin1, /* replace =*/ false);
474
475 assertTrue(dpm.isAdminActive(admin1));
476
477 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
478
479 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100480 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
481 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700482
483 // Try to remove active admin with a different caller userid should fail too, without
484 // having MANAGE_DEVICE_ADMINS.
485 mContext.callerPermissions.clear();
486
Makoto Onukid932f762015-09-29 16:53:38 -0700487 // Change the caller, and call into DPMS directly with a different user-id.
488
Makoto Onukif76b06a2015-09-22 15:03:44 -0700489 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100490 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
491 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700492 }
493
494 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800495 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
496 * (because we can't send the remove broadcast).
497 */
498 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
499 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
500
501 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
502
503 // Add admin.
504
505 dpm.setActiveAdmin(admin1, /* replace =*/ false);
506
507 assertTrue(dpm.isAdminActive(admin1));
508
509 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
510
511 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100512 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800513 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100514 assertExpectException(IllegalStateException.class,
515 /* messageRegex= */ "User must be running and unlocked",
516 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800517
518 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
519
520 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100521 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800522 .thenReturn(true);
523
524 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700525 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800526 }
527
528 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700529 * Test for:
530 * {@link DevicePolicyManager#removeActiveAdmin}
531 */
Makoto Onukid932f762015-09-29 16:53:38 -0700532 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700533 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
534
535 // Add admin1.
536
537 dpm.setActiveAdmin(admin1, /* replace =*/ false);
538
539 assertTrue(dpm.isAdminActive(admin1));
540 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
541
542 // Different user, but should work, because caller has proper permissions.
543 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700544
545 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700546 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700547
548 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700549 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700550
551 // TODO DO Still can't be removed in this case.
552 }
553
554 /**
555 * Test for:
556 * {@link DevicePolicyManager#removeActiveAdmin}
557 */
558 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
559 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
560 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
561
562 // Add admin1.
563
564 dpm.setActiveAdmin(admin1, /* replace =*/ false);
565
566 assertTrue(dpm.isAdminActive(admin1));
567 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
568
569 // Broadcast from saveSettingsLocked().
570 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
571 MockUtils.checkIntentAction(
572 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
573 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
574
575 // Remove. No permissions, but same user, so it'll work.
576 mContext.callerPermissions.clear();
577 dpm.removeActiveAdmin(admin1);
578
Makoto Onukif76b06a2015-09-22 15:03:44 -0700579 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
580 MockUtils.checkIntentAction(
581 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
582 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
583 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700584 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700585 eq(dpms.mHandler),
586 eq(Activity.RESULT_OK),
587 isNull(String.class),
588 isNull(Bundle.class));
589
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700590 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700591
592 // Again broadcast from saveSettingsLocked().
593 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
594 MockUtils.checkIntentAction(
595 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
596 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
597
598 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700599 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700600
601 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000602 * Test for: @{link DevicePolicyManager#setActivePasswordState}
603 *
604 * Validates that when the password for a user changes, the notification broadcast intent
605 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
606 * addition to ones in the original user.
607 */
608 public void testSetActivePasswordState_sendToProfiles() throws Exception {
609 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
610
611 final int MANAGED_PROFILE_USER_ID = 78;
612 final int MANAGED_PROFILE_ADMIN_UID =
613 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
614
615 // Setup device owner.
616 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
617 mContext.packageName = admin1.getPackageName();
618 setupDeviceOwner();
619
620 // Add a managed profile belonging to the system user.
621 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
622
623 // Change the parent user's password.
624 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
625
626 // Both the device owner and the managed profile owner should receive this broadcast.
627 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
628 intent.setComponent(admin1);
629 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
630
631 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
632 MockUtils.checkIntent(intent),
633 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
634 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
635 MockUtils.checkIntent(intent),
636 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
637 }
638
639 /**
640 * Test for: @{link DevicePolicyManager#setActivePasswordState}
641 *
642 * Validates that when the password for a managed profile changes, the notification broadcast
643 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
644 * its parent.
645 */
646 public void testSetActivePasswordState_notSentToParent() throws Exception {
647 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
648
649 final int MANAGED_PROFILE_USER_ID = 78;
650 final int MANAGED_PROFILE_ADMIN_UID =
651 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
652
653 // Setup device owner.
654 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
655 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100656 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000657 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
658 setupDeviceOwner();
659
660 // Add a managed profile belonging to the system user.
661 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
662
663 // Change the profile's password.
664 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
665
666 // Both the device owner and the managed profile owner should receive this broadcast.
667 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
668 intent.setComponent(admin1);
669 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
670
671 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
672 MockUtils.checkIntent(intent),
673 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
674 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
675 MockUtils.checkIntent(intent),
676 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
677 }
678 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000679 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700680 */
681 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000682 setDeviceOwner();
683
684 // Try to set a profile owner on the same user, which should fail.
685 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
686 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100687 assertExpectException(IllegalStateException.class,
688 /* messageRegex= */ "already has a device owner",
689 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000690
691 // DO admin can't be deactivated.
692 dpm.removeActiveAdmin(admin1);
693 assertTrue(dpm.isAdminActive(admin1));
694
695 // TODO Test getDeviceOwnerName() too. To do so, we need to change
696 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
697 }
698
699 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700700 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800701 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700702 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
703 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
704
Makoto Onukid932f762015-09-29 16:53:38 -0700705 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700706 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
707
Makoto Onukid932f762015-09-29 16:53:38 -0700708 // Make sure admin1 is installed on system user.
709 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700710
Makoto Onukic8a5a552015-11-19 14:29:12 -0800711 // Check various get APIs.
712 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
713
Makoto Onukib643fb02015-09-22 15:03:44 -0700714 // DO needs to be an DA.
715 dpm.setActiveAdmin(admin1, /* replace =*/ false);
716
717 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700718 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700719
Makoto Onukic8a5a552015-11-19 14:29:12 -0800720 // getDeviceOwnerComponent should return the admin1 component.
721 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
722 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
723
724 // Check various get APIs.
725 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
726
727 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
728 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
729 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
730 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
731
732 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
733
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000734 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100735 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000736 eq(admin1.getPackageName()));
737
Makoto Onukib643fb02015-09-22 15:03:44 -0700738 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100739 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700740 eq(UserHandle.USER_SYSTEM), eq(false));
741
742 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
743 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
744 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
745
Makoto Onukic8a5a552015-11-19 14:29:12 -0800746 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700747 }
748
Makoto Onukic8a5a552015-11-19 14:29:12 -0800749 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
750 final int origCallingUser = mContext.binder.callingUid;
751 final List origPermissions = new ArrayList(mContext.callerPermissions);
752 mContext.callerPermissions.clear();
753
754 mContext.callerPermissions.add(permission.MANAGE_USERS);
755
756 mContext.binder.callingUid = Process.SYSTEM_UID;
757
758 // TODO Test getDeviceOwnerName() too. To do so, we need to change
759 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
760 if (hasDeviceOwner) {
761 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
762 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
763 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
764
765 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
766 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
767 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
768 } else {
769 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
770 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
771 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
772
773 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
774 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
775 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
776 }
777
778 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
779 if (hasDeviceOwner) {
780 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
781 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
782 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
783
784 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
785 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
786 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
787 } else {
788 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
789 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
790 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
791
792 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
793 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
794 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
795 }
796
797 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
798 // Still with MANAGE_USERS.
799 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
800 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
801 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
802
803 if (hasDeviceOwner) {
804 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
805 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
806 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
807 } else {
808 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
809 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
810 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
811 }
812
813 mContext.binder.callingUid = Process.SYSTEM_UID;
814 mContext.callerPermissions.remove(permission.MANAGE_USERS);
815 // System can still call "OnAnyUser" without MANAGE_USERS.
816 if (hasDeviceOwner) {
817 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
818 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
819 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
820
821 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
822 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
823 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
824 } else {
825 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
826 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
827 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
828
829 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
830 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
831 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
832 }
833
834 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
835 // Still no MANAGE_USERS.
836 if (hasDeviceOwner) {
837 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
838 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
839 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
840 } else {
841 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
842 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
843 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
844 }
845
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100846 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
847 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
848 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
849 dpm::getDeviceOwnerComponentOnAnyUser);
850 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
851 dpm::getDeviceOwnerUserId);
852 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
853 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800854
855 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
856 // Still no MANAGE_USERS.
857 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
858 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
859 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
860
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100861 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
862 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
863 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
864 dpm::getDeviceOwnerComponentOnAnyUser);
865 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
866 dpm::getDeviceOwnerUserId);
867 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
868 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800869
870 // Restore.
871 mContext.binder.callingUid = origCallingUser;
872 mContext.callerPermissions.addAll(origPermissions);
873 }
874
875
Makoto Onukib643fb02015-09-22 15:03:44 -0700876 /**
877 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
878 */
879 public void testSetDeviceOwner_noSuchPackage() {
880 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800881 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700882 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
883 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
884
885 // Call from a process on the system user.
886 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
887
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100888 assertExpectException(IllegalArgumentException.class,
889 /* messageRegex= */ "Invalid component",
890 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -0700891 }
892
893 public void testSetDeviceOwner_failures() throws Exception {
894 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
895 }
896
Makoto Onukia52562c2015-10-01 16:12:31 -0700897 public void testClearDeviceOwner() throws Exception {
898 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800899 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700900 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
901 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
902
903 // Set admin1 as a DA to the secondary user.
904 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
905
906 dpm.setActiveAdmin(admin1, /* replace =*/ false);
907
908 // Set admin 1 as the DO to the system user.
909
910 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
911 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
912 dpm.setActiveAdmin(admin1, /* replace =*/ false);
913 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
914
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000915 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100916 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000917 eq(admin1.getPackageName()));
918
Makoto Onukic8a5a552015-11-19 14:29:12 -0800919 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700920
Makoto Onuki90b89652016-01-28 14:44:18 -0800921 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100922 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000923 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800924
925 assertTrue(dpm.isAdminActive(admin1));
926 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
927
Makoto Onukia52562c2015-10-01 16:12:31 -0700928 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100929 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -0700930
931 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100932 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
933 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800934
935 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100936 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100937 assertExpectException(IllegalStateException.class,
938 /* messageRegex= */ "User must be running and unlocked",
939 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800940
Pavel Grafov75c0a892017-05-18 17:28:27 +0100941 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
942 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700943 dpm.clearDeviceOwnerApp(admin1.getPackageName());
944
945 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800946 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700947
Pavel Grafov75c0a892017-05-18 17:28:27 +0100948 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000949 eq(false),
950 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
951
Pavel Grafov75c0a892017-05-18 17:28:27 +0100952 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -0800953 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100954 eq(null),
955 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800956
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700957 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100958
959 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
960 // and once for clearing it.
961 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
962 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
963 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700964 // TODO Check other calls.
965 }
966
967 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
968 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800969 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700970 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
971 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
972
973 // Set admin1 as a DA to the secondary user.
974 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
975
976 dpm.setActiveAdmin(admin1, /* replace =*/ false);
977
978 // Set admin 1 as the DO to the system user.
979
980 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
981 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
982 dpm.setActiveAdmin(admin1, /* replace =*/ false);
983 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
984
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000985 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100986 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000987 eq(admin1.getPackageName()));
988
Makoto Onukic8a5a552015-11-19 14:29:12 -0800989 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700990
991 // Now call clear from the secondary user, which should throw.
992 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
993
994 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100995 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700996 eq(admin1.getPackageName()),
997 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100998 assertExpectException(SecurityException.class,
999 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1000 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001001
Makoto Onukic8a5a552015-11-19 14:29:12 -08001002 // DO shouldn't be removed.
1003 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001004 }
1005
Makoto Onukib643fb02015-09-22 15:03:44 -07001006 public void testSetProfileOwner() throws Exception {
1007 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001008
Makoto Onuki90b89652016-01-28 14:44:18 -08001009 // PO admin can't be deactivated.
1010 dpm.removeActiveAdmin(admin1);
1011 assertTrue(dpm.isAdminActive(admin1));
1012
Makoto Onuki803d6752015-10-30 12:58:39 -07001013 // Try setting DO on the same user, which should fail.
1014 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001015 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1016 runAsCaller(mServiceContext, dpms, dpm -> {
1017 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001018 assertExpectException(IllegalStateException.class,
1019 /* messageRegex= */ "already has a profile owner",
1020 () -> dpm.setDeviceOwner(admin2, "owner-name",
1021 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001022 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001023 }
1024
Makoto Onuki90b89652016-01-28 14:44:18 -08001025 public void testClearProfileOwner() throws Exception {
1026 setAsProfileOwner(admin1);
1027
1028 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1029
1030 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1031 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1032
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001033 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001034 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001035 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001036 assertExpectException(IllegalStateException.class,
1037 /* messageRegex= */ "User must be running and unlocked",
1038 () -> dpm.clearProfileOwner(admin1));
1039
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001040 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001041 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001042 dpm.clearProfileOwner(admin1);
1043
1044 // Check
1045 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001046 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001047 }
1048
Makoto Onukib643fb02015-09-22 15:03:44 -07001049 public void testSetProfileOwner_failures() throws Exception {
1050 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1051 }
1052
Makoto Onukia52562c2015-10-01 16:12:31 -07001053 public void testGetDeviceOwnerAdminLocked() throws Exception {
1054 checkDeviceOwnerWithMultipleDeviceAdmins();
1055 }
1056
1057 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1058 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1059 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1060 // make sure it gets the right component from the right user.
1061
1062 final int ANOTHER_USER_ID = 100;
1063 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1064
Pavel Grafov75c0a892017-05-18 17:28:27 +01001065 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001066
1067 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001068 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001069 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1070 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1071
1072 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1073
Pavel Grafov75c0a892017-05-18 17:28:27 +01001074 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001075
Makoto Onukia52562c2015-10-01 16:12:31 -07001076 // Make sure the admin packge is installed to each user.
1077 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1078 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1079
1080 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1081 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1082
1083 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1084
1085
1086 // Set active admins to the users.
1087 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1088 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1089
1090 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1091 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1092
1093 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1094
1095 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001096 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001097 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1098
Makoto Onukic8a5a552015-11-19 14:29:12 -08001099 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001100
1101 // Then check getDeviceOwnerAdminLocked().
1102 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1103 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1104 }
1105
1106 /**
1107 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001108 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1109 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001110 *
1111 * We didn't use to persist the DO component class name, but now we do, and the above method
1112 * finds the right component from a package name upon migration.
1113 */
1114 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001115 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001116 checkDeviceOwnerWithMultipleDeviceAdmins();
1117
1118 // Overwrite the device owner setting and clears the clas name.
1119 dpms.mOwners.setDeviceOwner(
1120 new ComponentName(admin2.getPackageName(), ""),
1121 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1122 dpms.mOwners.writeDeviceOwner();
1123
1124 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001125 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001126
1127 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001128 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001129 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001130 initializeDpms();
1131
1132 // Now the DO component name is a full name.
1133 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1134 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001135 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001136 }
1137
Makoto Onukib643fb02015-09-22 15:03:44 -07001138 public void testSetGetApplicationRestriction() {
1139 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001140 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001141
1142 {
1143 Bundle rest = new Bundle();
1144 rest.putString("KEY_STRING", "Foo1");
1145 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1146 }
1147
1148 {
1149 Bundle rest = new Bundle();
1150 rest.putString("KEY_STRING", "Foo2");
1151 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1152 }
1153
1154 {
1155 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1156 assertNotNull(returned);
1157 assertEquals(returned.size(), 1);
1158 assertEquals(returned.get("KEY_STRING"), "Foo1");
1159 }
1160
1161 {
1162 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1163 assertNotNull(returned);
1164 assertEquals(returned.size(), 1);
1165 assertEquals(returned.get("KEY_STRING"), "Foo2");
1166 }
1167
1168 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1169 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1170 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001171
Edman Anjosf9946772016-11-28 16:35:15 +01001172 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001173 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1174 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001175 *
1176 * @param packageName the name of the package to be setup
1177 * @param appId the application ID to be given to the package
1178 * @return the UID of the package as known by the mock package manager
1179 */
1180 private int setupPackageInPackageManager(final String packageName, final int appId)
1181 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001182 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001183 ApplicationInfo.FLAG_HAS_CODE);
1184 }
1185
1186 /**
1187 * Setup a package in the package manager mock. Useful for faking installed applications.
1188 *
1189 * @param packageName the name of the package to be setup
1190 * @param userId the user id where the package will be "installed"
1191 * @param appId the application ID to be given to the package
1192 * @param flags flags to set in the ApplicationInfo for this package
1193 * @return the UID of the package as known by the mock package manager
1194 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001195 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1196 int flags) throws Exception {
1197 final int uid = UserHandle.getUid(userId, appId);
1198 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001199 final PackageInfo pi = new PackageInfo();
1200 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001201 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001202 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001203 eq(packageName),
1204 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001205 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001206 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001207 eq(packageName),
1208 anyInt(),
1209 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001210 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001211 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001212 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001213 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001214 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001215 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001216 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001217 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001218 return uid;
1219 }
1220
Robin Lee7f5c91c2017-02-08 21:27:02 +00001221 public void testCertificateDisclosure() throws Exception {
1222 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1223 final UserHandle user = UserHandle.of(userId);
1224
1225 mContext.applicationInfo = new ApplicationInfo();
1226 mContext.callerPermissions.add(permission.MANAGE_USERS);
1227 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001228 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001229 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1230
Robin Leeabaa0692017-02-20 20:54:22 +00001231 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1232 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001233
1234 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1235 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1236
1237 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001238 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001239 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001240 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001241 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001242 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001243 .cancelAsUser(anyString(), anyInt(), eq(user));
1244
1245 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001246 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001247 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001248 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1249 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001250 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001251 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001252 .notifyAsUser(anyString(), anyInt(), argThat(
1253 new BaseMatcher<Notification>() {
1254 @Override
1255 public boolean matches(Object item) {
1256 final Notification noti = (Notification) item;
1257 return TEST_STRING.equals(
1258 noti.extras.getString(Notification.EXTRA_TITLE));
1259 }
1260 @Override
1261 public void describeTo(Description description) {
1262 description.appendText(
1263 "Notification{title=\"" + TEST_STRING + "\"}");
1264 }
1265 }), eq(user));
1266 }
1267
Edman Anjosf9946772016-11-28 16:35:15 +01001268 /**
1269 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1270 * privileges can acually be exercised by a delegate are not covered here.
1271 */
1272 public void testDelegation() throws Exception {
1273 setAsProfileOwner(admin1);
1274
1275 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1276
1277 // Given two packages
1278 final String CERT_DELEGATE = "com.delegate.certs";
1279 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1280 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1281 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1282 20989);
1283
1284 // On delegation
1285 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1286 mContext.packageName = admin1.getPackageName();
1287 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1288 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1289
1290 // DPMS correctly stores and retrieves the delegates
1291 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1292 assertEquals(2, policy.mDelegationMap.size());
1293 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1294 DELEGATION_CERT_INSTALL);
1295 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1296 DELEGATION_CERT_INSTALL);
1297 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1298 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1299 DELEGATION_APP_RESTRICTIONS);
1300 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1301 DELEGATION_APP_RESTRICTIONS);
1302 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1303
1304 // On calling install certificate APIs from an unauthorized process
1305 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1306 mContext.packageName = RESTRICTIONS_DELEGATE;
1307
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001308 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1309 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001310
1311 // On calling install certificate APIs from an authorized process
1312 mContext.binder.callingUid = CERT_DELEGATE_UID;
1313 mContext.packageName = CERT_DELEGATE;
1314
1315 // DPMS executes without a SecurityException
1316 try {
1317 dpm.installCaCert(null, null);
1318 } catch (SecurityException unexpected) {
1319 fail("Threw SecurityException on authorized access");
1320 } catch (NullPointerException expected) {
1321 }
1322
1323 // On removing a delegate
1324 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1325 mContext.packageName = admin1.getPackageName();
1326 dpm.setCertInstallerPackage(admin1, null);
1327
1328 // DPMS does not allow access to ex-delegate
1329 mContext.binder.callingUid = CERT_DELEGATE_UID;
1330 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001331 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1332 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001333
1334 // But still allows access to other existing delegates
1335 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1336 mContext.packageName = RESTRICTIONS_DELEGATE;
1337 try {
1338 dpm.getApplicationRestrictions(null, "pkg");
1339 } catch (SecurityException expected) {
1340 fail("Threw SecurityException on authorized access");
1341 }
1342 }
1343
Esteban Talaverabf60f722015-12-10 16:26:44 +00001344 public void testApplicationRestrictionsManagingApp() throws Exception {
1345 setAsProfileOwner(admin1);
1346
Rubin Xued1928a2016-02-11 17:23:06 +00001347 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001348 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001349 final String nonDelegateExceptionMessageRegex =
1350 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001351 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001352 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1353 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001354
Esteban Talaverabf60f722015-12-10 16:26:44 +00001355 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1356 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001357 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1358 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001359 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001360 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001361 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001362 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1363 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001364
1365 // Check via the profile owner that no restrictions were set.
1366 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001367 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001368 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1369
Rubin Xued1928a2016-02-11 17:23:06 +00001370 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001371 assertExpectException(PackageManager.NameNotFoundException.class,
1372 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1373 () -> dpm.setApplicationRestrictionsManagingPackage(
1374 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001375
Esteban Talaverabf60f722015-12-10 16:26:44 +00001376 // Let appRestrictionsManagerPackage manage app restrictions
1377 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1378 assertEquals(appRestrictionsManagerPackage,
1379 dpm.getApplicationRestrictionsManagingPackage(admin1));
1380
1381 // Now that package should be able to set and retrieve app restrictions.
1382 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001383 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001384 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1385 dpm.setApplicationRestrictions(null, "pkg1", rest);
1386 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1387 assertEquals(1, returned.size(), 1);
1388 assertEquals("Foo1", returned.get("KEY_STRING"));
1389
1390 // The same app running on a separate user shouldn't be able to manage app restrictions.
1391 mContext.binder.callingUid = UserHandle.getUid(
1392 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1393 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001394 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1395 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001396
1397 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1398 // too.
1399 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001400 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001401 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1402 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1403 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1404
1405 // Removing the ability for the package to manage app restrictions.
1406 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1407 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1408 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001409 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001410 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001411 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1412 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001413 }
1414
Makoto Onukia4f11972015-10-01 13:19:58 -07001415 public void testSetUserRestriction_asDo() throws Exception {
1416 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001417 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001418 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1419 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1420
1421 // First, set DO.
1422
1423 // Call from a process on the system user.
1424 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1425
1426 // Make sure admin1 is installed on system user.
1427 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001428
1429 // Call.
1430 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001431 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001432 UserHandle.USER_SYSTEM));
1433
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001434 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001435 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001436 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001437 DpmTestUtils.assertRestrictions(
1438 DpmTestUtils.newRestrictions(defaultRestrictions),
1439 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1440 );
1441 DpmTestUtils.assertRestrictions(
1442 DpmTestUtils.newRestrictions(defaultRestrictions),
1443 dpm.getUserRestrictions(admin1)
1444 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001445 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001446 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001447 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001448 eq(true) /* isDeviceOwner */,
1449 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001450 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001451 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001452
1453 for (String restriction : defaultRestrictions) {
1454 dpm.clearUserRestriction(admin1, restriction);
1455 }
1456
Esteban Talavera548a04b2016-12-20 15:22:30 +00001457 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001458 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001459
1460 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001461 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001462 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001463 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1464 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001465 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001466
Makoto Onukia4f11972015-10-01 13:19:58 -07001467 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001468 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001469 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001470 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1471 UserManager.DISALLOW_ADD_USER),
1472 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001473 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001474
Makoto Onuki068c54a2015-10-13 14:34:03 -07001475 DpmTestUtils.assertRestrictions(
1476 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001477 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001478 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1479 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001480 DpmTestUtils.assertRestrictions(
1481 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001482 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001483 dpm.getUserRestrictions(admin1)
1484 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001485
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001486 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001487 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001488 eq(UserHandle.USER_SYSTEM),
1489 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001490 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001491 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001492
Makoto Onuki068c54a2015-10-13 14:34:03 -07001493 DpmTestUtils.assertRestrictions(
1494 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1495 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1496 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001497 DpmTestUtils.assertRestrictions(
1498 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1499 dpm.getUserRestrictions(admin1)
1500 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001501
1502 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001503 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001504 eq(UserHandle.USER_SYSTEM),
1505 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001506 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001507 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001508
Esteban Talavera548a04b2016-12-20 15:22:30 +00001509 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001510
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001511 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1512 // DO sets them, the scope is global.
1513 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001514 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001515 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001516 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001517 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001518 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001519 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1520 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001521 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001522
1523 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1524 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001525 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001526
1527 // More tests.
1528 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001529 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001530 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001531 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1532 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001533 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001534
1535 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001536 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001537 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001538 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001539 UserManager.DISALLOW_ADD_USER),
1540 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001541 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001542
1543 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001544 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001545 eq(UserHandle.USER_SYSTEM),
1546 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001547 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001548 UserManager.DISALLOW_ADD_USER),
1549 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001550 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001551
1552 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1553 // locally.
1554 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001555 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001556
1557 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1558 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1559 dpm.setCameraDisabled(admin2, true);
1560
Pavel Grafov75c0a892017-05-18 17:28:27 +01001561 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001562 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001563 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001564 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001565 UserManager.DISALLOW_ADD_USER),
1566 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001567 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001568 // TODO Make sure restrictions are written to the file.
1569 }
1570
1571 public void testSetUserRestriction_asPo() {
1572 setAsProfileOwner(admin1);
1573
Makoto Onuki068c54a2015-10-13 14:34:03 -07001574 DpmTestUtils.assertRestrictions(
1575 DpmTestUtils.newRestrictions(),
1576 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1577 .ensureUserRestrictions()
1578 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001579
1580 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001581 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001582 eq(DpmMockContext.CALLER_USER_HANDLE),
1583 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001584 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001585 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001586
Makoto Onukia4f11972015-10-01 13:19:58 -07001587 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001588 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001589 eq(DpmMockContext.CALLER_USER_HANDLE),
1590 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1591 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001592 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001593 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001594
Makoto Onuki068c54a2015-10-13 14:34:03 -07001595 DpmTestUtils.assertRestrictions(
1596 DpmTestUtils.newRestrictions(
1597 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1598 UserManager.DISALLOW_OUTGOING_CALLS
1599 ),
1600 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1601 .ensureUserRestrictions()
1602 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001603 DpmTestUtils.assertRestrictions(
1604 DpmTestUtils.newRestrictions(
1605 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1606 UserManager.DISALLOW_OUTGOING_CALLS
1607 ),
1608 dpm.getUserRestrictions(admin1)
1609 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001610
1611 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001612 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001613 eq(DpmMockContext.CALLER_USER_HANDLE),
1614 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001615 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001616 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001617
1618 DpmTestUtils.assertRestrictions(
1619 DpmTestUtils.newRestrictions(
1620 UserManager.DISALLOW_OUTGOING_CALLS
1621 ),
1622 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1623 .ensureUserRestrictions()
1624 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001625 DpmTestUtils.assertRestrictions(
1626 DpmTestUtils.newRestrictions(
1627 UserManager.DISALLOW_OUTGOING_CALLS
1628 ),
1629 dpm.getUserRestrictions(admin1)
1630 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001631
1632 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001633 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001634 eq(DpmMockContext.CALLER_USER_HANDLE),
1635 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001636 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001637 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001638
Makoto Onuki068c54a2015-10-13 14:34:03 -07001639 DpmTestUtils.assertRestrictions(
1640 DpmTestUtils.newRestrictions(),
1641 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1642 .ensureUserRestrictions()
1643 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001644 DpmTestUtils.assertRestrictions(
1645 DpmTestUtils.newRestrictions(),
1646 dpm.getUserRestrictions(admin1)
1647 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001648
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1650 // though when DO sets them they'll be applied globally.
1651 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001652 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001654 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001655 eq(DpmMockContext.CALLER_USER_HANDLE),
1656 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1657 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001658 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001659 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001660
1661 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001662 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001663 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001664 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001665 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001666 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001667 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001668
Makoto Onukia4f11972015-10-01 13:19:58 -07001669 // TODO Make sure restrictions are written to the file.
1670 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001671
Esteban Talavera548a04b2016-12-20 15:22:30 +00001672
1673 public void testDefaultEnabledUserRestrictions() throws Exception {
1674 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1675 mContext.callerPermissions.add(permission.MANAGE_USERS);
1676 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1677 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1678
1679 // First, set DO.
1680
1681 // Call from a process on the system user.
1682 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1683
1684 // Make sure admin1 is installed on system user.
1685 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1686
1687 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1688 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1689 UserHandle.USER_SYSTEM));
1690
1691 // Check that the user restrictions that are enabled by default are set. Then unset them.
1692 String[] defaultRestrictions = UserRestrictionsUtils
1693 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1694 assertTrue(defaultRestrictions.length > 0);
1695 DpmTestUtils.assertRestrictions(
1696 DpmTestUtils.newRestrictions(defaultRestrictions),
1697 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1698 );
1699 DpmTestUtils.assertRestrictions(
1700 DpmTestUtils.newRestrictions(defaultRestrictions),
1701 dpm.getUserRestrictions(admin1)
1702 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001703 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001704 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001705 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001706 eq(true) /* isDeviceOwner */,
1707 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001708 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001709 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001710
1711 for (String restriction : defaultRestrictions) {
1712 dpm.clearUserRestriction(admin1, restriction);
1713 }
1714
1715 assertNoDeviceOwnerRestrictions();
1716
1717 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001718 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001719 initializeDpms();
1720 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1721 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1722
1723 assertNoDeviceOwnerRestrictions();
1724
1725 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1726 // is set as it wasn't enabled during setDeviceOwner.
1727 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1728 assertFalse(UserRestrictionsUtils
1729 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1730 UserRestrictionsUtils
1731 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1732 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001733 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001734 initializeDpms();
1735 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1736 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1737
1738 DpmTestUtils.assertRestrictions(
1739 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1740 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1741 );
1742 DpmTestUtils.assertRestrictions(
1743 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1744 dpm.getUserRestrictions(admin1)
1745 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001746 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001747 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001748 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001749 eq(true) /* isDeviceOwner */,
1750 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001751 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001752 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001753
1754 // Remove the restriction.
1755 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1756
1757 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1758 initializeDpms();
1759 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1760 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1761 assertNoDeviceOwnerRestrictions();
1762 } finally {
1763 UserRestrictionsUtils
1764 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1765 }
1766 }
1767
1768 private void assertNoDeviceOwnerRestrictions() {
1769 DpmTestUtils.assertRestrictions(
1770 DpmTestUtils.newRestrictions(),
1771 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1772 );
1773 DpmTestUtils.assertRestrictions(
1774 DpmTestUtils.newRestrictions(),
1775 dpm.getUserRestrictions(admin1)
1776 );
1777 }
1778
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001779 public void testGetMacAddress() throws Exception {
1780 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1781 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1782 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1783
1784 // In this test, change the caller user to "system".
1785 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1786
1787 // Make sure admin1 is installed on system user.
1788 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1789
1790 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001791 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1792 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001793
1794 // DO needs to be an DA.
1795 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1796 assertTrue(dpm.isAdminActive(admin1));
1797
1798 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001799 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1800 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001801
1802 // Test 3. Caller has PO, but not DO.
1803 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001804 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1805 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001806
1807 // Remove PO.
1808 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001809 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001810 // Test 4, Caller is DO now.
1811 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1812
1813 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001814 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001815
1816 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001817 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001818 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001819
1820 // 4-3. With a real MAC address.
1821 final WifiInfo wi = new WifiInfo();
1822 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001823 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001824 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001825 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001826
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001827 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001828 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1829 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1830
1831 // In this test, change the caller user to "system".
1832 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1833
1834 // Make sure admin1 is installed on system user.
1835 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1836
1837 // Set admin1 as DA.
1838 dpm.setActiveAdmin(admin1, false);
1839 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001840 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1841 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001842
1843 // Set admin1 as PO.
1844 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001845 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1846 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001847
1848 // Remove PO and add DO.
1849 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001850 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001851 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1852
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001853 // admin1 is DO.
1854 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001855 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001856 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001857 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1858 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001859
1860 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001861 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001862 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001863 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1864 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001865
1866 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001867 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001868 dpm.reboot(admin1);
1869 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001870
1871 public void testSetGetSupportText() {
1872 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1873 dpm.setActiveAdmin(admin1, true);
1874 dpm.setActiveAdmin(admin2, true);
1875 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1876
1877 // Null default support messages.
1878 {
1879 assertNull(dpm.getLongSupportMessage(admin1));
1880 assertNull(dpm.getShortSupportMessage(admin1));
1881 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1882 assertNull(dpm.getShortSupportMessageForUser(admin1,
1883 DpmMockContext.CALLER_USER_HANDLE));
1884 assertNull(dpm.getLongSupportMessageForUser(admin1,
1885 DpmMockContext.CALLER_USER_HANDLE));
1886 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1887 }
1888
1889 // Only system can call the per user versions.
1890 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001891 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1892 () -> dpm.getShortSupportMessageForUser(admin1,
1893 DpmMockContext.CALLER_USER_HANDLE));
1894 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1895 () -> dpm.getLongSupportMessageForUser(admin1,
1896 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00001897 }
1898
1899 // Can't set message for admin in another uid.
1900 {
1901 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001902 assertExpectException(SecurityException.class,
1903 /* messageRegex= */ "is not owned by uid",
1904 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00001905 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1906 }
1907
1908 // Set/Get short returns what it sets and other admins text isn't changed.
1909 {
1910 final String supportText = "Some text to test with.";
1911 dpm.setShortSupportMessage(admin1, supportText);
1912 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1913 assertNull(dpm.getLongSupportMessage(admin1));
1914 assertNull(dpm.getShortSupportMessage(admin2));
1915
1916 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1917 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1918 DpmMockContext.CALLER_USER_HANDLE));
1919 assertNull(dpm.getShortSupportMessageForUser(admin2,
1920 DpmMockContext.CALLER_USER_HANDLE));
1921 assertNull(dpm.getLongSupportMessageForUser(admin1,
1922 DpmMockContext.CALLER_USER_HANDLE));
1923 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1924
1925 dpm.setShortSupportMessage(admin1, null);
1926 assertNull(dpm.getShortSupportMessage(admin1));
1927 }
1928
1929 // Set/Get long returns what it sets and other admins text isn't changed.
1930 {
1931 final String supportText = "Some text to test with.\nWith more text.";
1932 dpm.setLongSupportMessage(admin1, supportText);
1933 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1934 assertNull(dpm.getShortSupportMessage(admin1));
1935 assertNull(dpm.getLongSupportMessage(admin2));
1936
1937 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1938 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1939 DpmMockContext.CALLER_USER_HANDLE));
1940 assertNull(dpm.getLongSupportMessageForUser(admin2,
1941 DpmMockContext.CALLER_USER_HANDLE));
1942 assertNull(dpm.getShortSupportMessageForUser(admin1,
1943 DpmMockContext.CALLER_USER_HANDLE));
1944 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1945
1946 dpm.setLongSupportMessage(admin1, null);
1947 assertNull(dpm.getLongSupportMessage(admin1));
1948 }
1949 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001950
phweiss73145f42017-01-17 19:06:38 +01001951 public void testCreateAdminSupportIntent() throws Exception {
1952 // Setup device owner.
1953 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1954 setupDeviceOwner();
1955
1956 // Nonexisting permission returns null
1957 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
1958 assertNull(intent);
1959
1960 // Existing permission that is not set returns null
1961 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1962 assertNull(intent);
1963
1964 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01001965 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01001966 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1967 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1968 .thenReturn(true);
1969 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1970 assertNull(intent);
1971
1972 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01001973 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01001974 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1975 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1976 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
1977 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1978 assertNotNull(intent);
1979 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
1980 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
1981 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001982 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01001983 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
1984 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1985
1986 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
1987 // user restrictions
1988
1989 // Camera is not disabled
1990 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1991 assertNull(intent);
1992
1993 // Camera is disabled
1994 dpm.setCameraDisabled(admin1, true);
1995 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1996 assertNotNull(intent);
1997 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
1998 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1999
2000 // Screen capture is not disabled
2001 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2002 assertNull(intent);
2003
2004 // Screen capture is disabled
2005 dpm.setScreenCaptureDisabled(admin1, true);
2006 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2007 assertNotNull(intent);
2008 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2009 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2010
2011 // Same checks for different user
2012 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2013 // Camera should be disabled by device owner
2014 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2015 assertNotNull(intent);
2016 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2017 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2018 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2019 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2020 // ScreenCapture should not be disabled by device owner
2021 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2022 assertNull(intent);
2023 }
2024
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002025 /**
2026 * Test for:
2027 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002028 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002029 * {@link DevicePolicyManager#isAffiliatedUser}
2030 */
2031 public void testUserAffiliation() throws Exception {
2032 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2033 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2034 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2035
2036 // Check that the system user is unaffiliated.
2037 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2038 assertFalse(dpm.isAffiliatedUser());
2039
2040 // Set a device owner on the system user. Check that the system user becomes affiliated.
2041 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2042 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2043 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2044 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002045 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002046
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002047 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002048 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2049 setAsProfileOwner(admin2);
2050 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002051 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002052
2053 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2054 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002055 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002056 userAffiliationIds.add("red");
2057 userAffiliationIds.add("green");
2058 userAffiliationIds.add("blue");
2059 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002060 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002061 assertFalse(dpm.isAffiliatedUser());
2062
2063 // Have the device owner specify a set of affiliation ids that do not intersect with those
2064 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002065 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002066 deviceAffiliationIds.add("cyan");
2067 deviceAffiliationIds.add("yellow");
2068 deviceAffiliationIds.add("magenta");
2069 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2070 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002071 MoreAsserts.assertContentsInAnyOrder(
2072 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002073 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2074 assertFalse(dpm.isAffiliatedUser());
2075
2076 // Have the profile owner specify a set of affiliation ids that intersect with those
2077 // specified by the device owner. Check that the test user becomes affiliated.
2078 userAffiliationIds.add("yellow");
2079 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002080 MoreAsserts.assertContentsInAnyOrder(
2081 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002082 assertTrue(dpm.isAffiliatedUser());
2083
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002084 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002085 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002086 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002087 assertFalse(dpm.isAffiliatedUser());
2088
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002089 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2090 dpm.setAffiliationIds(admin2, userAffiliationIds);
2091 assertTrue(dpm.isAffiliatedUser());
2092 dpm.clearProfileOwner(admin2);
2093 assertFalse(dpm.isAffiliatedUser());
2094
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002095 // Check that the system user remains affiliated.
2096 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2097 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002098
2099 // Clear the device owner - the user becomes unaffiliated.
2100 clearDeviceOwner();
2101 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002102 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002103
2104 public void testGetUserProvisioningState_defaultResult() {
2105 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2106 }
2107
2108 public void testSetUserProvisioningState_permission() throws Exception {
2109 setupProfileOwner();
2110 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2111
2112 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2113 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2114 }
2115
2116 public void testSetUserProvisioningState_unprivileged() throws Exception {
2117 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002118 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2119 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2120 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002121 }
2122
2123 public void testSetUserProvisioningState_noManagement() {
2124 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002125 assertExpectException(IllegalStateException.class,
2126 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2127 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2128 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002129 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2130 }
2131
2132 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2133 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2134 setupDeviceOwner();
2135 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2136
2137 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2138 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2139 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2140 }
2141
2142 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2143 throws Exception {
2144 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2145 setupDeviceOwner();
2146 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2147
2148 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2149 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2150 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2151 }
2152
2153 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2154 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2155 setupDeviceOwner();
2156 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2157
2158 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2159 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2160 }
2161
2162 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2163 throws Exception {
2164 setupProfileOwner();
2165 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2166
2167 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2168 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2169 DevicePolicyManager.STATE_USER_UNMANAGED);
2170 }
2171
2172 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2173 throws Exception {
2174 setupProfileOwner();
2175 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2176
2177 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2178 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2179 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2180 }
2181
2182 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2183 setupProfileOwner();
2184 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2185
2186 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2187 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2188 }
2189
2190 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2191 setupProfileOwner();
2192 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2193
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002194 assertExpectException(IllegalStateException.class,
2195 /* messageRegex= */ "Cannot move to user provisioning state",
2196 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2197 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2198 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002199 }
2200
2201 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2202 throws Exception {
2203 setupProfileOwner();
2204 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2205
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002206 assertExpectException(IllegalStateException.class,
2207 /* messageRegex= */ "Cannot move to user provisioning state",
2208 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2209 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2210 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002211 }
2212
2213 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2214 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2215 for (int state : states) {
2216 dpm.setUserProvisioningState(state, userId);
2217 assertEquals(state, dpm.getUserProvisioningState());
2218 }
2219 }
2220
2221 private void setupProfileOwner() throws Exception {
2222 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2223
2224 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2225 dpm.setActiveAdmin(admin1, false);
2226 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2227
2228 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2229 }
2230
2231 private void setupDeviceOwner() throws Exception {
2232 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2233
2234 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2235 dpm.setActiveAdmin(admin1, false);
2236 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2237
2238 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2239 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002240
2241 public void testSetMaximumTimeToLock() {
2242 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2243
2244 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2245 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2246
Pavel Grafov75c0a892017-05-18 17:28:27 +01002247 reset(getServices().powerManagerInternal);
2248 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002249
2250 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002251 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2252 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002253 reset(getServices().powerManagerInternal);
2254 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002255
2256 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002257 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2258 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002259 reset(getServices().powerManagerInternal);
2260 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002261
2262 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002263 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2264 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002265 reset(getServices().powerManagerInternal);
2266 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002267
2268 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002269 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2270 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002271 reset(getServices().powerManagerInternal);
2272 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002273
2274 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002275 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2276 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002277 reset(getServices().powerManagerInternal);
2278 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002279
2280 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002281 reset(getServices().powerManagerInternal);
2282 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002283
Pavel Grafov28939982017-10-03 15:11:52 +01002284 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2285 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2286 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002287 reset(getServices().powerManagerInternal);
2288 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002289
2290 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002291 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2292 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002293 reset(getServices().powerManagerInternal);
2294 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002295
Pavel Grafov28939982017-10-03 15:11:52 +01002296 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002297 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002298 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2299 verifyStayOnWhilePluggedCleared(false);
2300 }
2301
2302 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2303 // uses separate challenge.
2304 public void testSetMaximumTimeToLockProfile() throws Exception {
2305 final int PROFILE_USER = 15;
2306 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2307 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2308 mContext.binder.callingUid = PROFILE_ADMIN;
2309 final DevicePolicyManagerInternal dpmi =
2310 LocalServices.getService(DevicePolicyManagerInternal.class);
2311
2312 dpm.setMaximumTimeToLock(admin1, 0);
2313
2314 reset(getServices().powerManagerInternal);
2315 reset(getServices().settings);
2316
2317 // First add timeout for the profile.
2318 dpm.setMaximumTimeToLock(admin1, 10);
2319 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2320
2321 reset(getServices().powerManagerInternal);
2322 reset(getServices().settings);
2323
2324 // Add separate challenge
2325 when(getServices().lockPatternUtils
2326 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2327 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2328
2329 verifyScreenTimeoutCall(10L, PROFILE_USER);
2330 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2331
2332 reset(getServices().powerManagerInternal);
2333 reset(getServices().settings);
2334
2335 // Remove the timeout.
2336 dpm.setMaximumTimeToLock(admin1, 0);
2337 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2338 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2339
2340 reset(getServices().powerManagerInternal);
2341 reset(getServices().settings);
2342
2343 // Add it back.
2344 dpm.setMaximumTimeToLock(admin1, 10);
2345 verifyScreenTimeoutCall(10L, PROFILE_USER);
2346 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2347
2348 reset(getServices().powerManagerInternal);
2349 reset(getServices().settings);
2350
2351 // Remove separate challenge.
2352 reset(getServices().lockPatternUtils);
2353 when(getServices().lockPatternUtils
2354 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2355 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2356
2357 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2358 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2359
2360 reset(getServices().powerManagerInternal);
2361 reset(getServices().settings);
2362
2363 // Remove the timeout.
2364 dpm.setMaximumTimeToLock(admin1, 0);
2365 verifyScreenTimeoutCall(null, PROFILE_USER);
2366 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002367 }
2368
Michal Karpinski943aabd2016-10-06 11:09:25 +01002369 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2370 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2371 setupDeviceOwner();
2372 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2373
Michal Karpinskid084ca52017-01-18 15:54:18 +00002374 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2375 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2376 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2377 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2378 - ONE_MINUTE;
2379
2380 // verify that the minimum timeout cannot be modified on user builds (system property is
2381 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002382 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002383
2384 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2385 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2386 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2387
Pavel Grafov75c0a892017-05-18 17:28:27 +01002388 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002389
2390 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002391 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002392
Michal Karpinskid084ca52017-01-18 15:54:18 +00002393 // reset to default (0 means the admin is not participating, so default should be returned)
2394 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002395
2396 // aggregation should be the default if unset by any admin
2397 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2398 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2399
2400 // admin not participating by default
2401 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2402
2403 //clamping from the top
2404 dpm.setRequiredStrongAuthTimeout(admin1,
2405 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2406 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2407 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2408 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2409 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2410
Michal Karpinskid084ca52017-01-18 15:54:18 +00002411 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002412 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2413 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2414 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2415 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2416
2417 // clamping from the bottom
2418 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2419 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2420 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2421
Michal Karpinskid084ca52017-01-18 15:54:18 +00002422 // values within range
2423 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2424 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2425 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2426
2427 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2428 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2429 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002430
2431 // reset to default
2432 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2433 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2434 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2435 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2436
2437 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002438 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2439 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002440 }
2441
Pavel Grafov28939982017-10-03 15:11:52 +01002442 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002443 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002444 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002445 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002446 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002447 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002448 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002449 }
Pavel Grafov28939982017-10-03 15:11:52 +01002450 }
2451
2452 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002453 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2454 // UnfinishedVerificationException.
2455 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002456
Esteban Talavera01576862016-12-15 11:16:44 +00002457 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002458 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002459 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002460 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002461 .thenReturn(false);
2462 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002463 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2464 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002465 .thenReturn(true);
2466 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2467
2468 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002469 }
Victor Chang3e794af2016-03-04 13:48:17 +00002470
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002471 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2472 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002473 mContext.packageName = admin1.getPackageName();
2474 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002475 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2476 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2477 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2478 false);
2479 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2480 }
2481
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002482 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2483 setup_DeviceAdminFeatureOff();
2484 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2485 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2486 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2487 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2488 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2489 assertCheckProvisioningPreCondition(
2490 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2491 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2492 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2493 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2494 }
2495
Esteban Talavera01576862016-12-15 11:16:44 +00002496 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002497 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002498 .thenReturn(false);
2499 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002500 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2501 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002502 .thenReturn(true);
2503 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2504
2505 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002506 }
Victor Chang3e794af2016-03-04 13:48:17 +00002507
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002508 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2509 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002510 mContext.packageName = admin1.getPackageName();
2511 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002512 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2513 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2514 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2515 false);
2516 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2517
2518 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002519 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002520 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2521 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2522 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2523 true);
2524 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2525 }
2526
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002527 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2528 setup_ManagedProfileFeatureOff();
2529 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2530 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2531 DevicePolicyManager.CODE_OK);
2532 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2533 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2534 assertCheckProvisioningPreCondition(
2535 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2536 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2537 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2538 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2539
2540 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002541 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002542 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2543 DevicePolicyManager.CODE_OK);
2544 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2545 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2546 assertCheckProvisioningPreCondition(
2547 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2548 DevicePolicyManager.CODE_OK);
2549 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2550 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2551 }
2552
Esteban Talavera01576862016-12-15 11:16:44 +00002553 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002554 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002555 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002556 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2557 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002558 .thenReturn(true);
2559 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2560
2561 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002562 }
Victor Chang3e794af2016-03-04 13:48:17 +00002563
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002564 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2565 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002566 mContext.packageName = admin1.getPackageName();
2567 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002568 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2569 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2570 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2571 false /* because of non-split user */);
2572 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2573 false /* because of non-split user */);
2574 }
2575
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002576 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002577 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002578 setup_nonSplitUser_firstBoot_primaryUser();
2579 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2580 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2581 DevicePolicyManager.CODE_OK);
2582 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2583 DevicePolicyManager.CODE_OK);
2584 assertCheckProvisioningPreCondition(
2585 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2586 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2587 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2588 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2589 }
2590
Esteban Talavera01576862016-12-15 11:16:44 +00002591 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002592 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002593 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002594 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2595 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002596 .thenReturn(true);
2597 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2598
2599 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002600 }
Victor Chang3e794af2016-03-04 13:48:17 +00002601
Nicolas Prevot45d29072017-01-18 16:11:19 +00002602 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2603 setDeviceOwner();
2604 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2605 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2606 }
2607
2608 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2609 setup_nonSplitUser_withDo_primaryUser();
2610 final int MANAGED_PROFILE_USER_ID = 18;
2611 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2612 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002613 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002614 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002615 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002616 true)).thenReturn(true);
2617 }
2618
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002619 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2620 throws Exception {
2621 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002622 mContext.packageName = admin1.getPackageName();
2623 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002624 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2625 false/* because of completed device setup */);
2626 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2627 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2628 false/* because of non-split user */);
2629 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2630 false/* because of non-split user */);
2631 }
2632
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002633 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2634 throws Exception {
2635 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2636 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2637 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2638 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2639 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2640 DevicePolicyManager.CODE_OK);
2641 assertCheckProvisioningPreCondition(
2642 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2643 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2644 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2645 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2646 }
2647
Nicolas Prevot45d29072017-01-18 16:11:19 +00002648 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2649 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002650 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002651 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2652
2653 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2654 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002655 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002656
2657 // COMP mode is allowed.
2658 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2659 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002660 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002661
Nicolas Prevot45d29072017-01-18 16:11:19 +00002662 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002663 assertCheckProvisioningPreCondition(
2664 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002665 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002666 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002667 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2668 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2669 }
Esteban Talavera01576862016-12-15 11:16:44 +00002670
Nicolas Prevot45d29072017-01-18 16:11:19 +00002671 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2672 setup_nonSplitUser_withDo_primaryUser();
2673 mContext.packageName = admin1.getPackageName();
2674 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2675 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2676 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002677 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002678 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2679 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2680 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002681 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002682 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2683 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2684 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2685 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2686 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002687 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002688 assertCheckProvisioningPreCondition(
2689 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002690 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002691 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002692 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2693 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2694 }
Esteban Talavera01576862016-12-15 11:16:44 +00002695
Nicolas Prevot45d29072017-01-18 16:11:19 +00002696 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2697 throws Exception {
2698 setup_nonSplitUser_withDo_primaryUser();
2699 mContext.packageName = admin1.getPackageName();
2700 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002701 // The DO should not be allowed to initiate provisioning if the restriction is set by
2702 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002703 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002704 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2705 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2706 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002707 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002708 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2709 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2710 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2711 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2712 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002713 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2714
2715 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002716 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002717 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002718 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002719 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2720 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2721 }
2722
2723 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2724 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2725 mContext.packageName = admin1.getPackageName();
2726 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2727
2728 // We can delete the managed profile to create a new one, so provisioning is allowed.
2729 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2730 DevicePolicyManager.CODE_OK);
2731 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2732 assertCheckProvisioningPreCondition(
2733 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2734 DpmMockContext.ANOTHER_PACKAGE_NAME,
2735 DevicePolicyManager.CODE_OK);
2736 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2737 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2738 }
2739
2740 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2741 throws Exception {
2742 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2743 mContext.packageName = admin1.getPackageName();
2744 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002745 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002746 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2747 eq(UserHandle.SYSTEM)))
2748 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002749 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002750 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2751 eq(UserHandle.SYSTEM)))
2752 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002753
2754 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002755 assertCheckProvisioningPreCondition(
2756 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2757 DpmMockContext.ANOTHER_PACKAGE_NAME,
2758 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2759 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2760 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002761
2762 // But the device owner can still do it because it has set the restriction itself.
2763 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2764 DevicePolicyManager.CODE_OK);
2765 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002766 }
2767
2768 private void setup_splitUser_firstBoot_systemUser() 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(true);
2772 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002773 .thenReturn(false);
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_splitUser_firstBoot_systemUser() throws Exception {
2780 setup_splitUser_firstBoot_systemUser();
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,
2785 false /* because canAddMoreManagedProfiles returns false */);
2786 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2787 true);
2788 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2789 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002790 }
2791
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002792 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2793 throws Exception {
2794 setup_splitUser_firstBoot_systemUser();
2795 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2796 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2797 DevicePolicyManager.CODE_OK);
2798 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002799 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002800 assertCheckProvisioningPreCondition(
2801 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2802 DevicePolicyManager.CODE_OK);
2803 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2804 DevicePolicyManager.CODE_SYSTEM_USER);
2805 }
2806
Esteban Talavera01576862016-12-15 11:16:44 +00002807 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002808 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002809 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002810 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2811 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002812 .thenReturn(false);
2813 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2814
2815 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002816 }
Victor Chang3e794af2016-03-04 13:48:17 +00002817
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002818 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2819 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002820 mContext.packageName = admin1.getPackageName();
2821 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002822 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2823 true/* it's undefined behavior. Can be changed into false in the future */);
2824 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2825 false /* because canAddMoreManagedProfiles returns false */);
2826 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2827 true/* it's undefined behavior. Can be changed into false in the future */);
2828 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2829 false/* because calling uid is system user */);
2830 }
2831
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002832 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2833 throws Exception {
2834 setup_splitUser_afterDeviceSetup_systemUser();
2835 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2836 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2837 DevicePolicyManager.CODE_OK);
2838 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002839 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002840 assertCheckProvisioningPreCondition(
2841 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2842 DevicePolicyManager.CODE_OK);
2843 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2844 DevicePolicyManager.CODE_SYSTEM_USER);
2845 }
2846
Esteban Talavera01576862016-12-15 11:16:44 +00002847 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002848 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002849 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002850 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2851 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002852 true)).thenReturn(true);
2853 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2854
2855 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002856 }
Victor Chang3e794af2016-03-04 13:48:17 +00002857
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002858 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2859 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002860 mContext.packageName = admin1.getPackageName();
2861 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002862 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2863 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2864 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2865 true);
2866 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002867 }
2868
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002869 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002870 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002871 setup_splitUser_firstBoot_primaryUser();
2872 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2873 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2874 DevicePolicyManager.CODE_OK);
2875 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2876 DevicePolicyManager.CODE_OK);
2877 assertCheckProvisioningPreCondition(
2878 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2879 DevicePolicyManager.CODE_OK);
2880 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2881 DevicePolicyManager.CODE_OK);
2882 }
2883
Esteban Talavera01576862016-12-15 11:16:44 +00002884 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002885 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002886 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002887 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2888 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002889 true)).thenReturn(true);
2890 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2891
2892 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002893 }
Victor Chang3e794af2016-03-04 13:48:17 +00002894
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002895 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2896 throws Exception {
2897 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002898 mContext.packageName = admin1.getPackageName();
2899 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002900 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2901 true/* it's undefined behavior. Can be changed into false in the future */);
2902 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2903 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2904 true/* it's undefined behavior. Can be changed into false in the future */);
2905 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2906 false/* because user setup completed */);
2907 }
2908
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002909 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002910 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002911 setup_splitUser_afterDeviceSetup_primaryUser();
2912 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2913 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2914 DevicePolicyManager.CODE_OK);
2915 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2916 DevicePolicyManager.CODE_OK);
2917 assertCheckProvisioningPreCondition(
2918 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2919 DevicePolicyManager.CODE_OK);
2920 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2921 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2922 }
2923
Esteban Talavera01576862016-12-15 11:16:44 +00002924 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002925 setDeviceOwner();
2926
Pavel Grafov75c0a892017-05-18 17:28:27 +01002927 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002928 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002929 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2930 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002931 .thenReturn(false);
2932 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2933
2934 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002935 }
Victor Chang3e794af2016-03-04 13:48:17 +00002936
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002937 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2938 throws Exception {
2939 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002940 mContext.packageName = admin1.getPackageName();
2941 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002942 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2943 false /* can't provision managed profile on system user */);
2944 }
2945
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002946 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002947 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002948 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2949 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2950 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2951 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2952 }
2953
2954 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002955 setDeviceOwner();
2956
Pavel Grafov75c0a892017-05-18 17:28:27 +01002957 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002958 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002959 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2960 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002961 true)).thenReturn(true);
2962 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2963
2964 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002965 }
Victor Chang3e794af2016-03-04 13:48:17 +00002966
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002967 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2968 throws Exception {
2969 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002970 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2971 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002972 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2973 }
2974
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002975 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002976 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002977 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2978 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002979
2980 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002981 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2982 DevicePolicyManager.CODE_OK);
2983 }
2984
2985 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002986 setDeviceOwner();
2987
Pavel Grafov75c0a892017-05-18 17:28:27 +01002988 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002989 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002990 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2991 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002992 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2993 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002994 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002995 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002996 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002997 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00002998 true)).thenReturn(true);
2999 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3000
3001 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003002 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003003
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003004 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3005 throws Exception {
3006 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003007 mContext.packageName = admin1.getPackageName();
3008 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003009 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3010 }
3011
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003012 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3013 throws Exception {
3014 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3015 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3016 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3017 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3018 }
3019
3020 public void testCheckProvisioningPreCondition_permission() {
3021 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003022 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3023 () -> dpm.checkProvisioningPreCondition(
3024 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003025 }
3026
Victor Chang3577ed22016-08-25 18:49:26 +01003027 public void testForceUpdateUserSetupComplete_permission() {
3028 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003029 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3030 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003031 }
3032
3033 public void testForceUpdateUserSetupComplete_systemUser() {
3034 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3035 // GIVEN calling from user 20
3036 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003037 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3038 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003039 }
3040
3041 public void testForceUpdateUserSetupComplete_userbuild() {
3042 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3043 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3044
3045 final int userId = UserHandle.USER_SYSTEM;
3046 // GIVEN userComplete is false in SettingsProvider
3047 setUserSetupCompleteForUser(false, userId);
3048
3049 // GIVEN userComplete is true in DPM
3050 DevicePolicyManagerService.DevicePolicyData userData =
3051 new DevicePolicyManagerService.DevicePolicyData(userId);
3052 userData.mUserSetupComplete = true;
3053 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3054
3055 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003056 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003057
3058 assertTrue(dpms.hasUserSetupCompleted());
3059
3060 dpm.forceUpdateUserSetupComplete();
3061
3062 // THEN the state in dpms is not changed
3063 assertTrue(dpms.hasUserSetupCompleted());
3064 }
3065
3066 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3067 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3068 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3069
3070 final int userId = UserHandle.USER_SYSTEM;
3071 // GIVEN userComplete is false in SettingsProvider
3072 setUserSetupCompleteForUser(false, userId);
3073
3074 // GIVEN userComplete is true in DPM
3075 DevicePolicyManagerService.DevicePolicyData userData =
3076 new DevicePolicyManagerService.DevicePolicyData(userId);
3077 userData.mUserSetupComplete = true;
3078 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3079
3080 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003081 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003082
3083 assertTrue(dpms.hasUserSetupCompleted());
3084
3085 dpm.forceUpdateUserSetupComplete();
3086
3087 // THEN the state in dpms is not changed
3088 assertFalse(dpms.hasUserSetupCompleted());
3089 }
3090
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003091 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003092 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003093 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003094
3095 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3096 runAsCaller(mAdmin1Context, dpms, dpm -> {
3097 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3098 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003099 }
3100
3101 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3102 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3103 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003104
3105 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3106 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003107 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003108 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3109 .thenReturn(true);
3110
3111 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003112 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003113
3114 // Enabling logging should not change the timestamp.
3115 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003116 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003117 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003118 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003119 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003120 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003121
3122 // Retrieving the logs should update the timestamp.
3123 final long beforeRetrieval = System.currentTimeMillis();
3124 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003125 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003126 final long afterRetrieval = System.currentTimeMillis();
3127 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3128 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3129
3130 // Retrieving the pre-boot logs should update the timestamp.
3131 Thread.sleep(2);
3132 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003133 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003134 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3135
3136 // Checking the timestamp again should not change it.
3137 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003138 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003139
3140 // Retrieving the logs again should update the timestamp.
3141 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003142 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003143 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3144
3145 // Disabling logging should not change the timestamp.
3146 Thread.sleep(2);
3147 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003148 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003149
3150 // Restarting the DPMS should not lose the timestamp.
3151 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003152 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003153
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003154 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3155 mContext.binder.callingUid = 1234567;
3156 mContext.callerPermissions.add(permission.MANAGE_USERS);
3157 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3158 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3159
3160 // System can retrieve the timestamp.
3161 mContext.binder.clearCallingIdentity();
3162 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3163
3164 // Removing the device owner should clear the timestamp.
3165 clearDeviceOwner();
3166 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003167 }
3168
yuemingw0de748d2017-11-15 19:22:27 +00003169 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3170 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3171 setupDeviceOwner();
3172 assertExpectException(SecurityException.class, null, () ->
3173 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3174 }
3175
3176 public void testSetSystemSettingFailWithPO() throws Exception {
3177 setupProfileOwner();
3178 assertExpectException(SecurityException.class, null, () ->
3179 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"));
3180 }
3181
3182 public void testSetSystemSetting() throws Exception {
3183 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3184 setupDeviceOwner();
3185 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3186 verify(getServices().settings).settingsSystemPutString(
3187 Settings.System.SCREEN_BRIGHTNESS, "0");
3188 }
3189
yuemingwe43cdf72017-10-12 16:52:11 +01003190 public void testSetTime() throws Exception {
3191 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3192 setupDeviceOwner();
3193 dpm.setTime(admin1, 0);
3194 verify(getServices().alarmManager).setTime(0);
3195 }
3196
3197 public void testSetTimeFailWithPO() throws Exception {
3198 setupProfileOwner();
3199 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3200 }
3201
3202 public void testSetTimeWithAutoTimeOn() throws Exception {
3203 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3204 setupDeviceOwner();
3205 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3206 .thenReturn(1);
3207 assertFalse(dpm.setTime(admin1, 0));
3208 }
3209
3210 public void testSetTimeZone() throws Exception {
3211 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3212 setupDeviceOwner();
3213 dpm.setTimeZone(admin1, "Asia/Shanghai");
3214 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3215 }
3216
3217 public void testSetTimeZoneFailWithPO() throws Exception {
3218 setupProfileOwner();
3219 assertExpectException(SecurityException.class, null,
3220 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3221 }
3222
3223 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3224 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3225 setupDeviceOwner();
3226 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3227 .thenReturn(1);
3228 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3229 }
3230
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003231 public void testGetLastBugReportRequestTime() throws Exception {
3232 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3233 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003234
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003235 mContext.packageName = admin1.getPackageName();
3236 mContext.applicationInfo = new ApplicationInfo();
3237 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3238 .thenReturn(Color.WHITE);
3239 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3240 anyObject())).thenReturn(Color.WHITE);
3241
Esteban Talaverad36dd152016-12-15 08:51:45 +00003242 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3243 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003244 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003245
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003246 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003247 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003248
3249 // Requesting a bug report should update the timestamp.
3250 final long beforeRequest = System.currentTimeMillis();
3251 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003252 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003253 final long afterRequest = System.currentTimeMillis();
3254 assertTrue(bugReportRequestTime >= beforeRequest);
3255 assertTrue(bugReportRequestTime <= afterRequest);
3256
3257 // Checking the timestamp again should not change it.
3258 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003259 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003260
3261 // Restarting the DPMS should not lose the timestamp.
3262 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003263 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003264
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003265 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3266 mContext.binder.callingUid = 1234567;
3267 mContext.callerPermissions.add(permission.MANAGE_USERS);
3268 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3269 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3270
3271 // System can retrieve the timestamp.
3272 mContext.binder.clearCallingIdentity();
3273 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3274
3275 // Removing the device owner should clear the timestamp.
3276 clearDeviceOwner();
3277 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003278 }
3279
3280 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3281 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3282 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003283 mContext.packageName = admin1.getPackageName();
3284 mContext.applicationInfo = new ApplicationInfo();
3285 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3286 .thenReturn(Color.WHITE);
3287 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3288 anyObject())).thenReturn(Color.WHITE);
3289
3290 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3291 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003292 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003293 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003294 .thenReturn(true);
3295
3296 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003297 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003298
3299 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3300 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003301 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003302
3303 // Enabling logging should not change the timestamp.
3304 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003305 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003306
3307 // Retrieving the logs should update the timestamp.
3308 final long beforeRetrieval = System.currentTimeMillis();
3309 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003310 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003311 final long afterRetrieval = System.currentTimeMillis();
3312 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3313 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3314
3315 // Checking the timestamp again should not change it.
3316 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003317 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003318
3319 // Retrieving the logs again should update the timestamp.
3320 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003321 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003322 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3323
3324 // Disabling logging should not change the timestamp.
3325 Thread.sleep(2);
3326 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003327 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003328
3329 // Restarting the DPMS should not lose the timestamp.
3330 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003331 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3332
3333 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3334 mContext.binder.callingUid = 1234567;
3335 mContext.callerPermissions.add(permission.MANAGE_USERS);
3336 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3337 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3338
3339 // System can retrieve the timestamp.
3340 mContext.binder.clearCallingIdentity();
3341 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3342
3343 // Removing the device owner should clear the timestamp.
3344 clearDeviceOwner();
3345 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003346 }
3347
Tony Mak2f26b792016-11-28 17:54:51 +00003348 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3349 // Setup device owner.
3350 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3351 setupDeviceOwner();
3352
3353 // Only device owner is setup, the result list should be empty.
3354 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3355 MoreAsserts.assertEmpty(targetUsers);
3356
3357 // Setup a managed profile managed by the same admin.
3358 final int MANAGED_PROFILE_USER_ID = 15;
3359 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3360 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3361
3362 // Add a secondary user, it should never talk with.
3363 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003364 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003365
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003366 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3367 // other.
3368 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3369 MoreAsserts.assertEmpty(targetUsers);
3370
3371 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3372 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3373 MoreAsserts.assertEmpty(targetUsers);
3374
3375 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003376 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003377 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3378 dpm.setAffiliationIds(admin1, userAffiliationIds);
3379
3380 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3381 dpm.setAffiliationIds(admin1, userAffiliationIds);
3382
Tony Mak2f26b792016-11-28 17:54:51 +00003383 // Calling from device owner admin, the result list should just contain the managed
3384 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003385 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003386 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3387 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3388
3389 // Calling from managed profile admin, the result list should just contain the system
3390 // user id.
3391 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3392 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3393 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003394
3395 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003396 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003397
3398 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3399 // to each other.
3400 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3401 MoreAsserts.assertEmpty(targetUsers);
3402
3403 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3404 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3405 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003406 }
3407
3408 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3409 // Setup a device owner.
3410 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3411 setupDeviceOwner();
3412
3413 // Set up a managed profile managed by different package.
3414 final int MANAGED_PROFILE_USER_ID = 15;
3415 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3416 final ComponentName adminDifferentPackage =
3417 new ComponentName("another.package", "whatever.class");
3418 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3419
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003420 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003421 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003422 dpm.setAffiliationIds(admin1, userAffiliationIds);
3423
3424 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3425 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3426
Tony Mak2f26b792016-11-28 17:54:51 +00003427 // Calling from device owner admin, we should get zero bind device admin target users as
3428 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003429 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003430 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3431 MoreAsserts.assertEmpty(targetUsers);
3432
3433 // Calling from managed profile admin, we should still get zero target users for the same
3434 // reason.
3435 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3436 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3437 MoreAsserts.assertEmpty(targetUsers);
3438 }
3439
Charles Hee078db72017-10-19 18:03:20 +01003440 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003441 // Setup a device owner.
3442 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3443 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003444 // Lock task policy is updated when loading user data.
3445 verify(getServices().iactivityManager).updateLockTaskPackages(
3446 UserHandle.USER_SYSTEM, new String[0]);
3447 verify(getServices().iactivityManager).updateLockTaskFeatures(
3448 UserHandle.USER_SYSTEM, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003449
3450 // Set up a managed profile managed by different package (package name shouldn't matter)
3451 final int MANAGED_PROFILE_USER_ID = 15;
3452 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3453 final ComponentName adminDifferentPackage =
3454 new ComponentName("another.package", "whatever.class");
3455 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Charles Hee078db72017-10-19 18:03:20 +01003456 verify(getServices().iactivityManager).updateLockTaskPackages(
3457 MANAGED_PROFILE_USER_ID, new String[0]);
3458 verify(getServices().iactivityManager).updateLockTaskFeatures(
3459 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003460
3461 // The DO can still set lock task packages
3462 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3463 final String[] doPackages = {"doPackage1", "doPackage2"};
3464 dpm.setLockTaskPackages(admin1, doPackages);
3465 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3466 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3467 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Charles Hee078db72017-10-19 18:03:20 +01003468 verify(getServices().iactivityManager).updateLockTaskPackages(
3469 UserHandle.USER_SYSTEM, doPackages);
3470 // And the DO can still set lock task features
3471 final int doFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3472 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3473 dpm.setLockTaskFeatures(admin1, doFlags);
3474 verify(getServices().iactivityManager).updateLockTaskFeatures(
3475 UserHandle.USER_SYSTEM, doFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003476
3477 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3478 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3479 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003480 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3481 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3482 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3483 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003484 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
Charles Hee078db72017-10-19 18:03:20 +01003485 // And it shouldn't be able to setLockTaskFeatures.
3486 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3487 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3488 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3489 () -> dpm.setLockTaskFeatures(adminDifferentPackage, poFlags));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003490
3491 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003492 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003493 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3494 dpm.setAffiliationIds(admin1, userAffiliationIds);
3495
3496 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3497 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3498
3499 // Now the managed profile can set lock task packages.
3500 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3501 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3502 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3503 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003504 verify(getServices().iactivityManager).updateLockTaskPackages(
3505 MANAGED_PROFILE_USER_ID, poPackages);
3506 // And it can set lock task features.
3507 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
3508 verify(getServices().iactivityManager).updateLockTaskFeatures(
3509 MANAGED_PROFILE_USER_ID, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003510
3511 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003512 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003513 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3514 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003515 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3516 MANAGED_PROFILE_USER_ID, new String[0]);
3517 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3518 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003519
3520 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3521 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3522 }
3523
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003524 public void testIsDeviceManaged() throws Exception {
3525 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3526 setupDeviceOwner();
3527
3528 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3529 // find out that the device has a device owner.
3530 assertTrue(dpm.isDeviceManaged());
3531 mContext.binder.callingUid = 1234567;
3532 mContext.callerPermissions.add(permission.MANAGE_USERS);
3533 assertTrue(dpm.isDeviceManaged());
3534 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3535 mContext.binder.clearCallingIdentity();
3536 assertTrue(dpm.isDeviceManaged());
3537
3538 clearDeviceOwner();
3539
3540 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3541 // not have a device owner.
3542 mContext.binder.callingUid = 1234567;
3543 mContext.callerPermissions.add(permission.MANAGE_USERS);
3544 assertFalse(dpm.isDeviceManaged());
3545 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3546 mContext.binder.clearCallingIdentity();
3547 assertFalse(dpm.isDeviceManaged());
3548 }
3549
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003550 public void testDeviceOwnerOrganizationName() throws Exception {
3551 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3552 setupDeviceOwner();
3553
3554 dpm.setOrganizationName(admin1, "organization");
3555
3556 // Device owner can retrieve organization managing the device.
3557 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3558
3559 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3560 mContext.binder.callingUid = 1234567;
3561 mContext.callerPermissions.add(permission.MANAGE_USERS);
3562 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3563 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3564
3565 // System can retrieve organization managing the device.
3566 mContext.binder.clearCallingIdentity();
3567 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3568
3569 // Removing the device owner clears the organization managing the device.
3570 clearDeviceOwner();
3571 assertNull(dpm.getDeviceOwnerOrganizationName());
3572 }
3573
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003574 public void testWipeDataManagedProfile() throws Exception {
3575 final int MANAGED_PROFILE_USER_ID = 15;
3576 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3577 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3578 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3579
3580 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003581 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003582 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003583 // Get mock reason string since we throw an IAE with empty string input.
3584 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3585 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003586
3587 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003588 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003589 MANAGED_PROFILE_USER_ID);
3590 }
3591
3592 public void testWipeDataManagedProfileDisallowed() throws Exception {
3593 final int MANAGED_PROFILE_USER_ID = 15;
3594 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3595 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3596
3597 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003598 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003599 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3600
Pavel Grafov75c0a892017-05-18 17:28:27 +01003601 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003602 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3603 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3604 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003605 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3606 thenReturn("Just a test string.");
3607
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003608 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003609 // The PO is not allowed to remove the profile if the user restriction was set on the
3610 // profile by the system
3611 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3612 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003613 }
3614
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003615 public void testWipeDataDeviceOwner() throws Exception {
3616 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003617 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003618 UserManager.DISALLOW_FACTORY_RESET,
3619 UserHandle.SYSTEM))
3620 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003621 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3622 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003623
3624 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003625 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003626 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3627 /*wipeEuicc=*/ eq(false));
3628 }
3629
3630 public void testWipeEuiccDataEnabled() throws Exception {
3631 setDeviceOwner();
3632 when(getServices().userManager.getUserRestrictionSource(
3633 UserManager.DISALLOW_FACTORY_RESET,
3634 UserHandle.SYSTEM))
3635 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003636 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3637 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003638
3639 dpm.wipeData(WIPE_EUICC);
3640 verify(getServices().recoverySystem).rebootWipeUserData(
3641 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3642 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003643 }
3644
3645 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3646 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003647 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003648 UserManager.DISALLOW_FACTORY_RESET,
3649 UserHandle.SYSTEM))
3650 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003651 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3652 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003653 // The DO is not allowed to wipe the device if the user restriction was set
3654 // by the system
3655 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3656 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003657 }
3658
3659 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3660 final int MANAGED_PROFILE_USER_ID = 15;
3661 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3662 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3663
3664 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003665 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003666 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3667
Pavel Grafov75c0a892017-05-18 17:28:27 +01003668 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003669 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3670 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3671 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3672
3673 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3674 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3675
3676 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3677 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3678 // Failed password attempts on the parent user are taken into account, as there isn't a
3679 // separate work challenge.
3680 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3681 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3682 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3683
3684 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3685 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003686 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003687 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003688 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003689 }
3690
3691 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3692 throws Exception {
3693 final int MANAGED_PROFILE_USER_ID = 15;
3694 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3695 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3696
3697 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003698 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003699 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3700
Pavel Grafov75c0a892017-05-18 17:28:27 +01003701 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003702 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3703 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3704 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3705
3706 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3707 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3708
3709 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3710 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3711 // Failed password attempts on the parent user are taken into account, as there isn't a
3712 // separate work challenge.
3713 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3714 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3715 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3716
3717 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3718 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003719 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003720 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003721 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003722 }
3723
3724 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3725 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003726 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003727 UserManager.DISALLOW_FACTORY_RESET,
3728 UserHandle.SYSTEM))
3729 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3730
3731 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3732
3733 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3734 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3735 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3736 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3737 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3738
3739 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3740 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003741 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003742 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3743 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003744 }
3745
3746 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3747 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003748 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003749 UserManager.DISALLOW_FACTORY_RESET,
3750 UserHandle.SYSTEM))
3751 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3752
3753 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3754
3755 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3756 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3757 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3758 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3759 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3760
3761 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003762 verifyZeroInteractions(getServices().recoverySystem);
3763 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003764 .removeUserEvenWhenDisallowed(anyInt());
3765 }
3766
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003767 public void testGetPermissionGrantState() throws Exception {
3768 final String permission = "some.permission";
3769 final String app1 = "com.example.app1";
3770 final String app2 = "com.example.app2";
3771
Pavel Grafov75c0a892017-05-18 17:28:27 +01003772 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003773 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003774 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003775 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003776 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003777 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3778 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003779 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003780 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003781 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003782 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003783 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003784 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3785
3786 // System can retrieve permission grant state.
3787 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003788 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003789 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3790 dpm.getPermissionGrantState(null, app1, permission));
3791 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3792 dpm.getPermissionGrantState(null, app2, permission));
3793
3794 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003795 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3796 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003797 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3798 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003799
3800 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003801 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3802 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003803 setAsProfileOwner(admin1);
3804 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3805 dpm.getPermissionGrantState(admin1, app1, permission));
3806 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3807 dpm.getPermissionGrantState(admin1, app2, permission));
3808 }
3809
Rubin Xuaab7a412016-12-30 21:13:29 +00003810 public void testResetPasswordWithToken() throws Exception {
3811 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3812 setupDeviceOwner();
3813 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003814 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3815 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3816
Rubin Xuaab7a412016-12-30 21:13:29 +00003817 // test adding a token
3818 final byte[] token = new byte[32];
3819 final long handle = 123456;
3820 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003821 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003822 .thenReturn(handle);
3823 assertTrue(dpm.setResetPasswordToken(admin1, token));
3824
3825 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003826 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003827 .thenReturn(true);
3828 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3829
3830 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003831 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01003832 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
3833 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00003834 eq(UserHandle.USER_SYSTEM)))
3835 .thenReturn(true);
3836 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3837
3838 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003839 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003840 .thenReturn(true);
3841 assertTrue(dpm.clearResetPasswordToken(admin1));
3842 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003843
Alexandru-Andrei Rotaru7f31bb02017-09-07 16:29:48 +01003844 public void testSetPasswordBlacklistCannotBeCalledByNonAdmin() throws Exception {
3845 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3846 () -> dpm.setPasswordBlacklist(admin1, null, null));
3847 verifyZeroInteractions(getServices().passwordBlacklist);
3848 }
3849
3850 public void testClearingPasswordBlacklistDoesNotCreateNewBlacklist() throws Exception {
3851 setupProfileOwner();
3852 dpm.setPasswordBlacklist(admin1, null, null);
3853 verifyZeroInteractions(getServices().passwordBlacklist);
3854 }
3855
3856 public void testSetPasswordBlacklistCreatesNewBlacklist() throws Exception {
3857 final String name = "myblacklist";
3858 final List<String> explicit = Arrays.asList("password", "letmein");
3859 setupProfileOwner();
3860 dpm.setPasswordBlacklist(admin1, name, explicit);
3861 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, explicit);
3862 }
3863
3864 public void testSetPasswordBlacklistOnlyConvertsExplicitToLowerCase() throws Exception {
3865 final List<String> mixedCase = Arrays.asList("password", "LETMEIN", "FooTBAll");
3866 final List<String> lowerCase = Arrays.asList("password", "letmein", "football");
3867 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3868 setupDeviceOwner();
3869 final String name = "Name of the Blacklist";
3870 dpm.setPasswordBlacklist(admin1, name, mixedCase);
3871 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, lowerCase);
3872 }
3873
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003874 public void testIsActivePasswordSufficient() throws Exception {
3875 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3876 mContext.packageName = admin1.getPackageName();
3877 setupDeviceOwner();
3878
3879 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3880 dpm.setPasswordMinimumLength(admin1, 8);
3881 dpm.setPasswordMinimumLetters(admin1, 6);
3882 dpm.setPasswordMinimumLowerCase(admin1, 3);
3883 dpm.setPasswordMinimumUpperCase(admin1, 1);
3884 dpm.setPasswordMinimumNonLetter(admin1, 1);
3885 dpm.setPasswordMinimumNumeric(admin1, 1);
3886 dpm.setPasswordMinimumSymbols(admin1, 0);
3887
3888 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3889 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3890 8, 2,
3891 6, 1,
3892 0, 1);
3893
3894 setActivePasswordState(passwordMetricsNoSymbols);
3895 assertTrue(dpm.isActivePasswordSufficient());
3896
3897 initializeDpms();
3898 reset(mContext.spiedContext);
3899 assertTrue(dpm.isActivePasswordSufficient());
3900
3901 // This call simulates the user entering the password for the first time after a reboot.
3902 // This causes password metrics to be reloaded into memory. Until this happens,
3903 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3904 // even if the DPC changes password requirements so that the password no longer meets the
3905 // requirements. This is a known limitation of the current implementation of
3906 // isActivePasswordSufficient() - see b/34218769.
3907 setActivePasswordState(passwordMetricsNoSymbols);
3908 assertTrue(dpm.isActivePasswordSufficient());
3909
3910 dpm.setPasswordMinimumSymbols(admin1, 1);
3911 // This assertion would fail if we had not called setActivePasswordState() again after
3912 // initializeDpms() - see previous comment.
3913 assertFalse(dpm.isActivePasswordSufficient());
3914
3915 initializeDpms();
3916 reset(mContext.spiedContext);
3917 assertFalse(dpm.isActivePasswordSufficient());
3918
3919 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3920 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3921 7, 2,
3922 5, 1,
3923 1, 2);
3924
3925 setActivePasswordState(passwordMetricsWithSymbols);
3926 assertTrue(dpm.isActivePasswordSufficient());
3927 }
3928
Pavel Grafov75c0a892017-05-18 17:28:27 +01003929 private void setActivePasswordState(PasswordMetrics passwordMetrics)
3930 throws Exception {
3931 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003932 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003933
Pavel Grafov75c0a892017-05-18 17:28:27 +01003934 dpm.setActivePasswordState(passwordMetrics, userHandle);
3935 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003936
Pavel Grafov75c0a892017-05-18 17:28:27 +01003937 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3938 intent.setComponent(admin1);
3939 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3940
3941 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3942 MockUtils.checkIntent(intent),
3943 MockUtils.checkUserHandle(userHandle));
3944
3945 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
3946 // let it finish with system uid, otherwise it will throw and crash.
3947 flushTasks();
3948
3949 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003950 }
3951
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003952 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3953 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3954 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3955 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3956 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3957 DpmMockContext.SYSTEM_UID);
3958 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3959 DpmMockContext.SYSTEM_UID);
3960
3961 // Set up a device owner.
3962 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003963 setupDeviceOwner();
3964
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003965 // First and second user set IMEs manually.
3966 mContext.binder.callingUid = firstUserSystemUid;
3967 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3968 mContext.binder.callingUid = secondUserSystemUid;
3969 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003970
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003971 // Device owner changes IME for first user.
3972 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003973 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003974 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003975 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003976 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003977 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003978 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003979 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3980 mContext.binder.callingUid = firstUserSystemUid;
3981 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3982 mContext.binder.callingUid = secondUserSystemUid;
3983 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003984
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003985 // Second user changes IME manually.
3986 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3987 mContext.binder.callingUid = firstUserSystemUid;
3988 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3989 mContext.binder.callingUid = secondUserSystemUid;
3990 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003991
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003992 // First user changes IME manually.
3993 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3994 mContext.binder.callingUid = firstUserSystemUid;
3995 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3996 mContext.binder.callingUid = secondUserSystemUid;
3997 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003998
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003999 // Device owner changes IME for first user again.
4000 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004001 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004002 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004003 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004004 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004005 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004006 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4007 mContext.binder.callingUid = firstUserSystemUid;
4008 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4009 mContext.binder.callingUid = secondUserSystemUid;
4010 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004011
4012 // Restarting the DPMS should not lose information.
4013 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004014 mContext.binder.callingUid = firstUserSystemUid;
4015 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4016 mContext.binder.callingUid = secondUserSystemUid;
4017 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004018
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004019 // Device owner can find out whether it set the current IME itself.
4020 mContext.binder.callingUid = deviceOwnerUid;
4021 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004022
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004023 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004024 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004025 mContext.binder.callingUid = firstUserSystemUid;
4026 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4027 mContext.binder.callingUid = secondUserSystemUid;
4028 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004029 }
4030
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004031 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4032 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4033 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4034 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4035 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4036 DpmMockContext.SYSTEM_UID);
4037 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4038 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004039
4040 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004041 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004042 setupProfileOwner();
4043
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004044 // First and second user set IMEs manually.
4045 mContext.binder.callingUid = firstUserSystemUid;
4046 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4047 mContext.binder.callingUid = secondUserSystemUid;
4048 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004049
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004050 // Profile owner changes IME for second user.
4051 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004052 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004053 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004054 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004055 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004056 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004057 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004058 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4059 mContext.binder.callingUid = firstUserSystemUid;
4060 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4061 mContext.binder.callingUid = secondUserSystemUid;
4062 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004063
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004064 // First user changes IME manually.
4065 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4066 mContext.binder.callingUid = firstUserSystemUid;
4067 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4068 mContext.binder.callingUid = secondUserSystemUid;
4069 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004070
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004071 // Second user changes IME manually.
4072 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4073 mContext.binder.callingUid = firstUserSystemUid;
4074 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4075 mContext.binder.callingUid = secondUserSystemUid;
4076 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004077
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004078 // Profile owner changes IME for second user again.
4079 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004080 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004081 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004082 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004083 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004084 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004085 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4086 mContext.binder.callingUid = firstUserSystemUid;
4087 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4088 mContext.binder.callingUid = secondUserSystemUid;
4089 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004090
4091 // Restarting the DPMS should not lose information.
4092 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004093 mContext.binder.callingUid = firstUserSystemUid;
4094 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4095 mContext.binder.callingUid = secondUserSystemUid;
4096 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004097
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004098 // Profile owner can find out whether it set the current IME itself.
4099 mContext.binder.callingUid = profileOwnerUid;
4100 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004101
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004102 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004103 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004104 mContext.binder.callingUid = firstUserSystemUid;
4105 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4106 mContext.binder.callingUid = secondUserSystemUid;
4107 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004108 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004109
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004110 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4111 throws Exception {
4112 // Set up a device owner.
4113 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4114 setupDeviceOwner();
4115 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4116 }
4117
4118 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4119 throws Exception {
4120 // Set up a profile owner.
4121 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4122 setupProfileOwner();
4123 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4124 }
4125
4126 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4127 int adminUid) throws Exception {
4128 mContext.binder.callingUid = adminUid;
4129 final int userId = UserHandle.getUserId(adminUid);
4130
4131 final String packageName = "some.package";
4132 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4133 admin1, Collections.singletonList(packageName)));
4134 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4135
4136 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4137 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4138
4139 // Attempt to set to empty list (which means no listener is whitelisted)
4140 mContext.binder.callingUid = adminUid;
4141 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004142 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004143 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4144
4145 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4146 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4147 }
4148
4149 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4150 // Set up a managed profile
4151 final int MANAGED_PROFILE_USER_ID = 15;
4152 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4153 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4154 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4155
4156 final String permittedListener = "some.package";
4157 setupPackageInPackageManager(
4158 permittedListener,
4159 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4160 /*appId=*/ 12345, /*flags=*/ 0);
4161
4162 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4163 admin1, Collections.singletonList(permittedListener)));
4164
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004165 // isNotificationListenerServicePermitted should throw if not called from System.
4166 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4167 () -> dpms.isNotificationListenerServicePermitted(
4168 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004169
4170 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4171 assertTrue(dpms.isNotificationListenerServicePermitted(
4172 permittedListener, MANAGED_PROFILE_USER_ID));
4173 }
4174
4175 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4176 throws Exception {
4177 // Set up a managed profile
4178 final int MANAGED_PROFILE_USER_ID = 15;
4179 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4180 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4181 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4182
4183 final String permittedListener = "permitted.package";
4184 int appId = 12345;
4185 setupPackageInPackageManager(
4186 permittedListener,
4187 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4188 appId, /*flags=*/ 0);
4189
4190 final String notPermittedListener = "not.permitted.package";
4191 setupPackageInPackageManager(
4192 notPermittedListener,
4193 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4194 ++appId, /*flags=*/ 0);
4195
4196 final String systemListener = "system.package";
4197 setupPackageInPackageManager(
4198 systemListener,
4199 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4200 ++appId, ApplicationInfo.FLAG_SYSTEM);
4201
4202 // By default all packages are allowed
4203 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4204
4205 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4206 assertTrue(dpms.isNotificationListenerServicePermitted(
4207 permittedListener, MANAGED_PROFILE_USER_ID));
4208 assertTrue(dpms.isNotificationListenerServicePermitted(
4209 notPermittedListener, MANAGED_PROFILE_USER_ID));
4210 assertTrue(dpms.isNotificationListenerServicePermitted(
4211 systemListener, MANAGED_PROFILE_USER_ID));
4212
4213 // Setting only one package in the whitelist
4214 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4215 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4216 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004217 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004218 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4219 assertEquals(1, permittedListeners.size());
4220 assertEquals(permittedListener, permittedListeners.get(0));
4221
4222 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4223 assertTrue(dpms.isNotificationListenerServicePermitted(
4224 permittedListener, MANAGED_PROFILE_USER_ID));
4225 assertFalse(dpms.isNotificationListenerServicePermitted(
4226 notPermittedListener, MANAGED_PROFILE_USER_ID));
4227 // System packages are always allowed (even if not in the whitelist)
4228 assertTrue(dpms.isNotificationListenerServicePermitted(
4229 systemListener, MANAGED_PROFILE_USER_ID));
4230
4231 // Setting an empty whitelist - only system listeners allowed
4232 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4233 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004234 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004235 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4236
4237 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4238 assertFalse(dpms.isNotificationListenerServicePermitted(
4239 permittedListener, MANAGED_PROFILE_USER_ID));
4240 assertFalse(dpms.isNotificationListenerServicePermitted(
4241 notPermittedListener, MANAGED_PROFILE_USER_ID));
4242 // System packages are always allowed (even if not in the whitelist)
4243 assertTrue(dpms.isNotificationListenerServicePermitted(
4244 systemListener, MANAGED_PROFILE_USER_ID));
4245
4246 // Setting a null whitelist - all listeners allowed
4247 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4248 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4249 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4250
4251 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4252 assertTrue(dpms.isNotificationListenerServicePermitted(
4253 permittedListener, MANAGED_PROFILE_USER_ID));
4254 assertTrue(dpms.isNotificationListenerServicePermitted(
4255 notPermittedListener, MANAGED_PROFILE_USER_ID));
4256 assertTrue(dpms.isNotificationListenerServicePermitted(
4257 systemListener, MANAGED_PROFILE_USER_ID));
4258 }
4259
4260 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4261 throws Exception {
4262 // Set up a managed profile
4263 final int MANAGED_PROFILE_USER_ID = 15;
4264 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4265 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4266 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4267
4268 final String nonSystemPackage = "non.system.package";
4269 int appId = 12345;
4270 setupPackageInPackageManager(
4271 nonSystemPackage,
4272 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4273 appId, /*flags=*/ 0);
4274
4275 final String systemListener = "system.package";
4276 setupPackageInPackageManager(
4277 systemListener,
4278 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4279 ++appId, ApplicationInfo.FLAG_SYSTEM);
4280
4281 // By default all packages are allowed (for all profiles)
4282 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4283
4284 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4285 assertTrue(dpms.isNotificationListenerServicePermitted(
4286 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4287 assertTrue(dpms.isNotificationListenerServicePermitted(
4288 systemListener, MANAGED_PROFILE_USER_ID));
4289 assertTrue(dpms.isNotificationListenerServicePermitted(
4290 nonSystemPackage, UserHandle.USER_SYSTEM));
4291 assertTrue(dpms.isNotificationListenerServicePermitted(
4292 systemListener, UserHandle.USER_SYSTEM));
4293
4294 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4295 // all allowed in primary profile
4296 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4297 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004298 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004299 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4300
4301 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4302 assertFalse(dpms.isNotificationListenerServicePermitted(
4303 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4304 assertTrue(dpms.isNotificationListenerServicePermitted(
4305 systemListener, MANAGED_PROFILE_USER_ID));
4306 assertTrue(dpms.isNotificationListenerServicePermitted(
4307 nonSystemPackage, UserHandle.USER_SYSTEM));
4308 assertTrue(dpms.isNotificationListenerServicePermitted(
4309 systemListener, UserHandle.USER_SYSTEM));
4310 }
4311
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004312 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004313 mServiceContext.packageName = mRealTestContext.getPackageName();
4314 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4315 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004316 setDeviceOwner();
4317
Pavel Grafov75c0a892017-05-18 17:28:27 +01004318 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004319 }
4320
4321 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004322 mServiceContext.packageName = mRealTestContext.getPackageName();
4323 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4324 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004325 setAsProfileOwner(admin1);
4326
Pavel Grafov75c0a892017-05-18 17:28:27 +01004327 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4328 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004329 }
4330
4331 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004332 mServiceContext.packageName = mRealTestContext.getPackageName();
4333 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4334 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004335 setAsProfileOwner(admin1);
4336
Pavel Grafov75c0a892017-05-18 17:28:27 +01004337 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4338 caller.packageName = "com.example.delegate";
4339 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4340 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004341
Pavel Grafov75c0a892017-05-18 17:28:27 +01004342 // Make caller a delegated cert installer.
4343 runAsCaller(mAdmin1Context, dpms,
4344 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004345
4346 verifyCanGetOwnerInstalledCaCerts(null, caller);
4347 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004348 }
4349
Robin Lee2c68dad2017-03-17 12:50:24 +00004350 private void verifyCanGetOwnerInstalledCaCerts(
4351 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004352 final String alias = "cert";
4353 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004354
4355 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004356 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004357 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4358 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004359 }
4360 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4361
4362 // caller: device admin or delegated certificate installer
4363 callerContext.applicationInfo = new ApplicationInfo();
4364 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4365
4366 // system_server
4367 final DpmMockContext serviceContext = mContext;
4368 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004369 getServices().addPackageContext(callerUser, admin1Context);
4370 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004371
4372 // Install a CA cert.
4373 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004374 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004375 .thenReturn(alias);
4376 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004377 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004378 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004379 });
4380
Pavel Grafov75c0a892017-05-18 17:28:27 +01004381 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4382 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4383 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004384 flushTasks();
4385
Robin Lee2c68dad2017-03-17 12:50:24 +00004386 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4387
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004388 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004389 runAsCaller(admin1Context, dpms, (dpm) -> {
4390 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004391 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004392 ownerInstalledCaCerts.addAll(installedCaCerts);
4393 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004394
4395 // Restarting the DPMS should not lose information.
4396 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004397 runAsCaller(admin1Context, dpms, (dpm) ->
4398 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004399
4400 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004401 runAsCaller(serviceContext, dpms, (dpm) -> {
4402 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004403
Robin Lee2c68dad2017-03-17 12:50:24 +00004404 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004405 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004406 });
4407
Pavel Grafov75c0a892017-05-18 17:28:27 +01004408 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4409 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4410 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004411 flushTasks();
4412
4413 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4414 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004415 runAsCaller(admin1Context, dpms, (dpm) -> {
4416 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4417 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004418 }
4419
Robin Lee2c68dad2017-03-17 12:50:24 +00004420 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4421 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004422 final String alias = "cert";
4423 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004424
4425 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004426 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004427 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4428 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004429 }
4430 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4431
4432 // caller: device admin or delegated certificate installer
4433 callerContext.applicationInfo = new ApplicationInfo();
4434 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4435
4436 // system_server
4437 final DpmMockContext serviceContext = mContext;
4438 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004439 getServices().addPackageContext(callerUser, admin1Context);
4440 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004441
4442 // Install a CA cert as caller
4443 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004444 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004445 .thenReturn(alias);
4446 assertTrue(dpm.installCaCert(callerName, caCert));
4447 });
4448
4449 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004450 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004451 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004452 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4453 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4454 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004455 flushTasks();
4456
Robin Lee2c68dad2017-03-17 12:50:24 +00004457 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004458 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004459
4460 runAsCaller(serviceContext, dpms, (dpm) -> {
4461 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4462 assertNotNull(ownerInstalledCaCerts);
4463 assertTrue(ownerInstalledCaCerts.isEmpty());
4464 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004465 }
4466
Eran Messeri94d56762017-12-21 20:50:54 +00004467 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4468 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4469 Arrays.sort(gotFlags);
4470 Arrays.sort(expectedFlags);
4471 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4472 }
4473
4474 public void testTranslationOfIdAttestationFlag() {
4475 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4476 int[] correspondingAttUtilsTypes = new int[]{
4477 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4478 AttestationUtils.ID_TYPE_MEID};
4479
4480 // Test translation of zero flags
4481 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4482
4483 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4484 // non-null array
4485 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4486
4487 // Test translation of a single flag
4488 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4489 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4490 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4491
4492 // Test translation of two flags
4493 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4494 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4495 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4496 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4497
4498 // Test translation of all three flags
4499 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4500 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4501 AttestationUtils.ID_TYPE_MEID});
4502 // Test translation of all three flags
4503 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4504 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4505 AttestationUtils.ID_TYPE_MEID});
4506 }
4507
Victor Chang3e794af2016-03-04 13:48:17 +00004508 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004509 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004510 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4511 dpms.notifyChangeToContentObserver(
4512 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4513 }
4514
4515 private void assertProvisioningAllowed(String action, boolean expected) {
4516 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4517 dpm.isProvisioningAllowed(action));
4518 }
Tony Mak2f26b792016-11-28 17:54:51 +00004519
Nicolas Prevot45d29072017-01-18 16:11:19 +00004520 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4521 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004522 final String previousPackageName = mContext.packageName;
4523 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004524
4525 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4526 mContext.packageName = packageName;
4527 mMockContext.binder.callingUid = uid;
4528 assertProvisioningAllowed(action, expected);
4529
4530 // Set the previous package name / calling uid to go back to the initial state.
4531 mContext.packageName = previousPackageName;
4532 mMockContext.binder.callingUid = previousUid;
4533 }
4534
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004535 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004536 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4537 }
4538
4539 private void assertCheckProvisioningPreCondition(
4540 String action, String packageName, int provisioningCondition) {
4541 assertEquals("checkProvisioningPreCondition("
4542 + action + ", " + packageName + ") returning unexpected result",
4543 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004544 }
4545
Tony Mak2f26b792016-11-28 17:54:51 +00004546 /**
4547 * Setup a managed profile with the specified admin and its uid.
4548 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4549 * @param adminUid uid of the admin package.
4550 * @param copyFromAdmin package information for {@code admin} will be built based on this
4551 * component's information.
4552 */
4553 private void addManagedProfile(
4554 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4555 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004556 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004557 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4558 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4559 dpm.setActiveAdmin(admin, false, userId);
4560 assertTrue(dpm.setProfileOwner(admin, null, userId));
4561 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4562 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004563
4564 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004565 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004566 */
Robin Leeabaa0692017-02-20 20:54:22 +00004567 private static StringParceledListSlice asSlice(String[] s) {
4568 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004569 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004570
4571 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004572 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4573 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004574
Robin Lee2c68dad2017-03-17 12:50:24 +00004575 // We can't let exceptions happen on the background thread. Throw them here if they happen
4576 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004577 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004578 }
Victor Chang3e794af2016-03-04 13:48:17 +00004579}