blob: 57030e433fa908126fbf5671ec556bc18c236d27 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
Eran Messeri94d56762017-12-21 20:50:54 +000020import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
21import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
22import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
23import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
yinxuf4f9cec2017-06-19 10:28:19 -070024import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010025import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
26import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
27import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
28
Eugene Susla4f8680b2017-08-07 17:25:30 -070029import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010030
Pavel Grafov75c0a892017-05-18 17:28:27 +010031import static org.mockito.Matchers.any;
32import static org.mockito.Matchers.anyInt;
33import static org.mockito.Matchers.anyLong;
34import static org.mockito.Matchers.anyObject;
35import static org.mockito.Matchers.anyString;
36import static org.mockito.Matchers.eq;
37import static org.mockito.Matchers.isNull;
38import static org.mockito.Mockito.atLeast;
39import static org.mockito.Mockito.doAnswer;
40import static org.mockito.Mockito.doReturn;
41import static org.mockito.Mockito.never;
42import static org.mockito.Mockito.nullable;
43import static org.mockito.Mockito.reset;
44import static org.mockito.Mockito.timeout;
45import static org.mockito.Mockito.times;
46import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080047import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010048import static org.mockito.Mockito.verifyZeroInteractions;
49import static org.mockito.Mockito.when;
50import static org.mockito.hamcrest.MockitoHamcrest.argThat;
51
Makoto Onukif76b06a2015-09-22 15:03:44 -070052import android.Manifest.permission;
53import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000054import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070055import android.app.admin.DeviceAdminReceiver;
56import android.app.admin.DevicePolicyManager;
57import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010058import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070059import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070060import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000061import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000062import android.content.pm.ApplicationInfo;
63import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070064import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010065import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000066import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000067import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010068import android.graphics.Color;
69import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080070import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080071import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070072import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080073import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070074import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070075import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010076import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080077import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010078import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000079import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000080import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080081import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000082import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010083import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070084import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070085
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010086import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000087import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000088import com.android.server.LocalServices;
89import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000090import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000091
Robin Lee7f5c91c2017-02-08 21:27:02 +000092import org.hamcrest.BaseMatcher;
93import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -080094import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -070095import org.mockito.invocation.InvocationOnMock;
96import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070097
Makoto Onukic8a5a552015-11-19 14:29:12 -080098import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000099import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000100import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700101import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700102import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700103import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100104import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000105import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700108 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000109 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700110 m FrameworksServicesTests &&
111 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000112 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800114 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115
116 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000117 *
118 * , or:
119 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700120 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000121@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100122@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700123public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000124 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
125 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
126 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100127 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
128 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000129
Pavel Grafov75c0a892017-05-18 17:28:27 +0100130 // TODO replace all instances of this with explicit {@link #mServiceContext}.
131 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700132 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100133
134 private DpmMockContext mServiceContext;
135 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700136 public DevicePolicyManager dpm;
137 public DevicePolicyManagerServiceTestable dpms;
138
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100139 /*
140 * The CA cert below is the content of cacert.pem as generated by:
141 *
142 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
143 */
144 private static final String TEST_CA =
145 "-----BEGIN CERTIFICATE-----\n" +
146 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
147 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
148 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
149 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
150 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
151 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
152 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
153 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
154 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
155 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
156 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
157 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
158 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
159 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
160 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
161 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
162 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
163 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
164 "wQ==\n" +
165 "-----END CERTIFICATE-----\n";
166
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700167 @Override
168 protected void setUp() throws Exception {
169 super.setUp();
170
171 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100172 mServiceContext = mContext;
173 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
174 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700175 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100176 doReturn(Collections.singletonList(new ResolveInfo()))
177 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
178 any(Intent.class),
179 anyInt(),
180 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700181
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800182 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100183 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800184
Makoto Onukia52562c2015-10-01 16:12:31 -0700185 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700186
Sudheer Shanka101c3532018-01-08 16:28:42 -0800187 Mockito.reset(getServices().usageStatsManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700188 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
189 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
190 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800191 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700192
Pavel Grafov75c0a892017-05-18 17:28:27 +0100193 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
194 mAdmin1Context.packageName = admin1.getPackageName();
195 mAdmin1Context.applicationInfo = new ApplicationInfo();
196 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
197
Makoto Onukib643fb02015-09-22 15:03:44 -0700198 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700199 }
200
Robin Lee2c68dad2017-03-17 12:50:24 +0000201 @Override
202 protected void tearDown() throws Exception {
203 flushTasks();
204 super.tearDown();
205 }
206
Makoto Onukia52562c2015-10-01 16:12:31 -0700207 private void initializeDpms() {
208 // Need clearCallingIdentity() to pass permission checks.
209 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100210 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700211
Pavel Grafov75c0a892017-05-18 17:28:27 +0100212 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
Sudheer Shanka101c3532018-01-08 16:28:42 -0800213 dpms.handleStart();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100214 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
215 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700216
Pavel Grafov75c0a892017-05-18 17:28:27 +0100217 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700218
Pavel Grafov75c0a892017-05-18 17:28:27 +0100219 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700220 }
221
Makoto Onukib643fb02015-09-22 15:03:44 -0700222 private void setUpUserManager() {
223 // Emulate UserManager.set/getApplicationRestriction().
224 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
225
226 // UM.setApplicationRestrictions() will save to appRestrictions.
227 doAnswer(new Answer<Void>() {
228 @Override
229 public Void answer(InvocationOnMock invocation) throws Throwable {
230 String pkg = (String) invocation.getArguments()[0];
231 Bundle bundle = (Bundle) invocation.getArguments()[1];
232 UserHandle user = (UserHandle) invocation.getArguments()[2];
233
234 appRestrictions.put(Pair.create(pkg, user), bundle);
235
236 return null;
237 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100238 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100239 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700240
241 // UM.getApplicationRestrictions() will read from appRestrictions.
242 doAnswer(new Answer<Bundle>() {
243 @Override
244 public Bundle answer(InvocationOnMock invocation) throws Throwable {
245 String pkg = (String) invocation.getArguments()[0];
246 UserHandle user = (UserHandle) invocation.getArguments()[1];
247
248 return appRestrictions.get(Pair.create(pkg, user));
249 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100250 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700251 anyString(), any(UserHandle.class));
252
Makoto Onukid932f762015-09-29 16:53:38 -0700253 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100254 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700255 }
256
257 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100258 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700259
Pavel Grafov75c0a892017-05-18 17:28:27 +0100260 mServiceContext.binder.callingUid =
261 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
262 runAsCaller(mServiceContext, dpms, dpm -> {
263 // PO needs to be a DA.
264 dpm.setActiveAdmin(admin, /*replace=*/ false);
265 // Fire!
266 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
267 // Check
268 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
269 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700270
Pavel Grafov75c0a892017-05-18 17:28:27 +0100271 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700272 }
273
274 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100275 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700276 .thenReturn(false);
277
278 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100279 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700280
281 // If the device has no DPMS feature, it shouldn't register the local service.
282 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
283 }
284
Sudheer Shanka101c3532018-01-08 16:28:42 -0800285 public void testHandleStart() throws Exception {
286 // Device owner in SYSTEM_USER
287 setDeviceOwner();
288 // Profile owner in CALLER_USER_HANDLE
289 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
290 setAsProfileOwner(admin2);
291 // Active admin in CALLER_USER_HANDLE
292 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
293 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
294 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
295 DpmMockContext.CALLER_USER_HANDLE);
296 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
297 DpmMockContext.CALLER_USER_HANDLE));
298
299 initializeDpms();
300
301 // Verify
302 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
303 MockUtils.checkAdminApps(admin1.getPackageName()),
304 eq(UserHandle.USER_SYSTEM));
305 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
306 MockUtils.checkAdminApps(admin2.getPackageName(),
307 adminAnotherPackage.getPackageName()),
308 eq(DpmMockContext.CALLER_USER_HANDLE));
309 }
310
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700311 /**
312 * Caller doesn't have proper permissions.
313 */
314 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700315 // 1. Failure cases.
316
317 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100318 assertExpectException(SecurityException.class, /* messageRegex= */ null,
319 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700320
321 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
322 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100323
324 assertExpectException(SecurityException.class, /* messageRegex= */ null,
325 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700326 }
327
Makoto Onukif76b06a2015-09-22 15:03:44 -0700328 /**
329 * Test for:
330 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800331 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700332 * {@link DevicePolicyManager#isAdminActive}
333 * {@link DevicePolicyManager#isAdminActiveAsUser}
334 * {@link DevicePolicyManager#getActiveAdmins}
335 * {@link DevicePolicyManager#getActiveAdminsAsUser}
336 */
337 public void testSetActiveAdmin() throws Exception {
338 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700339 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
340
Makoto Onukif76b06a2015-09-22 15:03:44 -0700341 // 2. Call the API.
342 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700343
344 // 3. Verify internal calls.
345
346 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700347 verify(mContext.spiedContext).sendBroadcastAsUser(
348 MockUtils.checkIntentAction(
349 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
350 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
351 verify(mContext.spiedContext).sendBroadcastAsUser(
352 MockUtils.checkIntentAction(
353 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700354 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
355
Pavel Grafov75c0a892017-05-18 17:28:27 +0100356 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700357 eq(admin1.getPackageName()),
358 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
359 eq(PackageManager.DONT_KILL_APP),
360 eq(DpmMockContext.CALLER_USER_HANDLE),
361 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700362
Sudheer Shanka101c3532018-01-08 16:28:42 -0800363 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
364 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
365
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700366 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700367
368 // Make sure it's active admin1.
369 assertTrue(dpm.isAdminActive(admin1));
370 assertFalse(dpm.isAdminActive(admin2));
371 assertFalse(dpm.isAdminActive(admin3));
372
373 // But not admin1 for a different user.
374
375 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
376 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
377 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
378
379 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
380 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
381
382 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
383
384 // Next, add one more admin.
385 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700386 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700387 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700388
389 dpm.setActiveAdmin(admin2, /* replace =*/ false);
390
391 // Now we have two admins.
392 assertTrue(dpm.isAdminActive(admin1));
393 assertTrue(dpm.isAdminActive(admin2));
394 assertFalse(dpm.isAdminActive(admin3));
395
396 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
397 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100398 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700399 eq(admin1.getPackageName()),
400 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
401 eq(PackageManager.DONT_KILL_APP),
402 eq(DpmMockContext.CALLER_USER_HANDLE),
403 anyString());
404
Sudheer Shanka101c3532018-01-08 16:28:42 -0800405 // times(2) because it was previously called for admin1 which is in the same package
406 // as admin2.
407 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
408 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
409
Makoto Onukif76b06a2015-09-22 15:03:44 -0700410 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100411 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
412 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700413
414 // 5. Add the same admin1 again with replace, which should succeed.
415 dpm.setActiveAdmin(admin1, /* replace =*/ true);
416
417 // TODO make sure it's replaced.
418
419 // 6. Test getActiveAdmins()
420 List<ComponentName> admins = dpm.getActiveAdmins();
421 assertEquals(2, admins.size());
422 assertEquals(admin1, admins.get(0));
423 assertEquals(admin2, admins.get(1));
424
Sudheer Shanka101c3532018-01-08 16:28:42 -0800425 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
426 // replaced
427 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
428
Makoto Onukif76b06a2015-09-22 15:03:44 -0700429 // Another user has no admins.
430 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
431
432 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
433 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
434
435 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
436 }
437
Makoto Onukid932f762015-09-29 16:53:38 -0700438 public void testSetActiveAdmin_multiUsers() throws Exception {
439
440 final int ANOTHER_USER_ID = 100;
441 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
442
Pavel Grafov75c0a892017-05-18 17:28:27 +0100443 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700444
445 // Set up pacakge manager for the other user.
446 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700447
448 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
449
450 dpm.setActiveAdmin(admin1, /* replace =*/ false);
451
452 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
453 dpm.setActiveAdmin(admin2, /* replace =*/ false);
454
455
456 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
457 assertTrue(dpm.isAdminActive(admin1));
458 assertFalse(dpm.isAdminActive(admin2));
459
460 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
461 assertFalse(dpm.isAdminActive(admin1));
462 assertTrue(dpm.isAdminActive(admin2));
463 }
464
Makoto Onukif76b06a2015-09-22 15:03:44 -0700465 /**
466 * Test for:
467 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800468 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700469 */
470 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
471 // 1. Make sure the caller has proper permissions.
472 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
473
474 dpm.setActiveAdmin(admin1, /* replace =*/ false);
475 assertTrue(dpm.isAdminActive(admin1));
476
477 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100478 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
479 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700480 }
481
482 /**
483 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800484 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
485 * BIND_DEVICE_ADMIN.
486 */
487 public void testSetActiveAdmin_permissionCheck() throws Exception {
488 // 1. Make sure the caller has proper permissions.
489 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
490
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100491 assertExpectException(IllegalArgumentException.class,
492 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
493 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800494 assertFalse(dpm.isAdminActive(adminNoPerm));
495
496 // Change the target API level to MNC. Now it can be set as DA.
497 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
498 VERSION_CODES.M);
499 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
500 assertTrue(dpm.isAdminActive(adminNoPerm));
501
502 // TODO Test the "load from the file" case where DA will still be loaded even without
503 // BIND_DEVICE_ADMIN and target API is N.
504 }
505
506 /**
507 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700508 * {@link DevicePolicyManager#removeActiveAdmin}
509 */
510 public void testRemoveActiveAdmin_SecurityException() {
511 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
512
513 // Add admin.
514
515 dpm.setActiveAdmin(admin1, /* replace =*/ false);
516
517 assertTrue(dpm.isAdminActive(admin1));
518
519 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
520
521 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100522 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
523 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700524
525 // Try to remove active admin with a different caller userid should fail too, without
526 // having MANAGE_DEVICE_ADMINS.
527 mContext.callerPermissions.clear();
528
Makoto Onukid932f762015-09-29 16:53:38 -0700529 // Change the caller, and call into DPMS directly with a different user-id.
530
Makoto Onukif76b06a2015-09-22 15:03:44 -0700531 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100532 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
533 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700534 }
535
536 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800537 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
538 * (because we can't send the remove broadcast).
539 */
540 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
541 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
542
543 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
544
545 // Add admin.
546
547 dpm.setActiveAdmin(admin1, /* replace =*/ false);
548
549 assertTrue(dpm.isAdminActive(admin1));
550
551 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
552
553 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100554 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800555 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100556 assertExpectException(IllegalStateException.class,
557 /* messageRegex= */ "User must be running and unlocked",
558 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800559
560 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800561 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
562 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800563
564 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100565 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800566 .thenReturn(true);
567
568 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700569 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800570 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
571 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800572 }
573
574 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700575 * Test for:
576 * {@link DevicePolicyManager#removeActiveAdmin}
577 */
Makoto Onukid932f762015-09-29 16:53:38 -0700578 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700579 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
580
581 // Add admin1.
582
583 dpm.setActiveAdmin(admin1, /* replace =*/ false);
584
585 assertTrue(dpm.isAdminActive(admin1));
586 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
587
588 // Different user, but should work, because caller has proper permissions.
589 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700590
591 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700592 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700593
594 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700595 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800596 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
597 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700598
599 // TODO DO Still can't be removed in this case.
600 }
601
602 /**
603 * Test for:
604 * {@link DevicePolicyManager#removeActiveAdmin}
605 */
606 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
607 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
608 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
609
610 // Add admin1.
611
612 dpm.setActiveAdmin(admin1, /* replace =*/ false);
613
614 assertTrue(dpm.isAdminActive(admin1));
615 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
616
617 // Broadcast from saveSettingsLocked().
618 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
619 MockUtils.checkIntentAction(
620 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
621 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
622
623 // Remove. No permissions, but same user, so it'll work.
624 mContext.callerPermissions.clear();
625 dpm.removeActiveAdmin(admin1);
626
Makoto Onukif76b06a2015-09-22 15:03:44 -0700627 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
628 MockUtils.checkIntentAction(
629 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
630 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
631 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700632 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700633 eq(dpms.mHandler),
634 eq(Activity.RESULT_OK),
635 isNull(String.class),
636 isNull(Bundle.class));
637
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700638 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800639 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
640 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700641
642 // Again broadcast from saveSettingsLocked().
643 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
644 MockUtils.checkIntentAction(
645 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
646 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
647
648 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700649 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700650
Sudheer Shanka101c3532018-01-08 16:28:42 -0800651 public void testRemoveActiveAdmin_multipleAdminsInUser() {
652 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
653 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
654
655 // Add admin1.
656 dpm.setActiveAdmin(admin1, /* replace =*/ false);
657
658 assertTrue(dpm.isAdminActive(admin1));
659 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
660
661 // Add admin2.
662 dpm.setActiveAdmin(admin2, /* replace =*/ false);
663
664 assertTrue(dpm.isAdminActive(admin2));
665 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
666
667 // Broadcast from saveSettingsLocked().
668 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
669 MockUtils.checkIntentAction(
670 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
671 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
672
673 // Remove. No permissions, but same user, so it'll work.
674 mContext.callerPermissions.clear();
675 dpm.removeActiveAdmin(admin1);
676
677 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
678 MockUtils.checkIntentAction(
679 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
680 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
681 isNull(String.class),
682 any(BroadcastReceiver.class),
683 eq(dpms.mHandler),
684 eq(Activity.RESULT_OK),
685 isNull(String.class),
686 isNull(Bundle.class));
687
688 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
689 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
690 MockUtils.checkAdminApps(admin2.getPackageName()),
691 eq(DpmMockContext.CALLER_USER_HANDLE));
692
693 // Again broadcast from saveSettingsLocked().
694 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
695 MockUtils.checkIntentAction(
696 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
697 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
698 }
699
700 /**
701 * Test for:
702 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
703 */
704 public void testForceRemoveActiveAdmin() throws Exception {
705 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
706
707 // Add admin.
708 setupPackageInPackageManager(admin1.getPackageName(),
709 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
710 /* appId= */ 10138,
711 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
712 dpm.setActiveAdmin(admin1, /* replace =*/ false);
713 assertTrue(dpm.isAdminActive(admin1));
714
715 // Calling from a non-shell uid should fail with a SecurityException
716 mContext.binder.callingUid = 123456;
717 assertExpectException(SecurityException.class,
718 /* messageRegex =*/ "Non-shell user attempted to call",
719 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
720
721 mContext.binder.callingUid = Process.SHELL_UID;
722 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
723
724 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
725 // Verify
726 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
727 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
728 null, DpmMockContext.CALLER_USER_HANDLE);
729 }
730
Makoto Onukib643fb02015-09-22 15:03:44 -0700731 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000732 * Test for: @{link DevicePolicyManager#setActivePasswordState}
733 *
734 * Validates that when the password for a user changes, the notification broadcast intent
735 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
736 * addition to ones in the original user.
737 */
738 public void testSetActivePasswordState_sendToProfiles() throws Exception {
739 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
740
741 final int MANAGED_PROFILE_USER_ID = 78;
742 final int MANAGED_PROFILE_ADMIN_UID =
743 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
744
745 // Setup device owner.
746 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
747 mContext.packageName = admin1.getPackageName();
748 setupDeviceOwner();
749
750 // Add a managed profile belonging to the system user.
751 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
752
753 // Change the parent user's password.
754 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
755
756 // Both the device owner and the managed profile owner should receive this broadcast.
757 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
758 intent.setComponent(admin1);
759 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
760
761 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
762 MockUtils.checkIntent(intent),
763 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
764 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
765 MockUtils.checkIntent(intent),
766 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
767 }
768
769 /**
770 * Test for: @{link DevicePolicyManager#setActivePasswordState}
771 *
772 * Validates that when the password for a managed profile changes, the notification broadcast
773 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
774 * its parent.
775 */
776 public void testSetActivePasswordState_notSentToParent() throws Exception {
777 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
778
779 final int MANAGED_PROFILE_USER_ID = 78;
780 final int MANAGED_PROFILE_ADMIN_UID =
781 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
782
783 // Setup device owner.
784 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
785 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100786 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000787 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
788 setupDeviceOwner();
789
790 // Add a managed profile belonging to the system user.
791 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
792
793 // Change the profile's password.
794 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
795
796 // Both the device owner and the managed profile owner should receive this broadcast.
797 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
798 intent.setComponent(admin1);
799 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
800
801 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
802 MockUtils.checkIntent(intent),
803 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
804 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
805 MockUtils.checkIntent(intent),
806 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
807 }
808 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000809 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700810 */
811 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000812 setDeviceOwner();
813
814 // Try to set a profile owner on the same user, which should fail.
815 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
816 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100817 assertExpectException(IllegalStateException.class,
818 /* messageRegex= */ "already has a device owner",
819 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000820
821 // DO admin can't be deactivated.
822 dpm.removeActiveAdmin(admin1);
823 assertTrue(dpm.isAdminActive(admin1));
824
825 // TODO Test getDeviceOwnerName() too. To do so, we need to change
826 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
827 }
828
829 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700830 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800831 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700832 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
833 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
834
Makoto Onukid932f762015-09-29 16:53:38 -0700835 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700836 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
837
Makoto Onukid932f762015-09-29 16:53:38 -0700838 // Make sure admin1 is installed on system user.
839 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700840
Makoto Onukic8a5a552015-11-19 14:29:12 -0800841 // Check various get APIs.
842 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
843
Makoto Onukib643fb02015-09-22 15:03:44 -0700844 // DO needs to be an DA.
845 dpm.setActiveAdmin(admin1, /* replace =*/ false);
846
847 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700848 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700849
Makoto Onukic8a5a552015-11-19 14:29:12 -0800850 // getDeviceOwnerComponent should return the admin1 component.
851 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
852 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
853
854 // Check various get APIs.
855 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
856
857 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
858 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
859 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
860 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
861
862 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
863
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000864 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100865 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000866 eq(admin1.getPackageName()));
867
Makoto Onukib643fb02015-09-22 15:03:44 -0700868 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100869 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700870 eq(UserHandle.USER_SYSTEM), eq(false));
871
872 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
873 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
874 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
875
Makoto Onukic8a5a552015-11-19 14:29:12 -0800876 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700877 }
878
Makoto Onukic8a5a552015-11-19 14:29:12 -0800879 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
880 final int origCallingUser = mContext.binder.callingUid;
881 final List origPermissions = new ArrayList(mContext.callerPermissions);
882 mContext.callerPermissions.clear();
883
884 mContext.callerPermissions.add(permission.MANAGE_USERS);
885
886 mContext.binder.callingUid = Process.SYSTEM_UID;
887
888 // TODO Test getDeviceOwnerName() too. To do so, we need to change
889 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
890 if (hasDeviceOwner) {
891 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
892 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
893 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
894
895 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
896 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
897 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
898 } else {
899 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
900 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
901 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
902
903 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
904 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
905 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
906 }
907
908 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
909 if (hasDeviceOwner) {
910 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
911 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
912 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
913
914 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
915 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
916 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
917 } else {
918 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
919 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
920 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
921
922 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
923 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
924 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
925 }
926
927 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
928 // Still with MANAGE_USERS.
929 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
930 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
931 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
932
933 if (hasDeviceOwner) {
934 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
935 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
936 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
937 } else {
938 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
939 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
940 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
941 }
942
943 mContext.binder.callingUid = Process.SYSTEM_UID;
944 mContext.callerPermissions.remove(permission.MANAGE_USERS);
945 // System can still call "OnAnyUser" without MANAGE_USERS.
946 if (hasDeviceOwner) {
947 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
948 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
949 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
950
951 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
952 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
953 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
954 } else {
955 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
956 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
957 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
958
959 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
960 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
961 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
962 }
963
964 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
965 // Still no MANAGE_USERS.
966 if (hasDeviceOwner) {
967 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
968 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
969 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
970 } else {
971 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
972 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
973 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
974 }
975
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100976 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
977 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
978 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
979 dpm::getDeviceOwnerComponentOnAnyUser);
980 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
981 dpm::getDeviceOwnerUserId);
982 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
983 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800984
985 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
986 // Still no MANAGE_USERS.
987 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
988 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
989 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
990
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100991 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
992 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
993 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
994 dpm::getDeviceOwnerComponentOnAnyUser);
995 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
996 dpm::getDeviceOwnerUserId);
997 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
998 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800999
1000 // Restore.
1001 mContext.binder.callingUid = origCallingUser;
1002 mContext.callerPermissions.addAll(origPermissions);
1003 }
1004
1005
Makoto Onukib643fb02015-09-22 15:03:44 -07001006 /**
1007 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1008 */
1009 public void testSetDeviceOwner_noSuchPackage() {
1010 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001011 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001012 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1013 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1014
1015 // Call from a process on the system user.
1016 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1017
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001018 assertExpectException(IllegalArgumentException.class,
1019 /* messageRegex= */ "Invalid component",
1020 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001021 }
1022
1023 public void testSetDeviceOwner_failures() throws Exception {
1024 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1025 }
1026
Makoto Onukia52562c2015-10-01 16:12:31 -07001027 public void testClearDeviceOwner() throws Exception {
1028 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001029 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001030 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1031 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1032
1033 // Set admin1 as a DA to the secondary user.
1034 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1035
1036 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1037
1038 // Set admin 1 as the DO to the system user.
1039
1040 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1041 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1042 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1043 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1044
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001045 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001046 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001047 eq(admin1.getPackageName()));
1048
Makoto Onukic8a5a552015-11-19 14:29:12 -08001049 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001050
Makoto Onuki90b89652016-01-28 14:44:18 -08001051 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001052 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001053 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001054
1055 assertTrue(dpm.isAdminActive(admin1));
1056 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1057
Makoto Onukia52562c2015-10-01 16:12:31 -07001058 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001059 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001060
1061 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001062 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1063 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001064
1065 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001066 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001067 assertExpectException(IllegalStateException.class,
1068 /* messageRegex= */ "User must be running and unlocked",
1069 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001070
Pavel Grafov75c0a892017-05-18 17:28:27 +01001071 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1072 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001073 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1074
1075 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001076 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001077
Pavel Grafov75c0a892017-05-18 17:28:27 +01001078 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001079 eq(false),
1080 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1081
Pavel Grafov75c0a892017-05-18 17:28:27 +01001082 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001083 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001084 eq(null),
1085 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001086
Sudheer Shanka101c3532018-01-08 16:28:42 -08001087 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1088 null, UserHandle.USER_SYSTEM);
1089
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001090 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001091
1092 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1093 // and once for clearing it.
1094 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1095 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1096 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001097 // TODO Check other calls.
1098 }
1099
1100 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1101 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001102 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001103 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1104 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1105
1106 // Set admin1 as a DA to the secondary user.
1107 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1108
1109 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1110
1111 // Set admin 1 as the DO to the system user.
1112
1113 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1114 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1115 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1116 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1117
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001118 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001119 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001120 eq(admin1.getPackageName()));
1121
Makoto Onukic8a5a552015-11-19 14:29:12 -08001122 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001123
1124 // Now call clear from the secondary user, which should throw.
1125 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1126
1127 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001128 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001129 eq(admin1.getPackageName()),
1130 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001131 assertExpectException(SecurityException.class,
1132 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1133 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001134
Makoto Onukic8a5a552015-11-19 14:29:12 -08001135 // DO shouldn't be removed.
1136 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001137 }
1138
Makoto Onukib643fb02015-09-22 15:03:44 -07001139 public void testSetProfileOwner() throws Exception {
1140 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001141
Makoto Onuki90b89652016-01-28 14:44:18 -08001142 // PO admin can't be deactivated.
1143 dpm.removeActiveAdmin(admin1);
1144 assertTrue(dpm.isAdminActive(admin1));
1145
Makoto Onuki803d6752015-10-30 12:58:39 -07001146 // Try setting DO on the same user, which should fail.
1147 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001148 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1149 runAsCaller(mServiceContext, dpms, dpm -> {
1150 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001151 assertExpectException(IllegalStateException.class,
1152 /* messageRegex= */ "already has a profile owner",
1153 () -> dpm.setDeviceOwner(admin2, "owner-name",
1154 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001155 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001156 }
1157
Makoto Onuki90b89652016-01-28 14:44:18 -08001158 public void testClearProfileOwner() throws Exception {
1159 setAsProfileOwner(admin1);
1160
1161 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1162
1163 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1164 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1165
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001166 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001167 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001168 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001169 assertExpectException(IllegalStateException.class,
1170 /* messageRegex= */ "User must be running and unlocked",
1171 () -> dpm.clearProfileOwner(admin1));
1172
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001173 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001174 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001175 dpm.clearProfileOwner(admin1);
1176
1177 // Check
1178 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001179 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001180 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1181 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001182 }
1183
Makoto Onukib643fb02015-09-22 15:03:44 -07001184 public void testSetProfileOwner_failures() throws Exception {
1185 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1186 }
1187
Makoto Onukia52562c2015-10-01 16:12:31 -07001188 public void testGetDeviceOwnerAdminLocked() throws Exception {
1189 checkDeviceOwnerWithMultipleDeviceAdmins();
1190 }
1191
1192 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1193 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1194 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1195 // make sure it gets the right component from the right user.
1196
1197 final int ANOTHER_USER_ID = 100;
1198 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1199
Pavel Grafov75c0a892017-05-18 17:28:27 +01001200 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001201
1202 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001203 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001204 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1205 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1206
1207 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1208
Pavel Grafov75c0a892017-05-18 17:28:27 +01001209 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001210
Makoto Onukia52562c2015-10-01 16:12:31 -07001211 // Make sure the admin packge is installed to each user.
1212 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1213 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1214
1215 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1216 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1217
1218 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1219
1220
1221 // Set active admins to the users.
1222 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1223 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1224
1225 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1226 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1227
1228 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1229
1230 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001231 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001232 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1233
Makoto Onukic8a5a552015-11-19 14:29:12 -08001234 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001235
1236 // Then check getDeviceOwnerAdminLocked().
1237 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1238 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1239 }
1240
1241 /**
1242 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001243 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1244 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001245 *
1246 * We didn't use to persist the DO component class name, but now we do, and the above method
1247 * finds the right component from a package name upon migration.
1248 */
1249 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001250 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001251 checkDeviceOwnerWithMultipleDeviceAdmins();
1252
1253 // Overwrite the device owner setting and clears the clas name.
1254 dpms.mOwners.setDeviceOwner(
1255 new ComponentName(admin2.getPackageName(), ""),
1256 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1257 dpms.mOwners.writeDeviceOwner();
1258
1259 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001260 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001261
1262 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001263 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001264 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001265 initializeDpms();
1266
1267 // Now the DO component name is a full name.
1268 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1269 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001270 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001271 }
1272
Makoto Onukib643fb02015-09-22 15:03:44 -07001273 public void testSetGetApplicationRestriction() {
1274 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001275 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001276
1277 {
1278 Bundle rest = new Bundle();
1279 rest.putString("KEY_STRING", "Foo1");
1280 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1281 }
1282
1283 {
1284 Bundle rest = new Bundle();
1285 rest.putString("KEY_STRING", "Foo2");
1286 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1287 }
1288
1289 {
1290 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1291 assertNotNull(returned);
1292 assertEquals(returned.size(), 1);
1293 assertEquals(returned.get("KEY_STRING"), "Foo1");
1294 }
1295
1296 {
1297 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1298 assertNotNull(returned);
1299 assertEquals(returned.size(), 1);
1300 assertEquals(returned.get("KEY_STRING"), "Foo2");
1301 }
1302
1303 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1304 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1305 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001306
Edman Anjosf9946772016-11-28 16:35:15 +01001307 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001308 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1309 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001310 *
1311 * @param packageName the name of the package to be setup
1312 * @param appId the application ID to be given to the package
1313 * @return the UID of the package as known by the mock package manager
1314 */
1315 private int setupPackageInPackageManager(final String packageName, final int appId)
1316 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001317 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001318 ApplicationInfo.FLAG_HAS_CODE);
1319 }
1320
1321 /**
1322 * Setup a package in the package manager mock. Useful for faking installed applications.
1323 *
1324 * @param packageName the name of the package to be setup
1325 * @param userId the user id where the package will be "installed"
1326 * @param appId the application ID to be given to the package
1327 * @param flags flags to set in the ApplicationInfo for this package
1328 * @return the UID of the package as known by the mock package manager
1329 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001330 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1331 int flags) throws Exception {
1332 final int uid = UserHandle.getUid(userId, appId);
1333 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001334 final PackageInfo pi = new PackageInfo();
1335 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001336 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001337 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001338 eq(packageName),
1339 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001340 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001341 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001342 eq(packageName),
1343 anyInt(),
1344 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001345 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001346 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001347 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001348 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001349 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001350 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001351 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001352 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001353 return uid;
1354 }
1355
Robin Lee7f5c91c2017-02-08 21:27:02 +00001356 public void testCertificateDisclosure() throws Exception {
1357 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1358 final UserHandle user = UserHandle.of(userId);
1359
1360 mContext.applicationInfo = new ApplicationInfo();
1361 mContext.callerPermissions.add(permission.MANAGE_USERS);
1362 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001363 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001364 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1365
Robin Leeabaa0692017-02-20 20:54:22 +00001366 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1367 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001368
1369 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1370 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1371
1372 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001373 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001374 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001375 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001376 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001377 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001378 .cancelAsUser(anyString(), anyInt(), eq(user));
1379
1380 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001381 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001382 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001383 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1384 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001385 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001386 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001387 .notifyAsUser(anyString(), anyInt(), argThat(
1388 new BaseMatcher<Notification>() {
1389 @Override
1390 public boolean matches(Object item) {
1391 final Notification noti = (Notification) item;
1392 return TEST_STRING.equals(
1393 noti.extras.getString(Notification.EXTRA_TITLE));
1394 }
1395 @Override
1396 public void describeTo(Description description) {
1397 description.appendText(
1398 "Notification{title=\"" + TEST_STRING + "\"}");
1399 }
1400 }), eq(user));
1401 }
1402
Edman Anjosf9946772016-11-28 16:35:15 +01001403 /**
1404 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1405 * privileges can acually be exercised by a delegate are not covered here.
1406 */
1407 public void testDelegation() throws Exception {
1408 setAsProfileOwner(admin1);
1409
1410 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1411
1412 // Given two packages
1413 final String CERT_DELEGATE = "com.delegate.certs";
1414 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1415 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1416 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1417 20989);
1418
1419 // On delegation
1420 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1421 mContext.packageName = admin1.getPackageName();
1422 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1423 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1424
1425 // DPMS correctly stores and retrieves the delegates
1426 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1427 assertEquals(2, policy.mDelegationMap.size());
1428 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1429 DELEGATION_CERT_INSTALL);
1430 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1431 DELEGATION_CERT_INSTALL);
1432 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1433 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1434 DELEGATION_APP_RESTRICTIONS);
1435 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1436 DELEGATION_APP_RESTRICTIONS);
1437 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1438
1439 // On calling install certificate APIs from an unauthorized process
1440 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1441 mContext.packageName = RESTRICTIONS_DELEGATE;
1442
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001443 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1444 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001445
1446 // On calling install certificate APIs from an authorized process
1447 mContext.binder.callingUid = CERT_DELEGATE_UID;
1448 mContext.packageName = CERT_DELEGATE;
1449
1450 // DPMS executes without a SecurityException
1451 try {
1452 dpm.installCaCert(null, null);
1453 } catch (SecurityException unexpected) {
1454 fail("Threw SecurityException on authorized access");
1455 } catch (NullPointerException expected) {
1456 }
1457
1458 // On removing a delegate
1459 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1460 mContext.packageName = admin1.getPackageName();
1461 dpm.setCertInstallerPackage(admin1, null);
1462
1463 // DPMS does not allow access to ex-delegate
1464 mContext.binder.callingUid = CERT_DELEGATE_UID;
1465 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001466 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1467 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001468
1469 // But still allows access to other existing delegates
1470 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1471 mContext.packageName = RESTRICTIONS_DELEGATE;
1472 try {
1473 dpm.getApplicationRestrictions(null, "pkg");
1474 } catch (SecurityException expected) {
1475 fail("Threw SecurityException on authorized access");
1476 }
1477 }
1478
Esteban Talaverabf60f722015-12-10 16:26:44 +00001479 public void testApplicationRestrictionsManagingApp() throws Exception {
1480 setAsProfileOwner(admin1);
1481
Rubin Xued1928a2016-02-11 17:23:06 +00001482 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001483 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001484 final String nonDelegateExceptionMessageRegex =
1485 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001486 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001487 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1488 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001489
Esteban Talaverabf60f722015-12-10 16:26:44 +00001490 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1491 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001492 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1493 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001494 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001495 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001496 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001497 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1498 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001499
1500 // Check via the profile owner that no restrictions were set.
1501 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001502 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001503 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1504
Rubin Xued1928a2016-02-11 17:23:06 +00001505 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001506 assertExpectException(PackageManager.NameNotFoundException.class,
1507 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1508 () -> dpm.setApplicationRestrictionsManagingPackage(
1509 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001510
Esteban Talaverabf60f722015-12-10 16:26:44 +00001511 // Let appRestrictionsManagerPackage manage app restrictions
1512 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1513 assertEquals(appRestrictionsManagerPackage,
1514 dpm.getApplicationRestrictionsManagingPackage(admin1));
1515
1516 // Now that package should be able to set and retrieve app restrictions.
1517 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001518 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001519 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1520 dpm.setApplicationRestrictions(null, "pkg1", rest);
1521 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1522 assertEquals(1, returned.size(), 1);
1523 assertEquals("Foo1", returned.get("KEY_STRING"));
1524
1525 // The same app running on a separate user shouldn't be able to manage app restrictions.
1526 mContext.binder.callingUid = UserHandle.getUid(
1527 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1528 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001529 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1530 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001531
1532 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1533 // too.
1534 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001535 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001536 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1537 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1538 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1539
1540 // Removing the ability for the package to manage app restrictions.
1541 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1542 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1543 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001544 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001545 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001546 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1547 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001548 }
1549
Makoto Onukia4f11972015-10-01 13:19:58 -07001550 public void testSetUserRestriction_asDo() throws Exception {
1551 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001552 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001553 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1554 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1555
1556 // First, set DO.
1557
1558 // Call from a process on the system user.
1559 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1560
1561 // Make sure admin1 is installed on system user.
1562 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001563
1564 // Call.
1565 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001566 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001567 UserHandle.USER_SYSTEM));
1568
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001569 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001570 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001571 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001572 DpmTestUtils.assertRestrictions(
1573 DpmTestUtils.newRestrictions(defaultRestrictions),
1574 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1575 );
1576 DpmTestUtils.assertRestrictions(
1577 DpmTestUtils.newRestrictions(defaultRestrictions),
1578 dpm.getUserRestrictions(admin1)
1579 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001580 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001581 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001582 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001583 eq(true) /* isDeviceOwner */,
1584 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001585 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001586 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001587
1588 for (String restriction : defaultRestrictions) {
1589 dpm.clearUserRestriction(admin1, restriction);
1590 }
1591
Esteban Talavera548a04b2016-12-20 15:22:30 +00001592 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001593 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001594
1595 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001596 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001597 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001598 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1599 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001600 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001601
Makoto Onukia4f11972015-10-01 13:19:58 -07001602 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001603 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001604 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001605 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1606 UserManager.DISALLOW_ADD_USER),
1607 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001608 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001609
Makoto Onuki068c54a2015-10-13 14:34:03 -07001610 DpmTestUtils.assertRestrictions(
1611 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001612 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001613 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1614 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001615 DpmTestUtils.assertRestrictions(
1616 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001617 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001618 dpm.getUserRestrictions(admin1)
1619 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001620
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001621 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001622 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001623 eq(UserHandle.USER_SYSTEM),
1624 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001625 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001626 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001627
Makoto Onuki068c54a2015-10-13 14:34:03 -07001628 DpmTestUtils.assertRestrictions(
1629 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1630 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1631 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001632 DpmTestUtils.assertRestrictions(
1633 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1634 dpm.getUserRestrictions(admin1)
1635 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001636
1637 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001638 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001639 eq(UserHandle.USER_SYSTEM),
1640 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001641 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001642 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001643
Esteban Talavera548a04b2016-12-20 15:22:30 +00001644 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001645
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001646 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1647 // DO sets them, the scope is global.
1648 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001649 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001651 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001652 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001654 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1655 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001656 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001657
1658 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1659 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001660 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001661
1662 // More tests.
1663 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001664 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001665 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001666 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1667 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001668 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001669
1670 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001671 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001672 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001673 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001674 UserManager.DISALLOW_ADD_USER),
1675 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001676 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001677
1678 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001679 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001680 eq(UserHandle.USER_SYSTEM),
1681 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001682 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001683 UserManager.DISALLOW_ADD_USER),
1684 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001685 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686
1687 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1688 // locally.
1689 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001690 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001691
1692 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1693 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1694 dpm.setCameraDisabled(admin2, true);
1695
Pavel Grafov75c0a892017-05-18 17:28:27 +01001696 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001697 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001698 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001699 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001700 UserManager.DISALLOW_ADD_USER),
1701 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001702 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001703 // TODO Make sure restrictions are written to the file.
1704 }
1705
1706 public void testSetUserRestriction_asPo() {
1707 setAsProfileOwner(admin1);
1708
Makoto Onuki068c54a2015-10-13 14:34:03 -07001709 DpmTestUtils.assertRestrictions(
1710 DpmTestUtils.newRestrictions(),
1711 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1712 .ensureUserRestrictions()
1713 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001714
1715 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001716 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001717 eq(DpmMockContext.CALLER_USER_HANDLE),
1718 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001719 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001720 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001721
Makoto Onukia4f11972015-10-01 13:19:58 -07001722 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001723 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001724 eq(DpmMockContext.CALLER_USER_HANDLE),
1725 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1726 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001727 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001728 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001729
Makoto Onuki068c54a2015-10-13 14:34:03 -07001730 DpmTestUtils.assertRestrictions(
1731 DpmTestUtils.newRestrictions(
1732 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1733 UserManager.DISALLOW_OUTGOING_CALLS
1734 ),
1735 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1736 .ensureUserRestrictions()
1737 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001738 DpmTestUtils.assertRestrictions(
1739 DpmTestUtils.newRestrictions(
1740 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1741 UserManager.DISALLOW_OUTGOING_CALLS
1742 ),
1743 dpm.getUserRestrictions(admin1)
1744 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001745
1746 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001747 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001748 eq(DpmMockContext.CALLER_USER_HANDLE),
1749 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001750 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001751 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001752
1753 DpmTestUtils.assertRestrictions(
1754 DpmTestUtils.newRestrictions(
1755 UserManager.DISALLOW_OUTGOING_CALLS
1756 ),
1757 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1758 .ensureUserRestrictions()
1759 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001760 DpmTestUtils.assertRestrictions(
1761 DpmTestUtils.newRestrictions(
1762 UserManager.DISALLOW_OUTGOING_CALLS
1763 ),
1764 dpm.getUserRestrictions(admin1)
1765 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001766
1767 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001768 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001769 eq(DpmMockContext.CALLER_USER_HANDLE),
1770 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001771 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001772 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001773
Makoto Onuki068c54a2015-10-13 14:34:03 -07001774 DpmTestUtils.assertRestrictions(
1775 DpmTestUtils.newRestrictions(),
1776 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1777 .ensureUserRestrictions()
1778 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001779 DpmTestUtils.assertRestrictions(
1780 DpmTestUtils.newRestrictions(),
1781 dpm.getUserRestrictions(admin1)
1782 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001783
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001784 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1785 // though when DO sets them they'll be applied globally.
1786 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001787 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001789 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001790 eq(DpmMockContext.CALLER_USER_HANDLE),
1791 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1792 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001793 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001794 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001795
1796 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001797 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001798 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001799 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001800 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001801 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001802 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001803
Makoto Onukia4f11972015-10-01 13:19:58 -07001804 // TODO Make sure restrictions are written to the file.
1805 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001806
Esteban Talavera548a04b2016-12-20 15:22:30 +00001807
1808 public void testDefaultEnabledUserRestrictions() throws Exception {
1809 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1810 mContext.callerPermissions.add(permission.MANAGE_USERS);
1811 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1812 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1813
1814 // First, set DO.
1815
1816 // Call from a process on the system user.
1817 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1818
1819 // Make sure admin1 is installed on system user.
1820 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1821
1822 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1823 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1824 UserHandle.USER_SYSTEM));
1825
1826 // Check that the user restrictions that are enabled by default are set. Then unset them.
1827 String[] defaultRestrictions = UserRestrictionsUtils
1828 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1829 assertTrue(defaultRestrictions.length > 0);
1830 DpmTestUtils.assertRestrictions(
1831 DpmTestUtils.newRestrictions(defaultRestrictions),
1832 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1833 );
1834 DpmTestUtils.assertRestrictions(
1835 DpmTestUtils.newRestrictions(defaultRestrictions),
1836 dpm.getUserRestrictions(admin1)
1837 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001838 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001839 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001840 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001841 eq(true) /* isDeviceOwner */,
1842 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001843 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001844 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001845
1846 for (String restriction : defaultRestrictions) {
1847 dpm.clearUserRestriction(admin1, restriction);
1848 }
1849
1850 assertNoDeviceOwnerRestrictions();
1851
1852 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001853 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001854 initializeDpms();
1855 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1856 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1857
1858 assertNoDeviceOwnerRestrictions();
1859
1860 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1861 // is set as it wasn't enabled during setDeviceOwner.
1862 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1863 assertFalse(UserRestrictionsUtils
1864 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1865 UserRestrictionsUtils
1866 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1867 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001868 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001869 initializeDpms();
1870 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1871 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1872
1873 DpmTestUtils.assertRestrictions(
1874 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1875 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1876 );
1877 DpmTestUtils.assertRestrictions(
1878 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1879 dpm.getUserRestrictions(admin1)
1880 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001881 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001882 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001883 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001884 eq(true) /* isDeviceOwner */,
1885 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001886 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001887 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001888
1889 // Remove the restriction.
1890 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1891
1892 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1893 initializeDpms();
1894 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1895 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1896 assertNoDeviceOwnerRestrictions();
1897 } finally {
1898 UserRestrictionsUtils
1899 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1900 }
1901 }
1902
1903 private void assertNoDeviceOwnerRestrictions() {
1904 DpmTestUtils.assertRestrictions(
1905 DpmTestUtils.newRestrictions(),
1906 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1907 );
1908 DpmTestUtils.assertRestrictions(
1909 DpmTestUtils.newRestrictions(),
1910 dpm.getUserRestrictions(admin1)
1911 );
1912 }
1913
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001914 public void testGetMacAddress() throws Exception {
1915 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1916 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1917 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1918
1919 // In this test, change the caller user to "system".
1920 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1921
1922 // Make sure admin1 is installed on system user.
1923 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1924
1925 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001926 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1927 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001928
1929 // DO needs to be an DA.
1930 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1931 assertTrue(dpm.isAdminActive(admin1));
1932
1933 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001934 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1935 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001936
1937 // Test 3. Caller has PO, but not DO.
1938 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001939 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1940 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001941
1942 // Remove PO.
1943 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001944 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001945 // Test 4, Caller is DO now.
1946 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1947
1948 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001949 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001950
1951 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001952 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001953 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001954
1955 // 4-3. With a real MAC address.
1956 final WifiInfo wi = new WifiInfo();
1957 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001958 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001959 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001960 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001961
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001962 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001963 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1964 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1965
1966 // In this test, change the caller user to "system".
1967 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1968
1969 // Make sure admin1 is installed on system user.
1970 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1971
1972 // Set admin1 as DA.
1973 dpm.setActiveAdmin(admin1, false);
1974 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001975 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1976 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001977
1978 // Set admin1 as PO.
1979 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001980 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1981 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001982
1983 // Remove PO and add DO.
1984 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001985 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001986 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1987
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001988 // admin1 is DO.
1989 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001990 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001991 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001992 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1993 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001994
1995 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001996 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001997 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001998 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1999 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002000
2001 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002002 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002003 dpm.reboot(admin1);
2004 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002005
2006 public void testSetGetSupportText() {
2007 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2008 dpm.setActiveAdmin(admin1, true);
2009 dpm.setActiveAdmin(admin2, true);
2010 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2011
2012 // Null default support messages.
2013 {
2014 assertNull(dpm.getLongSupportMessage(admin1));
2015 assertNull(dpm.getShortSupportMessage(admin1));
2016 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2017 assertNull(dpm.getShortSupportMessageForUser(admin1,
2018 DpmMockContext.CALLER_USER_HANDLE));
2019 assertNull(dpm.getLongSupportMessageForUser(admin1,
2020 DpmMockContext.CALLER_USER_HANDLE));
2021 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2022 }
2023
2024 // Only system can call the per user versions.
2025 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002026 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2027 () -> dpm.getShortSupportMessageForUser(admin1,
2028 DpmMockContext.CALLER_USER_HANDLE));
2029 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2030 () -> dpm.getLongSupportMessageForUser(admin1,
2031 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002032 }
2033
2034 // Can't set message for admin in another uid.
2035 {
2036 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002037 assertExpectException(SecurityException.class,
2038 /* messageRegex= */ "is not owned by uid",
2039 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002040 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2041 }
2042
2043 // Set/Get short returns what it sets and other admins text isn't changed.
2044 {
2045 final String supportText = "Some text to test with.";
2046 dpm.setShortSupportMessage(admin1, supportText);
2047 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2048 assertNull(dpm.getLongSupportMessage(admin1));
2049 assertNull(dpm.getShortSupportMessage(admin2));
2050
2051 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2052 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2053 DpmMockContext.CALLER_USER_HANDLE));
2054 assertNull(dpm.getShortSupportMessageForUser(admin2,
2055 DpmMockContext.CALLER_USER_HANDLE));
2056 assertNull(dpm.getLongSupportMessageForUser(admin1,
2057 DpmMockContext.CALLER_USER_HANDLE));
2058 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2059
2060 dpm.setShortSupportMessage(admin1, null);
2061 assertNull(dpm.getShortSupportMessage(admin1));
2062 }
2063
2064 // Set/Get long returns what it sets and other admins text isn't changed.
2065 {
2066 final String supportText = "Some text to test with.\nWith more text.";
2067 dpm.setLongSupportMessage(admin1, supportText);
2068 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2069 assertNull(dpm.getShortSupportMessage(admin1));
2070 assertNull(dpm.getLongSupportMessage(admin2));
2071
2072 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2073 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2074 DpmMockContext.CALLER_USER_HANDLE));
2075 assertNull(dpm.getLongSupportMessageForUser(admin2,
2076 DpmMockContext.CALLER_USER_HANDLE));
2077 assertNull(dpm.getShortSupportMessageForUser(admin1,
2078 DpmMockContext.CALLER_USER_HANDLE));
2079 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2080
2081 dpm.setLongSupportMessage(admin1, null);
2082 assertNull(dpm.getLongSupportMessage(admin1));
2083 }
2084 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002085
phweiss73145f42017-01-17 19:06:38 +01002086 public void testCreateAdminSupportIntent() throws Exception {
2087 // Setup device owner.
2088 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2089 setupDeviceOwner();
2090
2091 // Nonexisting permission returns null
2092 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2093 assertNull(intent);
2094
2095 // Existing permission that is not set returns null
2096 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2097 assertNull(intent);
2098
2099 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002100 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002101 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2102 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2103 .thenReturn(true);
2104 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2105 assertNull(intent);
2106
2107 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002108 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002109 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2110 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2111 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2112 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2113 assertNotNull(intent);
2114 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2115 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2116 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002117 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002118 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2119 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2120
2121 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2122 // user restrictions
2123
2124 // Camera is not disabled
2125 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2126 assertNull(intent);
2127
2128 // Camera is disabled
2129 dpm.setCameraDisabled(admin1, true);
2130 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2131 assertNotNull(intent);
2132 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2133 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2134
2135 // Screen capture is not disabled
2136 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2137 assertNull(intent);
2138
2139 // Screen capture is disabled
2140 dpm.setScreenCaptureDisabled(admin1, true);
2141 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2142 assertNotNull(intent);
2143 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2144 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2145
2146 // Same checks for different user
2147 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2148 // Camera should be disabled by device owner
2149 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2150 assertNotNull(intent);
2151 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2152 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2153 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2154 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2155 // ScreenCapture should not be disabled by device owner
2156 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2157 assertNull(intent);
2158 }
2159
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002160 /**
2161 * Test for:
2162 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002163 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002164 * {@link DevicePolicyManager#isAffiliatedUser}
2165 */
2166 public void testUserAffiliation() throws Exception {
2167 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2168 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2169 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2170
2171 // Check that the system user is unaffiliated.
2172 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2173 assertFalse(dpm.isAffiliatedUser());
2174
2175 // Set a device owner on the system user. Check that the system user becomes affiliated.
2176 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2177 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2178 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2179 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002180 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002181
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002182 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002183 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2184 setAsProfileOwner(admin2);
2185 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002186 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002187
2188 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2189 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002190 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002191 userAffiliationIds.add("red");
2192 userAffiliationIds.add("green");
2193 userAffiliationIds.add("blue");
2194 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002195 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002196 assertFalse(dpm.isAffiliatedUser());
2197
2198 // Have the device owner specify a set of affiliation ids that do not intersect with those
2199 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002200 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002201 deviceAffiliationIds.add("cyan");
2202 deviceAffiliationIds.add("yellow");
2203 deviceAffiliationIds.add("magenta");
2204 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2205 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002206 MoreAsserts.assertContentsInAnyOrder(
2207 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002208 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2209 assertFalse(dpm.isAffiliatedUser());
2210
2211 // Have the profile owner specify a set of affiliation ids that intersect with those
2212 // specified by the device owner. Check that the test user becomes affiliated.
2213 userAffiliationIds.add("yellow");
2214 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002215 MoreAsserts.assertContentsInAnyOrder(
2216 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002217 assertTrue(dpm.isAffiliatedUser());
2218
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002219 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002220 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002221 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002222 assertFalse(dpm.isAffiliatedUser());
2223
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002224 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2225 dpm.setAffiliationIds(admin2, userAffiliationIds);
2226 assertTrue(dpm.isAffiliatedUser());
2227 dpm.clearProfileOwner(admin2);
2228 assertFalse(dpm.isAffiliatedUser());
2229
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002230 // Check that the system user remains affiliated.
2231 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2232 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002233
2234 // Clear the device owner - the user becomes unaffiliated.
2235 clearDeviceOwner();
2236 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002237 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002238
2239 public void testGetUserProvisioningState_defaultResult() {
2240 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2241 }
2242
2243 public void testSetUserProvisioningState_permission() throws Exception {
2244 setupProfileOwner();
2245 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2246
2247 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2248 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2249 }
2250
2251 public void testSetUserProvisioningState_unprivileged() throws Exception {
2252 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002253 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2254 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2255 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002256 }
2257
2258 public void testSetUserProvisioningState_noManagement() {
2259 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002260 assertExpectException(IllegalStateException.class,
2261 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2262 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2263 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002264 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2265 }
2266
2267 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2268 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2269 setupDeviceOwner();
2270 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2271
2272 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2273 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2274 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2275 }
2276
2277 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2278 throws Exception {
2279 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2280 setupDeviceOwner();
2281 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2282
2283 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2284 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2285 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2286 }
2287
2288 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2289 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2290 setupDeviceOwner();
2291 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2292
2293 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2294 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2295 }
2296
2297 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2298 throws Exception {
2299 setupProfileOwner();
2300 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2301
2302 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2303 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2304 DevicePolicyManager.STATE_USER_UNMANAGED);
2305 }
2306
2307 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2308 throws Exception {
2309 setupProfileOwner();
2310 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2311
2312 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2313 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2314 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2315 }
2316
2317 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2318 setupProfileOwner();
2319 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2320
2321 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2322 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2323 }
2324
2325 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2326 setupProfileOwner();
2327 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2328
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002329 assertExpectException(IllegalStateException.class,
2330 /* messageRegex= */ "Cannot move to user provisioning state",
2331 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2332 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2333 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002334 }
2335
2336 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2337 throws Exception {
2338 setupProfileOwner();
2339 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2340
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002341 assertExpectException(IllegalStateException.class,
2342 /* messageRegex= */ "Cannot move to user provisioning state",
2343 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2344 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2345 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002346 }
2347
2348 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2349 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2350 for (int state : states) {
2351 dpm.setUserProvisioningState(state, userId);
2352 assertEquals(state, dpm.getUserProvisioningState());
2353 }
2354 }
2355
2356 private void setupProfileOwner() throws Exception {
2357 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2358
2359 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2360 dpm.setActiveAdmin(admin1, false);
2361 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2362
2363 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2364 }
2365
2366 private void setupDeviceOwner() throws Exception {
2367 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2368
2369 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2370 dpm.setActiveAdmin(admin1, false);
2371 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2372
2373 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2374 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002375
2376 public void testSetMaximumTimeToLock() {
2377 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2378
2379 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2380 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2381
Pavel Grafov75c0a892017-05-18 17:28:27 +01002382 reset(getServices().powerManagerInternal);
2383 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002384
2385 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002386 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2387 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002388 reset(getServices().powerManagerInternal);
2389 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002390
2391 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002392 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2393 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002394 reset(getServices().powerManagerInternal);
2395 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002396
2397 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002398 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2399 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002400 reset(getServices().powerManagerInternal);
2401 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002402
2403 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002404 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2405 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002406 reset(getServices().powerManagerInternal);
2407 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002408
2409 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002410 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2411 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002412 reset(getServices().powerManagerInternal);
2413 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002414
2415 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002416 reset(getServices().powerManagerInternal);
2417 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002418
Pavel Grafov28939982017-10-03 15:11:52 +01002419 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2420 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2421 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002422 reset(getServices().powerManagerInternal);
2423 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002424
2425 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002426 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2427 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002428 reset(getServices().powerManagerInternal);
2429 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002430
Pavel Grafov28939982017-10-03 15:11:52 +01002431 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002432 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002433 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2434 verifyStayOnWhilePluggedCleared(false);
2435 }
2436
2437 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2438 // uses separate challenge.
2439 public void testSetMaximumTimeToLockProfile() throws Exception {
2440 final int PROFILE_USER = 15;
2441 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2442 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2443 mContext.binder.callingUid = PROFILE_ADMIN;
2444 final DevicePolicyManagerInternal dpmi =
2445 LocalServices.getService(DevicePolicyManagerInternal.class);
2446
2447 dpm.setMaximumTimeToLock(admin1, 0);
2448
2449 reset(getServices().powerManagerInternal);
2450 reset(getServices().settings);
2451
2452 // First add timeout for the profile.
2453 dpm.setMaximumTimeToLock(admin1, 10);
2454 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2455
2456 reset(getServices().powerManagerInternal);
2457 reset(getServices().settings);
2458
2459 // Add separate challenge
2460 when(getServices().lockPatternUtils
2461 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2462 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2463
2464 verifyScreenTimeoutCall(10L, PROFILE_USER);
2465 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2466
2467 reset(getServices().powerManagerInternal);
2468 reset(getServices().settings);
2469
2470 // Remove the timeout.
2471 dpm.setMaximumTimeToLock(admin1, 0);
2472 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2473 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2474
2475 reset(getServices().powerManagerInternal);
2476 reset(getServices().settings);
2477
2478 // Add it back.
2479 dpm.setMaximumTimeToLock(admin1, 10);
2480 verifyScreenTimeoutCall(10L, PROFILE_USER);
2481 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2482
2483 reset(getServices().powerManagerInternal);
2484 reset(getServices().settings);
2485
2486 // Remove separate challenge.
2487 reset(getServices().lockPatternUtils);
2488 when(getServices().lockPatternUtils
2489 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2490 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2491
2492 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2493 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2494
2495 reset(getServices().powerManagerInternal);
2496 reset(getServices().settings);
2497
2498 // Remove the timeout.
2499 dpm.setMaximumTimeToLock(admin1, 0);
2500 verifyScreenTimeoutCall(null, PROFILE_USER);
2501 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002502 }
2503
Michal Karpinski943aabd2016-10-06 11:09:25 +01002504 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2505 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2506 setupDeviceOwner();
2507 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2508
Michal Karpinskid084ca52017-01-18 15:54:18 +00002509 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2510 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2511 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2512 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2513 - ONE_MINUTE;
2514
2515 // verify that the minimum timeout cannot be modified on user builds (system property is
2516 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002517 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002518
2519 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2520 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2521 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2522
Pavel Grafov75c0a892017-05-18 17:28:27 +01002523 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002524
2525 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002526 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002527
Michal Karpinskid084ca52017-01-18 15:54:18 +00002528 // reset to default (0 means the admin is not participating, so default should be returned)
2529 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002530
2531 // aggregation should be the default if unset by any admin
2532 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2533 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2534
2535 // admin not participating by default
2536 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2537
2538 //clamping from the top
2539 dpm.setRequiredStrongAuthTimeout(admin1,
2540 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2541 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2542 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2543 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2544 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2545
Michal Karpinskid084ca52017-01-18 15:54:18 +00002546 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002547 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2548 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2549 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2550 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2551
2552 // clamping from the bottom
2553 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2554 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2555 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2556
Michal Karpinskid084ca52017-01-18 15:54:18 +00002557 // values within range
2558 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2559 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2560 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2561
2562 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2563 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2564 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002565
2566 // reset to default
2567 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2568 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2569 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2570 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2571
2572 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002573 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2574 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002575 }
2576
Pavel Grafov28939982017-10-03 15:11:52 +01002577 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002578 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002579 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002580 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002581 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002582 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002583 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002584 }
Pavel Grafov28939982017-10-03 15:11:52 +01002585 }
2586
2587 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002588 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2589 // UnfinishedVerificationException.
2590 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002591
Esteban Talavera01576862016-12-15 11:16:44 +00002592 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002593 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002594 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002595 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002596 .thenReturn(false);
2597 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002598 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2599 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002600 .thenReturn(true);
2601 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2602
2603 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002604 }
Victor Chang3e794af2016-03-04 13:48:17 +00002605
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002606 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2607 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002608 mContext.packageName = admin1.getPackageName();
2609 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002610 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2611 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2612 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2613 false);
2614 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2615 }
2616
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002617 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2618 setup_DeviceAdminFeatureOff();
2619 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2620 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2621 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2622 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2623 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2624 assertCheckProvisioningPreCondition(
2625 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2626 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2627 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2628 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2629 }
2630
Esteban Talavera01576862016-12-15 11:16:44 +00002631 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002632 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002633 .thenReturn(false);
2634 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002635 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2636 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002637 .thenReturn(true);
2638 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2639
2640 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002641 }
Victor Chang3e794af2016-03-04 13:48:17 +00002642
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002643 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2644 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002645 mContext.packageName = admin1.getPackageName();
2646 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002647 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2648 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2649 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2650 false);
2651 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2652
2653 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002654 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002655 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2656 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2657 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2658 true);
2659 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2660 }
2661
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002662 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2663 setup_ManagedProfileFeatureOff();
2664 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2665 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2666 DevicePolicyManager.CODE_OK);
2667 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2668 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2669 assertCheckProvisioningPreCondition(
2670 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2671 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2672 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2673 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2674
2675 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002676 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002677 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2678 DevicePolicyManager.CODE_OK);
2679 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2680 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2681 assertCheckProvisioningPreCondition(
2682 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2683 DevicePolicyManager.CODE_OK);
2684 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2685 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2686 }
2687
Esteban Talavera01576862016-12-15 11:16:44 +00002688 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002689 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002690 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002691 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2692 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002693 .thenReturn(true);
2694 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2695
2696 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002697 }
Victor Chang3e794af2016-03-04 13:48:17 +00002698
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002699 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2700 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002701 mContext.packageName = admin1.getPackageName();
2702 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002703 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2704 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2705 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2706 false /* because of non-split user */);
2707 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2708 false /* because of non-split user */);
2709 }
2710
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002711 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002712 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002713 setup_nonSplitUser_firstBoot_primaryUser();
2714 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2715 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2716 DevicePolicyManager.CODE_OK);
2717 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2718 DevicePolicyManager.CODE_OK);
2719 assertCheckProvisioningPreCondition(
2720 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2721 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2722 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2723 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2724 }
2725
Esteban Talavera01576862016-12-15 11:16:44 +00002726 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002727 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002728 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002729 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2730 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002731 .thenReturn(true);
2732 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2733
2734 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002735 }
Victor Chang3e794af2016-03-04 13:48:17 +00002736
Nicolas Prevot45d29072017-01-18 16:11:19 +00002737 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2738 setDeviceOwner();
2739 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2740 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2741 }
2742
2743 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2744 setup_nonSplitUser_withDo_primaryUser();
2745 final int MANAGED_PROFILE_USER_ID = 18;
2746 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2747 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002748 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002749 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002750 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002751 true)).thenReturn(true);
2752 }
2753
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002754 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2755 throws Exception {
2756 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002757 mContext.packageName = admin1.getPackageName();
2758 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002759 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2760 false/* because of completed device setup */);
2761 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2762 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2763 false/* because of non-split user */);
2764 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2765 false/* because of non-split user */);
2766 }
2767
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002768 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2769 throws Exception {
2770 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2771 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2772 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2773 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2774 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2775 DevicePolicyManager.CODE_OK);
2776 assertCheckProvisioningPreCondition(
2777 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2778 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2779 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2780 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2781 }
2782
Nicolas Prevot45d29072017-01-18 16:11:19 +00002783 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2784 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002785 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002786 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2787
2788 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2789 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002790 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002791
2792 // COMP mode is allowed.
2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2794 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002795 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002796
Nicolas Prevot45d29072017-01-18 16:11:19 +00002797 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002798 assertCheckProvisioningPreCondition(
2799 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002800 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002801 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002802 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2803 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2804 }
Esteban Talavera01576862016-12-15 11:16:44 +00002805
Nicolas Prevot45d29072017-01-18 16:11:19 +00002806 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2807 setup_nonSplitUser_withDo_primaryUser();
2808 mContext.packageName = admin1.getPackageName();
2809 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2810 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2811 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002812 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002813 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2814 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2815 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002816 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002817 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2818 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2819 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2820 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2821 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002822 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002823 assertCheckProvisioningPreCondition(
2824 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002825 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002826 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002827 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2828 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2829 }
Esteban Talavera01576862016-12-15 11:16:44 +00002830
Nicolas Prevot45d29072017-01-18 16:11:19 +00002831 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2832 throws Exception {
2833 setup_nonSplitUser_withDo_primaryUser();
2834 mContext.packageName = admin1.getPackageName();
2835 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002836 // The DO should not be allowed to initiate provisioning if the restriction is set by
2837 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002838 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002839 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2840 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2841 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002842 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002843 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2844 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2845 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2846 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2847 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002848 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2849
2850 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002851 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002852 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002853 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002854 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2855 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2856 }
2857
2858 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2859 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2860 mContext.packageName = admin1.getPackageName();
2861 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2862
2863 // We can delete the managed profile to create a new one, so provisioning is allowed.
2864 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2865 DevicePolicyManager.CODE_OK);
2866 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2867 assertCheckProvisioningPreCondition(
2868 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2869 DpmMockContext.ANOTHER_PACKAGE_NAME,
2870 DevicePolicyManager.CODE_OK);
2871 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2872 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2873 }
2874
2875 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2876 throws Exception {
2877 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2878 mContext.packageName = admin1.getPackageName();
2879 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002880 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002881 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2882 eq(UserHandle.SYSTEM)))
2883 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002884 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002885 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2886 eq(UserHandle.SYSTEM)))
2887 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002888
2889 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002890 assertCheckProvisioningPreCondition(
2891 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2892 DpmMockContext.ANOTHER_PACKAGE_NAME,
2893 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2894 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2895 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002896
2897 // But the device owner can still do it because it has set the restriction itself.
2898 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2899 DevicePolicyManager.CODE_OK);
2900 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002901 }
2902
2903 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002904 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002905 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002906 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2907 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002908 .thenReturn(false);
2909 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2910
2911 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002912 }
Victor Chang3e794af2016-03-04 13:48:17 +00002913
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002914 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2915 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002916 mContext.packageName = admin1.getPackageName();
2917 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002918 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2919 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2920 false /* because canAddMoreManagedProfiles returns false */);
2921 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2922 true);
2923 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2924 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002925 }
2926
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002927 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2928 throws Exception {
2929 setup_splitUser_firstBoot_systemUser();
2930 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2931 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2932 DevicePolicyManager.CODE_OK);
2933 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002934 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002935 assertCheckProvisioningPreCondition(
2936 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2937 DevicePolicyManager.CODE_OK);
2938 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2939 DevicePolicyManager.CODE_SYSTEM_USER);
2940 }
2941
Esteban Talavera01576862016-12-15 11:16:44 +00002942 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002943 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002944 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002945 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2946 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002947 .thenReturn(false);
2948 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2949
2950 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002951 }
Victor Chang3e794af2016-03-04 13:48:17 +00002952
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002953 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2954 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002955 mContext.packageName = admin1.getPackageName();
2956 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002957 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2958 true/* it's undefined behavior. Can be changed into false in the future */);
2959 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2960 false /* because canAddMoreManagedProfiles returns false */);
2961 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2962 true/* it's undefined behavior. Can be changed into false in the future */);
2963 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2964 false/* because calling uid is system user */);
2965 }
2966
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002967 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2968 throws Exception {
2969 setup_splitUser_afterDeviceSetup_systemUser();
2970 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2971 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2972 DevicePolicyManager.CODE_OK);
2973 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002974 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002975 assertCheckProvisioningPreCondition(
2976 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2977 DevicePolicyManager.CODE_OK);
2978 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2979 DevicePolicyManager.CODE_SYSTEM_USER);
2980 }
2981
Esteban Talavera01576862016-12-15 11:16:44 +00002982 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002983 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002984 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002985 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2986 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002987 true)).thenReturn(true);
2988 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2989
2990 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002991 }
Victor Chang3e794af2016-03-04 13:48:17 +00002992
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002993 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2994 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002995 mContext.packageName = admin1.getPackageName();
2996 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002997 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2998 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2999 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3000 true);
3001 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003002 }
3003
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003004 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003005 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003006 setup_splitUser_firstBoot_primaryUser();
3007 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3008 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3009 DevicePolicyManager.CODE_OK);
3010 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3011 DevicePolicyManager.CODE_OK);
3012 assertCheckProvisioningPreCondition(
3013 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3014 DevicePolicyManager.CODE_OK);
3015 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3016 DevicePolicyManager.CODE_OK);
3017 }
3018
Esteban Talavera01576862016-12-15 11:16:44 +00003019 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003020 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003021 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003022 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3023 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003024 true)).thenReturn(true);
3025 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3026
3027 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003028 }
Victor Chang3e794af2016-03-04 13:48:17 +00003029
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003030 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3031 throws Exception {
3032 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003033 mContext.packageName = admin1.getPackageName();
3034 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003035 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3036 true/* it's undefined behavior. Can be changed into false in the future */);
3037 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3038 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3039 true/* it's undefined behavior. Can be changed into false in the future */);
3040 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3041 false/* because user setup completed */);
3042 }
3043
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003044 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003045 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003046 setup_splitUser_afterDeviceSetup_primaryUser();
3047 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3048 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3049 DevicePolicyManager.CODE_OK);
3050 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3051 DevicePolicyManager.CODE_OK);
3052 assertCheckProvisioningPreCondition(
3053 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3054 DevicePolicyManager.CODE_OK);
3055 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3056 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3057 }
3058
Esteban Talavera01576862016-12-15 11:16:44 +00003059 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003060 setDeviceOwner();
3061
Pavel Grafov75c0a892017-05-18 17:28:27 +01003062 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003063 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003064 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3065 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003066 .thenReturn(false);
3067 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3068
3069 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003070 }
Victor Chang3e794af2016-03-04 13:48:17 +00003071
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003072 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3073 throws Exception {
3074 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003075 mContext.packageName = admin1.getPackageName();
3076 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003077 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3078 false /* can't provision managed profile on system user */);
3079 }
3080
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003081 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003082 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003083 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3084 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3085 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3086 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3087 }
3088
3089 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003090 setDeviceOwner();
3091
Pavel Grafov75c0a892017-05-18 17:28:27 +01003092 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003093 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003094 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3095 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003096 true)).thenReturn(true);
3097 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3098
3099 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003100 }
Victor Chang3e794af2016-03-04 13:48:17 +00003101
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003102 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3103 throws Exception {
3104 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003105 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3106 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003107 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3108 }
3109
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003110 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003111 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003112 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3113 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003114
3115 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003116 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3117 DevicePolicyManager.CODE_OK);
3118 }
3119
3120 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003121 setDeviceOwner();
3122
Pavel Grafov75c0a892017-05-18 17:28:27 +01003123 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003124 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003125 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3126 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003127 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3128 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003129 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003130 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003131 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003132 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003133 true)).thenReturn(true);
3134 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3135
3136 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003137 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003138
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003139 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3140 throws Exception {
3141 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003142 mContext.packageName = admin1.getPackageName();
3143 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003144 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3145 }
3146
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003147 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3148 throws Exception {
3149 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3150 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3151 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3152 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3153 }
3154
3155 public void testCheckProvisioningPreCondition_permission() {
3156 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003157 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3158 () -> dpm.checkProvisioningPreCondition(
3159 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003160 }
3161
Victor Chang3577ed22016-08-25 18:49:26 +01003162 public void testForceUpdateUserSetupComplete_permission() {
3163 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003164 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3165 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003166 }
3167
3168 public void testForceUpdateUserSetupComplete_systemUser() {
3169 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3170 // GIVEN calling from user 20
3171 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003172 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3173 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003174 }
3175
3176 public void testForceUpdateUserSetupComplete_userbuild() {
3177 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3178 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3179
3180 final int userId = UserHandle.USER_SYSTEM;
3181 // GIVEN userComplete is false in SettingsProvider
3182 setUserSetupCompleteForUser(false, userId);
3183
3184 // GIVEN userComplete is true in DPM
3185 DevicePolicyManagerService.DevicePolicyData userData =
3186 new DevicePolicyManagerService.DevicePolicyData(userId);
3187 userData.mUserSetupComplete = true;
3188 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3189
3190 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003191 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003192
3193 assertTrue(dpms.hasUserSetupCompleted());
3194
3195 dpm.forceUpdateUserSetupComplete();
3196
3197 // THEN the state in dpms is not changed
3198 assertTrue(dpms.hasUserSetupCompleted());
3199 }
3200
3201 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3202 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3203 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3204
3205 final int userId = UserHandle.USER_SYSTEM;
3206 // GIVEN userComplete is false in SettingsProvider
3207 setUserSetupCompleteForUser(false, userId);
3208
3209 // GIVEN userComplete is true in DPM
3210 DevicePolicyManagerService.DevicePolicyData userData =
3211 new DevicePolicyManagerService.DevicePolicyData(userId);
3212 userData.mUserSetupComplete = true;
3213 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3214
3215 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003216 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003217
3218 assertTrue(dpms.hasUserSetupCompleted());
3219
3220 dpm.forceUpdateUserSetupComplete();
3221
3222 // THEN the state in dpms is not changed
3223 assertFalse(dpms.hasUserSetupCompleted());
3224 }
3225
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003226 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003227 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003228 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003229
3230 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3231 runAsCaller(mAdmin1Context, dpms, dpm -> {
3232 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3233 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003234 }
3235
3236 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3237 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3238 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003239
3240 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3241 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003242 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003243 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3244 .thenReturn(true);
3245
3246 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003247 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003248
3249 // Enabling logging should not change the timestamp.
3250 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003251 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003252 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003253 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003254 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003255 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003256
3257 // Retrieving the logs should update the timestamp.
3258 final long beforeRetrieval = System.currentTimeMillis();
3259 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003260 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003261 final long afterRetrieval = System.currentTimeMillis();
3262 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3263 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3264
3265 // Retrieving the pre-boot logs should update the timestamp.
3266 Thread.sleep(2);
3267 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003268 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003269 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3270
3271 // Checking the timestamp again should not change it.
3272 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003273 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003274
3275 // Retrieving the logs again should update the timestamp.
3276 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003277 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003278 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3279
3280 // Disabling logging should not change the timestamp.
3281 Thread.sleep(2);
3282 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003283 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003284
3285 // Restarting the DPMS should not lose the timestamp.
3286 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003287 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003288
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003289 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3290 mContext.binder.callingUid = 1234567;
3291 mContext.callerPermissions.add(permission.MANAGE_USERS);
3292 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3293 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3294
3295 // System can retrieve the timestamp.
3296 mContext.binder.clearCallingIdentity();
3297 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3298
3299 // Removing the device owner should clear the timestamp.
3300 clearDeviceOwner();
3301 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003302 }
3303
yuemingw0de748d2017-11-15 19:22:27 +00003304 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3305 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3306 setupDeviceOwner();
3307 assertExpectException(SecurityException.class, null, () ->
3308 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3309 }
3310
3311 public void testSetSystemSettingFailWithPO() throws Exception {
3312 setupProfileOwner();
3313 assertExpectException(SecurityException.class, null, () ->
3314 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"));
3315 }
3316
3317 public void testSetSystemSetting() throws Exception {
3318 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3319 setupDeviceOwner();
3320 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3321 verify(getServices().settings).settingsSystemPutString(
3322 Settings.System.SCREEN_BRIGHTNESS, "0");
3323 }
3324
yuemingwe43cdf72017-10-12 16:52:11 +01003325 public void testSetTime() throws Exception {
3326 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3327 setupDeviceOwner();
3328 dpm.setTime(admin1, 0);
3329 verify(getServices().alarmManager).setTime(0);
3330 }
3331
3332 public void testSetTimeFailWithPO() throws Exception {
3333 setupProfileOwner();
3334 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3335 }
3336
3337 public void testSetTimeWithAutoTimeOn() throws Exception {
3338 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3339 setupDeviceOwner();
3340 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3341 .thenReturn(1);
3342 assertFalse(dpm.setTime(admin1, 0));
3343 }
3344
3345 public void testSetTimeZone() throws Exception {
3346 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3347 setupDeviceOwner();
3348 dpm.setTimeZone(admin1, "Asia/Shanghai");
3349 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3350 }
3351
3352 public void testSetTimeZoneFailWithPO() throws Exception {
3353 setupProfileOwner();
3354 assertExpectException(SecurityException.class, null,
3355 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3356 }
3357
3358 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3359 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3360 setupDeviceOwner();
3361 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3362 .thenReturn(1);
3363 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3364 }
3365
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003366 public void testGetLastBugReportRequestTime() throws Exception {
3367 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3368 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003369
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003370 mContext.packageName = admin1.getPackageName();
3371 mContext.applicationInfo = new ApplicationInfo();
3372 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3373 .thenReturn(Color.WHITE);
3374 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3375 anyObject())).thenReturn(Color.WHITE);
3376
Esteban Talaverad36dd152016-12-15 08:51:45 +00003377 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3378 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003379 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003380
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003381 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003382 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003383
3384 // Requesting a bug report should update the timestamp.
3385 final long beforeRequest = System.currentTimeMillis();
3386 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003387 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003388 final long afterRequest = System.currentTimeMillis();
3389 assertTrue(bugReportRequestTime >= beforeRequest);
3390 assertTrue(bugReportRequestTime <= afterRequest);
3391
3392 // Checking the timestamp again should not change it.
3393 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003394 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003395
3396 // Restarting the DPMS should not lose the timestamp.
3397 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003398 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003399
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003400 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3401 mContext.binder.callingUid = 1234567;
3402 mContext.callerPermissions.add(permission.MANAGE_USERS);
3403 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3404 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3405
3406 // System can retrieve the timestamp.
3407 mContext.binder.clearCallingIdentity();
3408 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3409
3410 // Removing the device owner should clear the timestamp.
3411 clearDeviceOwner();
3412 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003413 }
3414
3415 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3416 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3417 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003418 mContext.packageName = admin1.getPackageName();
3419 mContext.applicationInfo = new ApplicationInfo();
3420 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3421 .thenReturn(Color.WHITE);
3422 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3423 anyObject())).thenReturn(Color.WHITE);
3424
3425 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3426 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003427 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003428 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003429 .thenReturn(true);
3430
3431 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003432 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003433
3434 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3435 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003436 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003437
3438 // Enabling logging should not change the timestamp.
3439 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003440 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003441
3442 // Retrieving the logs should update the timestamp.
3443 final long beforeRetrieval = System.currentTimeMillis();
3444 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003445 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003446 final long afterRetrieval = System.currentTimeMillis();
3447 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3448 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3449
3450 // Checking the timestamp again should not change it.
3451 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003452 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003453
3454 // Retrieving the logs again should update the timestamp.
3455 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003456 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003457 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3458
3459 // Disabling logging should not change the timestamp.
3460 Thread.sleep(2);
3461 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003462 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003463
3464 // Restarting the DPMS should not lose the timestamp.
3465 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003466 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3467
3468 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3469 mContext.binder.callingUid = 1234567;
3470 mContext.callerPermissions.add(permission.MANAGE_USERS);
3471 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3472 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3473
3474 // System can retrieve the timestamp.
3475 mContext.binder.clearCallingIdentity();
3476 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3477
3478 // Removing the device owner should clear the timestamp.
3479 clearDeviceOwner();
3480 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003481 }
3482
Tony Mak2f26b792016-11-28 17:54:51 +00003483 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3484 // Setup device owner.
3485 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3486 setupDeviceOwner();
3487
3488 // Only device owner is setup, the result list should be empty.
3489 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3490 MoreAsserts.assertEmpty(targetUsers);
3491
3492 // Setup a managed profile managed by the same admin.
3493 final int MANAGED_PROFILE_USER_ID = 15;
3494 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3495 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3496
3497 // Add a secondary user, it should never talk with.
3498 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003499 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003500
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003501 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3502 // other.
3503 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3504 MoreAsserts.assertEmpty(targetUsers);
3505
3506 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3507 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3508 MoreAsserts.assertEmpty(targetUsers);
3509
3510 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003511 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003512 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3513 dpm.setAffiliationIds(admin1, userAffiliationIds);
3514
3515 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3516 dpm.setAffiliationIds(admin1, userAffiliationIds);
3517
Tony Mak2f26b792016-11-28 17:54:51 +00003518 // Calling from device owner admin, the result list should just contain the managed
3519 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003520 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003521 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3522 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3523
3524 // Calling from managed profile admin, the result list should just contain the system
3525 // user id.
3526 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3527 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3528 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003529
3530 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003531 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003532
3533 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3534 // to each other.
3535 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3536 MoreAsserts.assertEmpty(targetUsers);
3537
3538 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3539 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3540 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003541 }
3542
3543 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3544 // Setup a device owner.
3545 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3546 setupDeviceOwner();
3547
3548 // Set up a managed profile managed by different package.
3549 final int MANAGED_PROFILE_USER_ID = 15;
3550 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3551 final ComponentName adminDifferentPackage =
3552 new ComponentName("another.package", "whatever.class");
3553 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3554
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003555 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003556 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003557 dpm.setAffiliationIds(admin1, userAffiliationIds);
3558
3559 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3560 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3561
Tony Mak2f26b792016-11-28 17:54:51 +00003562 // Calling from device owner admin, we should get zero bind device admin target users as
3563 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003564 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003565 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3566 MoreAsserts.assertEmpty(targetUsers);
3567
3568 // Calling from managed profile admin, we should still get zero target users for the same
3569 // reason.
3570 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3571 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3572 MoreAsserts.assertEmpty(targetUsers);
3573 }
3574
Charles Hee078db72017-10-19 18:03:20 +01003575 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003576 // Setup a device owner.
3577 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3578 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003579 // Lock task policy is updated when loading user data.
3580 verify(getServices().iactivityManager).updateLockTaskPackages(
3581 UserHandle.USER_SYSTEM, new String[0]);
3582 verify(getServices().iactivityManager).updateLockTaskFeatures(
3583 UserHandle.USER_SYSTEM, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003584
3585 // Set up a managed profile managed by different package (package name shouldn't matter)
3586 final int MANAGED_PROFILE_USER_ID = 15;
3587 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3588 final ComponentName adminDifferentPackage =
3589 new ComponentName("another.package", "whatever.class");
3590 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Charles Hee078db72017-10-19 18:03:20 +01003591 verify(getServices().iactivityManager).updateLockTaskPackages(
3592 MANAGED_PROFILE_USER_ID, new String[0]);
3593 verify(getServices().iactivityManager).updateLockTaskFeatures(
3594 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003595
3596 // The DO can still set lock task packages
3597 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3598 final String[] doPackages = {"doPackage1", "doPackage2"};
3599 dpm.setLockTaskPackages(admin1, doPackages);
3600 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3601 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3602 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Charles Hee078db72017-10-19 18:03:20 +01003603 verify(getServices().iactivityManager).updateLockTaskPackages(
3604 UserHandle.USER_SYSTEM, doPackages);
3605 // And the DO can still set lock task features
3606 final int doFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3607 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3608 dpm.setLockTaskFeatures(admin1, doFlags);
3609 verify(getServices().iactivityManager).updateLockTaskFeatures(
3610 UserHandle.USER_SYSTEM, doFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003611
3612 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3613 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3614 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003615 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3616 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3617 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3618 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003619 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
Charles Hee078db72017-10-19 18:03:20 +01003620 // And it shouldn't be able to setLockTaskFeatures.
3621 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3622 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3623 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3624 () -> dpm.setLockTaskFeatures(adminDifferentPackage, poFlags));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003625
3626 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003627 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003628 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3629 dpm.setAffiliationIds(admin1, userAffiliationIds);
3630
3631 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3632 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3633
3634 // Now the managed profile can set lock task packages.
3635 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3636 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3637 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3638 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003639 verify(getServices().iactivityManager).updateLockTaskPackages(
3640 MANAGED_PROFILE_USER_ID, poPackages);
3641 // And it can set lock task features.
3642 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
3643 verify(getServices().iactivityManager).updateLockTaskFeatures(
3644 MANAGED_PROFILE_USER_ID, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003645
3646 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003647 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003648 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3649 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003650 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3651 MANAGED_PROFILE_USER_ID, new String[0]);
3652 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3653 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003654
3655 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3656 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3657 }
3658
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003659 public void testIsDeviceManaged() throws Exception {
3660 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3661 setupDeviceOwner();
3662
3663 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3664 // find out that the device has a device owner.
3665 assertTrue(dpm.isDeviceManaged());
3666 mContext.binder.callingUid = 1234567;
3667 mContext.callerPermissions.add(permission.MANAGE_USERS);
3668 assertTrue(dpm.isDeviceManaged());
3669 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3670 mContext.binder.clearCallingIdentity();
3671 assertTrue(dpm.isDeviceManaged());
3672
3673 clearDeviceOwner();
3674
3675 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3676 // not have a device owner.
3677 mContext.binder.callingUid = 1234567;
3678 mContext.callerPermissions.add(permission.MANAGE_USERS);
3679 assertFalse(dpm.isDeviceManaged());
3680 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3681 mContext.binder.clearCallingIdentity();
3682 assertFalse(dpm.isDeviceManaged());
3683 }
3684
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003685 public void testDeviceOwnerOrganizationName() throws Exception {
3686 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3687 setupDeviceOwner();
3688
3689 dpm.setOrganizationName(admin1, "organization");
3690
3691 // Device owner can retrieve organization managing the device.
3692 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3693
3694 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3695 mContext.binder.callingUid = 1234567;
3696 mContext.callerPermissions.add(permission.MANAGE_USERS);
3697 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3698 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3699
3700 // System can retrieve organization managing the device.
3701 mContext.binder.clearCallingIdentity();
3702 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3703
3704 // Removing the device owner clears the organization managing the device.
3705 clearDeviceOwner();
3706 assertNull(dpm.getDeviceOwnerOrganizationName());
3707 }
3708
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003709 public void testWipeDataManagedProfile() throws Exception {
3710 final int MANAGED_PROFILE_USER_ID = 15;
3711 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3712 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3713 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3714
3715 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003716 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003717 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003718 // Get mock reason string since we throw an IAE with empty string input.
3719 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3720 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003721
3722 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003723 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003724 MANAGED_PROFILE_USER_ID);
3725 }
3726
3727 public void testWipeDataManagedProfileDisallowed() throws Exception {
3728 final int MANAGED_PROFILE_USER_ID = 15;
3729 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3730 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3731
3732 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003733 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003734 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3735
Pavel Grafov75c0a892017-05-18 17:28:27 +01003736 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003737 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3738 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3739 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003740 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3741 thenReturn("Just a test string.");
3742
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003743 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003744 // The PO is not allowed to remove the profile if the user restriction was set on the
3745 // profile by the system
3746 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3747 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003748 }
3749
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003750 public void testWipeDataDeviceOwner() throws Exception {
3751 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003752 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003753 UserManager.DISALLOW_FACTORY_RESET,
3754 UserHandle.SYSTEM))
3755 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003756 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3757 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003758
3759 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003760 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003761 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3762 /*wipeEuicc=*/ eq(false));
3763 }
3764
3765 public void testWipeEuiccDataEnabled() throws Exception {
3766 setDeviceOwner();
3767 when(getServices().userManager.getUserRestrictionSource(
3768 UserManager.DISALLOW_FACTORY_RESET,
3769 UserHandle.SYSTEM))
3770 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003771 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3772 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003773
3774 dpm.wipeData(WIPE_EUICC);
3775 verify(getServices().recoverySystem).rebootWipeUserData(
3776 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3777 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003778 }
3779
3780 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3781 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003782 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003783 UserManager.DISALLOW_FACTORY_RESET,
3784 UserHandle.SYSTEM))
3785 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003786 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3787 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003788 // The DO is not allowed to wipe the device if the user restriction was set
3789 // by the system
3790 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3791 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003792 }
3793
3794 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3795 final int MANAGED_PROFILE_USER_ID = 15;
3796 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3797 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3798
3799 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003800 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003801 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3802
Pavel Grafov75c0a892017-05-18 17:28:27 +01003803 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003804 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3805 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3806 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3807
3808 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3809 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3810
3811 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3812 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3813 // Failed password attempts on the parent user are taken into account, as there isn't a
3814 // separate work challenge.
3815 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3816 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3817 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3818
3819 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3820 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003821 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003822 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003823 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003824 }
3825
3826 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3827 throws Exception {
3828 final int MANAGED_PROFILE_USER_ID = 15;
3829 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3830 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3831
3832 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003833 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003834 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3835
Pavel Grafov75c0a892017-05-18 17:28:27 +01003836 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003837 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3838 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3839 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3840
3841 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3842 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3843
3844 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3845 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3846 // Failed password attempts on the parent user are taken into account, as there isn't a
3847 // separate work challenge.
3848 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3849 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3850 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3851
3852 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3853 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003854 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003855 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003856 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003857 }
3858
3859 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3860 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003861 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003862 UserManager.DISALLOW_FACTORY_RESET,
3863 UserHandle.SYSTEM))
3864 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3865
3866 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3867
3868 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3869 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3870 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3871 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3872 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3873
3874 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3875 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003876 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003877 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3878 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003879 }
3880
3881 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3882 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003883 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003884 UserManager.DISALLOW_FACTORY_RESET,
3885 UserHandle.SYSTEM))
3886 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3887
3888 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3889
3890 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3891 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3892 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3893 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3894 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3895
3896 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003897 verifyZeroInteractions(getServices().recoverySystem);
3898 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003899 .removeUserEvenWhenDisallowed(anyInt());
3900 }
3901
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003902 public void testGetPermissionGrantState() throws Exception {
3903 final String permission = "some.permission";
3904 final String app1 = "com.example.app1";
3905 final String app2 = "com.example.app2";
3906
Pavel Grafov75c0a892017-05-18 17:28:27 +01003907 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003908 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003909 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003910 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003911 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003912 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3913 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003914 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003915 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003916 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003917 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003918 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003919 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3920
3921 // System can retrieve permission grant state.
3922 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003923 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003924 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3925 dpm.getPermissionGrantState(null, app1, permission));
3926 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3927 dpm.getPermissionGrantState(null, app2, permission));
3928
3929 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003930 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3931 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003932 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3933 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003934
3935 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003936 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3937 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003938 setAsProfileOwner(admin1);
3939 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3940 dpm.getPermissionGrantState(admin1, app1, permission));
3941 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3942 dpm.getPermissionGrantState(admin1, app2, permission));
3943 }
3944
Rubin Xuaab7a412016-12-30 21:13:29 +00003945 public void testResetPasswordWithToken() throws Exception {
3946 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3947 setupDeviceOwner();
3948 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003949 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3950 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3951
Rubin Xuaab7a412016-12-30 21:13:29 +00003952 // test adding a token
3953 final byte[] token = new byte[32];
3954 final long handle = 123456;
3955 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003956 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003957 .thenReturn(handle);
3958 assertTrue(dpm.setResetPasswordToken(admin1, token));
3959
3960 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003961 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003962 .thenReturn(true);
3963 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3964
3965 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003966 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01003967 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
3968 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00003969 eq(UserHandle.USER_SYSTEM)))
3970 .thenReturn(true);
3971 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3972
3973 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003974 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003975 .thenReturn(true);
3976 assertTrue(dpm.clearResetPasswordToken(admin1));
3977 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003978
Alexandru-Andrei Rotaru7f31bb02017-09-07 16:29:48 +01003979 public void testSetPasswordBlacklistCannotBeCalledByNonAdmin() throws Exception {
3980 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3981 () -> dpm.setPasswordBlacklist(admin1, null, null));
3982 verifyZeroInteractions(getServices().passwordBlacklist);
3983 }
3984
3985 public void testClearingPasswordBlacklistDoesNotCreateNewBlacklist() throws Exception {
3986 setupProfileOwner();
3987 dpm.setPasswordBlacklist(admin1, null, null);
3988 verifyZeroInteractions(getServices().passwordBlacklist);
3989 }
3990
3991 public void testSetPasswordBlacklistCreatesNewBlacklist() throws Exception {
3992 final String name = "myblacklist";
3993 final List<String> explicit = Arrays.asList("password", "letmein");
3994 setupProfileOwner();
3995 dpm.setPasswordBlacklist(admin1, name, explicit);
3996 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, explicit);
3997 }
3998
3999 public void testSetPasswordBlacklistOnlyConvertsExplicitToLowerCase() throws Exception {
4000 final List<String> mixedCase = Arrays.asList("password", "LETMEIN", "FooTBAll");
4001 final List<String> lowerCase = Arrays.asList("password", "letmein", "football");
4002 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4003 setupDeviceOwner();
4004 final String name = "Name of the Blacklist";
4005 dpm.setPasswordBlacklist(admin1, name, mixedCase);
4006 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, lowerCase);
4007 }
4008
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004009 public void testIsActivePasswordSufficient() throws Exception {
4010 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4011 mContext.packageName = admin1.getPackageName();
4012 setupDeviceOwner();
4013
4014 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4015 dpm.setPasswordMinimumLength(admin1, 8);
4016 dpm.setPasswordMinimumLetters(admin1, 6);
4017 dpm.setPasswordMinimumLowerCase(admin1, 3);
4018 dpm.setPasswordMinimumUpperCase(admin1, 1);
4019 dpm.setPasswordMinimumNonLetter(admin1, 1);
4020 dpm.setPasswordMinimumNumeric(admin1, 1);
4021 dpm.setPasswordMinimumSymbols(admin1, 0);
4022
4023 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4024 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4025 8, 2,
4026 6, 1,
4027 0, 1);
4028
4029 setActivePasswordState(passwordMetricsNoSymbols);
4030 assertTrue(dpm.isActivePasswordSufficient());
4031
4032 initializeDpms();
4033 reset(mContext.spiedContext);
4034 assertTrue(dpm.isActivePasswordSufficient());
4035
4036 // This call simulates the user entering the password for the first time after a reboot.
4037 // This causes password metrics to be reloaded into memory. Until this happens,
4038 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4039 // even if the DPC changes password requirements so that the password no longer meets the
4040 // requirements. This is a known limitation of the current implementation of
4041 // isActivePasswordSufficient() - see b/34218769.
4042 setActivePasswordState(passwordMetricsNoSymbols);
4043 assertTrue(dpm.isActivePasswordSufficient());
4044
4045 dpm.setPasswordMinimumSymbols(admin1, 1);
4046 // This assertion would fail if we had not called setActivePasswordState() again after
4047 // initializeDpms() - see previous comment.
4048 assertFalse(dpm.isActivePasswordSufficient());
4049
4050 initializeDpms();
4051 reset(mContext.spiedContext);
4052 assertFalse(dpm.isActivePasswordSufficient());
4053
4054 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4055 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4056 7, 2,
4057 5, 1,
4058 1, 2);
4059
4060 setActivePasswordState(passwordMetricsWithSymbols);
4061 assertTrue(dpm.isActivePasswordSufficient());
4062 }
4063
Pavel Grafov75c0a892017-05-18 17:28:27 +01004064 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4065 throws Exception {
4066 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004067 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004068
Pavel Grafov75c0a892017-05-18 17:28:27 +01004069 dpm.setActivePasswordState(passwordMetrics, userHandle);
4070 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004071
Pavel Grafov75c0a892017-05-18 17:28:27 +01004072 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4073 intent.setComponent(admin1);
4074 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
4075
4076 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4077 MockUtils.checkIntent(intent),
4078 MockUtils.checkUserHandle(userHandle));
4079
4080 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4081 // let it finish with system uid, otherwise it will throw and crash.
4082 flushTasks();
4083
4084 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004085 }
4086
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004087 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4088 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4089 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4090 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4091 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4092 DpmMockContext.SYSTEM_UID);
4093 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4094 DpmMockContext.SYSTEM_UID);
4095
4096 // Set up a device owner.
4097 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004098 setupDeviceOwner();
4099
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004100 // First and second user set IMEs manually.
4101 mContext.binder.callingUid = firstUserSystemUid;
4102 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4103 mContext.binder.callingUid = secondUserSystemUid;
4104 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004105
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004106 // Device owner changes IME for first user.
4107 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004108 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004109 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004110 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004111 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004112 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004113 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004114 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4115 mContext.binder.callingUid = firstUserSystemUid;
4116 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4117 mContext.binder.callingUid = secondUserSystemUid;
4118 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004119
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004120 // Second user changes IME manually.
4121 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4122 mContext.binder.callingUid = firstUserSystemUid;
4123 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4124 mContext.binder.callingUid = secondUserSystemUid;
4125 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004126
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004127 // First user changes IME manually.
4128 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4129 mContext.binder.callingUid = firstUserSystemUid;
4130 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4131 mContext.binder.callingUid = secondUserSystemUid;
4132 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004133
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004134 // Device owner changes IME for first user again.
4135 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004136 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004137 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004138 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004139 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004140 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004141 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4142 mContext.binder.callingUid = firstUserSystemUid;
4143 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4144 mContext.binder.callingUid = secondUserSystemUid;
4145 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004146
4147 // Restarting the DPMS should not lose information.
4148 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004149 mContext.binder.callingUid = firstUserSystemUid;
4150 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4151 mContext.binder.callingUid = secondUserSystemUid;
4152 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004153
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004154 // Device owner can find out whether it set the current IME itself.
4155 mContext.binder.callingUid = deviceOwnerUid;
4156 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004157
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004158 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004159 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004160 mContext.binder.callingUid = firstUserSystemUid;
4161 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4162 mContext.binder.callingUid = secondUserSystemUid;
4163 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004164 }
4165
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004166 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4167 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4168 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4169 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4170 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4171 DpmMockContext.SYSTEM_UID);
4172 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4173 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004174
4175 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004176 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004177 setupProfileOwner();
4178
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004179 // First and second user set IMEs manually.
4180 mContext.binder.callingUid = firstUserSystemUid;
4181 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4182 mContext.binder.callingUid = secondUserSystemUid;
4183 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004184
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004185 // Profile owner changes IME for second user.
4186 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004187 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004188 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004189 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004190 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004191 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004192 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004193 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4194 mContext.binder.callingUid = firstUserSystemUid;
4195 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4196 mContext.binder.callingUid = secondUserSystemUid;
4197 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004198
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004199 // First user changes IME manually.
4200 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4201 mContext.binder.callingUid = firstUserSystemUid;
4202 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4203 mContext.binder.callingUid = secondUserSystemUid;
4204 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004205
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004206 // Second user changes IME manually.
4207 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4208 mContext.binder.callingUid = firstUserSystemUid;
4209 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4210 mContext.binder.callingUid = secondUserSystemUid;
4211 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004212
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004213 // Profile owner changes IME for second user again.
4214 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004215 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004216 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004217 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004218 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004219 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004220 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4221 mContext.binder.callingUid = firstUserSystemUid;
4222 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4223 mContext.binder.callingUid = secondUserSystemUid;
4224 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004225
4226 // Restarting the DPMS should not lose information.
4227 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004228 mContext.binder.callingUid = firstUserSystemUid;
4229 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4230 mContext.binder.callingUid = secondUserSystemUid;
4231 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004232
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004233 // Profile owner can find out whether it set the current IME itself.
4234 mContext.binder.callingUid = profileOwnerUid;
4235 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004236
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004237 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004238 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004239 mContext.binder.callingUid = firstUserSystemUid;
4240 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4241 mContext.binder.callingUid = secondUserSystemUid;
4242 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004243 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004244
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004245 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4246 throws Exception {
4247 // Set up a device owner.
4248 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4249 setupDeviceOwner();
4250 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4251 }
4252
4253 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4254 throws Exception {
4255 // Set up a profile owner.
4256 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4257 setupProfileOwner();
4258 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4259 }
4260
4261 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4262 int adminUid) throws Exception {
4263 mContext.binder.callingUid = adminUid;
4264 final int userId = UserHandle.getUserId(adminUid);
4265
4266 final String packageName = "some.package";
4267 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4268 admin1, Collections.singletonList(packageName)));
4269 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4270
4271 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4272 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4273
4274 // Attempt to set to empty list (which means no listener is whitelisted)
4275 mContext.binder.callingUid = adminUid;
4276 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004277 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004278 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4279
4280 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4281 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4282 }
4283
4284 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4285 // Set up a managed profile
4286 final int MANAGED_PROFILE_USER_ID = 15;
4287 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4288 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4289 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4290
4291 final String permittedListener = "some.package";
4292 setupPackageInPackageManager(
4293 permittedListener,
4294 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4295 /*appId=*/ 12345, /*flags=*/ 0);
4296
4297 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4298 admin1, Collections.singletonList(permittedListener)));
4299
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004300 // isNotificationListenerServicePermitted should throw if not called from System.
4301 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4302 () -> dpms.isNotificationListenerServicePermitted(
4303 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004304
4305 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4306 assertTrue(dpms.isNotificationListenerServicePermitted(
4307 permittedListener, MANAGED_PROFILE_USER_ID));
4308 }
4309
4310 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4311 throws Exception {
4312 // Set up a managed profile
4313 final int MANAGED_PROFILE_USER_ID = 15;
4314 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4315 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4316 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4317
4318 final String permittedListener = "permitted.package";
4319 int appId = 12345;
4320 setupPackageInPackageManager(
4321 permittedListener,
4322 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4323 appId, /*flags=*/ 0);
4324
4325 final String notPermittedListener = "not.permitted.package";
4326 setupPackageInPackageManager(
4327 notPermittedListener,
4328 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4329 ++appId, /*flags=*/ 0);
4330
4331 final String systemListener = "system.package";
4332 setupPackageInPackageManager(
4333 systemListener,
4334 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4335 ++appId, ApplicationInfo.FLAG_SYSTEM);
4336
4337 // By default all packages are allowed
4338 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4339
4340 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4341 assertTrue(dpms.isNotificationListenerServicePermitted(
4342 permittedListener, MANAGED_PROFILE_USER_ID));
4343 assertTrue(dpms.isNotificationListenerServicePermitted(
4344 notPermittedListener, MANAGED_PROFILE_USER_ID));
4345 assertTrue(dpms.isNotificationListenerServicePermitted(
4346 systemListener, MANAGED_PROFILE_USER_ID));
4347
4348 // Setting only one package in the whitelist
4349 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4350 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4351 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004352 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004353 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4354 assertEquals(1, permittedListeners.size());
4355 assertEquals(permittedListener, permittedListeners.get(0));
4356
4357 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4358 assertTrue(dpms.isNotificationListenerServicePermitted(
4359 permittedListener, MANAGED_PROFILE_USER_ID));
4360 assertFalse(dpms.isNotificationListenerServicePermitted(
4361 notPermittedListener, MANAGED_PROFILE_USER_ID));
4362 // System packages are always allowed (even if not in the whitelist)
4363 assertTrue(dpms.isNotificationListenerServicePermitted(
4364 systemListener, MANAGED_PROFILE_USER_ID));
4365
4366 // Setting an empty whitelist - only system listeners allowed
4367 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4368 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004369 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004370 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4371
4372 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4373 assertFalse(dpms.isNotificationListenerServicePermitted(
4374 permittedListener, MANAGED_PROFILE_USER_ID));
4375 assertFalse(dpms.isNotificationListenerServicePermitted(
4376 notPermittedListener, MANAGED_PROFILE_USER_ID));
4377 // System packages are always allowed (even if not in the whitelist)
4378 assertTrue(dpms.isNotificationListenerServicePermitted(
4379 systemListener, MANAGED_PROFILE_USER_ID));
4380
4381 // Setting a null whitelist - all listeners allowed
4382 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4383 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4384 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4385
4386 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4387 assertTrue(dpms.isNotificationListenerServicePermitted(
4388 permittedListener, MANAGED_PROFILE_USER_ID));
4389 assertTrue(dpms.isNotificationListenerServicePermitted(
4390 notPermittedListener, MANAGED_PROFILE_USER_ID));
4391 assertTrue(dpms.isNotificationListenerServicePermitted(
4392 systemListener, MANAGED_PROFILE_USER_ID));
4393 }
4394
4395 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4396 throws Exception {
4397 // Set up a managed profile
4398 final int MANAGED_PROFILE_USER_ID = 15;
4399 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4400 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4401 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4402
4403 final String nonSystemPackage = "non.system.package";
4404 int appId = 12345;
4405 setupPackageInPackageManager(
4406 nonSystemPackage,
4407 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4408 appId, /*flags=*/ 0);
4409
4410 final String systemListener = "system.package";
4411 setupPackageInPackageManager(
4412 systemListener,
4413 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4414 ++appId, ApplicationInfo.FLAG_SYSTEM);
4415
4416 // By default all packages are allowed (for all profiles)
4417 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4418
4419 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4420 assertTrue(dpms.isNotificationListenerServicePermitted(
4421 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4422 assertTrue(dpms.isNotificationListenerServicePermitted(
4423 systemListener, MANAGED_PROFILE_USER_ID));
4424 assertTrue(dpms.isNotificationListenerServicePermitted(
4425 nonSystemPackage, UserHandle.USER_SYSTEM));
4426 assertTrue(dpms.isNotificationListenerServicePermitted(
4427 systemListener, UserHandle.USER_SYSTEM));
4428
4429 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4430 // all allowed in primary profile
4431 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4432 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004433 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004434 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4435
4436 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4437 assertFalse(dpms.isNotificationListenerServicePermitted(
4438 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4439 assertTrue(dpms.isNotificationListenerServicePermitted(
4440 systemListener, MANAGED_PROFILE_USER_ID));
4441 assertTrue(dpms.isNotificationListenerServicePermitted(
4442 nonSystemPackage, UserHandle.USER_SYSTEM));
4443 assertTrue(dpms.isNotificationListenerServicePermitted(
4444 systemListener, UserHandle.USER_SYSTEM));
4445 }
4446
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004447 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004448 mServiceContext.packageName = mRealTestContext.getPackageName();
4449 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4450 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004451 setDeviceOwner();
4452
Pavel Grafov75c0a892017-05-18 17:28:27 +01004453 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004454 }
4455
4456 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004457 mServiceContext.packageName = mRealTestContext.getPackageName();
4458 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4459 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004460 setAsProfileOwner(admin1);
4461
Pavel Grafov75c0a892017-05-18 17:28:27 +01004462 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4463 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004464 }
4465
4466 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004467 mServiceContext.packageName = mRealTestContext.getPackageName();
4468 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4469 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004470 setAsProfileOwner(admin1);
4471
Pavel Grafov75c0a892017-05-18 17:28:27 +01004472 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4473 caller.packageName = "com.example.delegate";
4474 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4475 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004476
Pavel Grafov75c0a892017-05-18 17:28:27 +01004477 // Make caller a delegated cert installer.
4478 runAsCaller(mAdmin1Context, dpms,
4479 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004480
4481 verifyCanGetOwnerInstalledCaCerts(null, caller);
4482 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004483 }
4484
Robin Lee2c68dad2017-03-17 12:50:24 +00004485 private void verifyCanGetOwnerInstalledCaCerts(
4486 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004487 final String alias = "cert";
4488 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004489
4490 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004491 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004492 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4493 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004494 }
4495 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4496
4497 // caller: device admin or delegated certificate installer
4498 callerContext.applicationInfo = new ApplicationInfo();
4499 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4500
4501 // system_server
4502 final DpmMockContext serviceContext = mContext;
4503 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004504 getServices().addPackageContext(callerUser, admin1Context);
4505 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004506
4507 // Install a CA cert.
4508 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004509 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004510 .thenReturn(alias);
4511 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004512 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004513 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004514 });
4515
Pavel Grafov75c0a892017-05-18 17:28:27 +01004516 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4517 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4518 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004519 flushTasks();
4520
Robin Lee2c68dad2017-03-17 12:50:24 +00004521 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4522
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004523 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004524 runAsCaller(admin1Context, dpms, (dpm) -> {
4525 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004526 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004527 ownerInstalledCaCerts.addAll(installedCaCerts);
4528 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004529
4530 // Restarting the DPMS should not lose information.
4531 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004532 runAsCaller(admin1Context, dpms, (dpm) ->
4533 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004534
4535 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004536 runAsCaller(serviceContext, dpms, (dpm) -> {
4537 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004538
Robin Lee2c68dad2017-03-17 12:50:24 +00004539 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004540 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004541 });
4542
Pavel Grafov75c0a892017-05-18 17:28:27 +01004543 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4544 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4545 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004546 flushTasks();
4547
4548 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4549 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004550 runAsCaller(admin1Context, dpms, (dpm) -> {
4551 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4552 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004553 }
4554
Robin Lee2c68dad2017-03-17 12:50:24 +00004555 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4556 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004557 final String alias = "cert";
4558 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004559
4560 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004561 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004562 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4563 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004564 }
4565 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4566
4567 // caller: device admin or delegated certificate installer
4568 callerContext.applicationInfo = new ApplicationInfo();
4569 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4570
4571 // system_server
4572 final DpmMockContext serviceContext = mContext;
4573 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004574 getServices().addPackageContext(callerUser, admin1Context);
4575 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004576
4577 // Install a CA cert as caller
4578 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004579 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004580 .thenReturn(alias);
4581 assertTrue(dpm.installCaCert(callerName, caCert));
4582 });
4583
4584 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004585 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004586 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004587 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4588 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4589 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004590 flushTasks();
4591
Robin Lee2c68dad2017-03-17 12:50:24 +00004592 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004593 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004594
4595 runAsCaller(serviceContext, dpms, (dpm) -> {
4596 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4597 assertNotNull(ownerInstalledCaCerts);
4598 assertTrue(ownerInstalledCaCerts.isEmpty());
4599 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004600 }
4601
Eran Messeri94d56762017-12-21 20:50:54 +00004602 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4603 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4604 Arrays.sort(gotFlags);
4605 Arrays.sort(expectedFlags);
4606 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4607 }
4608
4609 public void testTranslationOfIdAttestationFlag() {
4610 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4611 int[] correspondingAttUtilsTypes = new int[]{
4612 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4613 AttestationUtils.ID_TYPE_MEID};
4614
4615 // Test translation of zero flags
4616 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4617
4618 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4619 // non-null array
4620 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4621
4622 // Test translation of a single flag
4623 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4624 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4625 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4626
4627 // Test translation of two flags
4628 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4629 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4630 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4631 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4632
4633 // Test translation of all three flags
4634 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4635 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4636 AttestationUtils.ID_TYPE_MEID});
4637 // Test translation of all three flags
4638 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4639 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4640 AttestationUtils.ID_TYPE_MEID});
4641 }
4642
Victor Chang3e794af2016-03-04 13:48:17 +00004643 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004644 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004645 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4646 dpms.notifyChangeToContentObserver(
4647 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4648 }
4649
4650 private void assertProvisioningAllowed(String action, boolean expected) {
4651 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4652 dpm.isProvisioningAllowed(action));
4653 }
Tony Mak2f26b792016-11-28 17:54:51 +00004654
Nicolas Prevot45d29072017-01-18 16:11:19 +00004655 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4656 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004657 final String previousPackageName = mContext.packageName;
4658 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004659
4660 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4661 mContext.packageName = packageName;
4662 mMockContext.binder.callingUid = uid;
4663 assertProvisioningAllowed(action, expected);
4664
4665 // Set the previous package name / calling uid to go back to the initial state.
4666 mContext.packageName = previousPackageName;
4667 mMockContext.binder.callingUid = previousUid;
4668 }
4669
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004670 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004671 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4672 }
4673
4674 private void assertCheckProvisioningPreCondition(
4675 String action, String packageName, int provisioningCondition) {
4676 assertEquals("checkProvisioningPreCondition("
4677 + action + ", " + packageName + ") returning unexpected result",
4678 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004679 }
4680
Tony Mak2f26b792016-11-28 17:54:51 +00004681 /**
4682 * Setup a managed profile with the specified admin and its uid.
4683 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4684 * @param adminUid uid of the admin package.
4685 * @param copyFromAdmin package information for {@code admin} will be built based on this
4686 * component's information.
4687 */
4688 private void addManagedProfile(
4689 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4690 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004691 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004692 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4693 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4694 dpm.setActiveAdmin(admin, false, userId);
4695 assertTrue(dpm.setProfileOwner(admin, null, userId));
4696 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4697 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004698
4699 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004700 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004701 */
Robin Leeabaa0692017-02-20 20:54:22 +00004702 private static StringParceledListSlice asSlice(String[] s) {
4703 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004704 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004705
4706 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004707 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4708 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004709
Robin Lee2c68dad2017-03-17 12:50:24 +00004710 // We can't let exceptions happen on the background thread. Throw them here if they happen
4711 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004712 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004713 }
Victor Chang3e794af2016-03-04 13:48:17 +00004714}