blob: 88fb992a6855e2be44f06a8593c61ddd79127781 [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;
Pavel Grafov6a40f092016-10-25 15:46:51 +010020import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
21import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
22import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
23
Pavel Grafov75c0a892017-05-18 17:28:27 +010024import static org.mockito.Matchers.any;
25import static org.mockito.Matchers.anyInt;
26import static org.mockito.Matchers.anyLong;
27import static org.mockito.Matchers.anyObject;
28import static org.mockito.Matchers.anyString;
29import static org.mockito.Matchers.eq;
30import static org.mockito.Matchers.isNull;
31import static org.mockito.Mockito.atLeast;
32import static org.mockito.Mockito.doAnswer;
33import static org.mockito.Mockito.doReturn;
34import static org.mockito.Mockito.never;
35import static org.mockito.Mockito.nullable;
36import static org.mockito.Mockito.reset;
37import static org.mockito.Mockito.timeout;
38import static org.mockito.Mockito.times;
39import static org.mockito.Mockito.verify;
40import static org.mockito.Mockito.verifyZeroInteractions;
41import static org.mockito.Mockito.when;
42import static org.mockito.hamcrest.MockitoHamcrest.argThat;
43
Makoto Onukif76b06a2015-09-22 15:03:44 -070044import android.Manifest.permission;
45import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000046import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070047import android.app.admin.DeviceAdminReceiver;
48import android.app.admin.DevicePolicyManager;
49import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010050import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070051import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070052import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000053import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000054import android.content.pm.ApplicationInfo;
55import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070056import android.content.pm.PackageManager;
Robin Leeabaa0692017-02-20 20:54:22 +000057import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000058import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010059import android.graphics.Color;
60import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080061import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080062import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070063import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080064import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070065import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070066import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080067import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010068import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000069import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080070import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000071import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010072import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070073import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070074
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010075import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000076import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000077import com.android.server.LocalServices;
78import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000079import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000080
Robin Lee7f5c91c2017-02-08 21:27:02 +000081import org.hamcrest.BaseMatcher;
82import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070083import org.mockito.invocation.InvocationOnMock;
84import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070085
Makoto Onukic8a5a552015-11-19 14:29:12 -080086import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000087import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000088import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070089import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070090import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070091import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010092import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000093import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070094
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070096 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +000097 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098 m FrameworksServicesTests &&
99 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000100 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700101 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800102 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103
104 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000105 *
106 * , or:
107 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000109@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700110public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000111 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
112 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
113 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
114
Pavel Grafov75c0a892017-05-18 17:28:27 +0100115 // TODO replace all instances of this with explicit {@link #mServiceContext}.
116 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100118
119 private DpmMockContext mServiceContext;
120 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 public DevicePolicyManager dpm;
122 public DevicePolicyManagerServiceTestable dpms;
123
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100124 /*
125 * The CA cert below is the content of cacert.pem as generated by:
126 *
127 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
128 */
129 private static final String TEST_CA =
130 "-----BEGIN CERTIFICATE-----\n" +
131 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
132 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
133 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
134 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
135 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
136 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
137 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
138 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
139 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
140 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
141 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
142 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
143 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
144 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
145 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
146 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
147 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
148 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
149 "wQ==\n" +
150 "-----END CERTIFICATE-----\n";
151
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700152 @Override
153 protected void setUp() throws Exception {
154 super.setUp();
155
156 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100157 mServiceContext = mContext;
158 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
159 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700160 .thenReturn(true);
161
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800162 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100163 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800164
Makoto Onukia52562c2015-10-01 16:12:31 -0700165 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700166
Makoto Onukid932f762015-09-29 16:53:38 -0700167 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
168 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
169 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800170 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700171
Pavel Grafov75c0a892017-05-18 17:28:27 +0100172 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
173 mAdmin1Context.packageName = admin1.getPackageName();
174 mAdmin1Context.applicationInfo = new ApplicationInfo();
175 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
176
Makoto Onukib643fb02015-09-22 15:03:44 -0700177 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700178 }
179
Robin Lee2c68dad2017-03-17 12:50:24 +0000180 @Override
181 protected void tearDown() throws Exception {
182 flushTasks();
183 super.tearDown();
184 }
185
Makoto Onukia52562c2015-10-01 16:12:31 -0700186 private void initializeDpms() {
187 // Need clearCallingIdentity() to pass permission checks.
188 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100189 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700190
Pavel Grafov75c0a892017-05-18 17:28:27 +0100191 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
192 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
193 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700194
Pavel Grafov75c0a892017-05-18 17:28:27 +0100195 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700196
Pavel Grafov75c0a892017-05-18 17:28:27 +0100197 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700198 }
199
Makoto Onukib643fb02015-09-22 15:03:44 -0700200 private void setUpUserManager() {
201 // Emulate UserManager.set/getApplicationRestriction().
202 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
203
204 // UM.setApplicationRestrictions() will save to appRestrictions.
205 doAnswer(new Answer<Void>() {
206 @Override
207 public Void answer(InvocationOnMock invocation) throws Throwable {
208 String pkg = (String) invocation.getArguments()[0];
209 Bundle bundle = (Bundle) invocation.getArguments()[1];
210 UserHandle user = (UserHandle) invocation.getArguments()[2];
211
212 appRestrictions.put(Pair.create(pkg, user), bundle);
213
214 return null;
215 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100216 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100217 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700218
219 // UM.getApplicationRestrictions() will read from appRestrictions.
220 doAnswer(new Answer<Bundle>() {
221 @Override
222 public Bundle answer(InvocationOnMock invocation) throws Throwable {
223 String pkg = (String) invocation.getArguments()[0];
224 UserHandle user = (UserHandle) invocation.getArguments()[1];
225
226 return appRestrictions.get(Pair.create(pkg, user));
227 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100228 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700229 anyString(), any(UserHandle.class));
230
Makoto Onukid932f762015-09-29 16:53:38 -0700231 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100232 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700233 }
234
235 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100236 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700237
Pavel Grafov75c0a892017-05-18 17:28:27 +0100238 mServiceContext.binder.callingUid =
239 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
240 runAsCaller(mServiceContext, dpms, dpm -> {
241 // PO needs to be a DA.
242 dpm.setActiveAdmin(admin, /*replace=*/ false);
243 // Fire!
244 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
245 // Check
246 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
247 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700248
Pavel Grafov75c0a892017-05-18 17:28:27 +0100249 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700250 }
251
252 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100253 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700254 .thenReturn(false);
255
256 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100257 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700258
259 // If the device has no DPMS feature, it shouldn't register the local service.
260 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
261 }
262
263 /**
264 * Caller doesn't have proper permissions.
265 */
266 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700267 // 1. Failure cases.
268
269 // Caller doesn't have MANAGE_DEVICE_ADMINS.
270 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700271 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700272 fail("Didn't throw SecurityException");
273 } catch (SecurityException expected) {
274 }
275
276 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
277 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
278 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700279 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700280 fail("Didn't throw SecurityException");
281 } catch (SecurityException expected) {
282 }
283 }
284
Makoto Onukif76b06a2015-09-22 15:03:44 -0700285 /**
286 * Test for:
287 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800288 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700289 * {@link DevicePolicyManager#isAdminActive}
290 * {@link DevicePolicyManager#isAdminActiveAsUser}
291 * {@link DevicePolicyManager#getActiveAdmins}
292 * {@link DevicePolicyManager#getActiveAdminsAsUser}
293 */
294 public void testSetActiveAdmin() throws Exception {
295 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700296 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
297
Makoto Onukif76b06a2015-09-22 15:03:44 -0700298 // 2. Call the API.
299 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700300
301 // 3. Verify internal calls.
302
303 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700304 verify(mContext.spiedContext).sendBroadcastAsUser(
305 MockUtils.checkIntentAction(
306 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
307 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
308 verify(mContext.spiedContext).sendBroadcastAsUser(
309 MockUtils.checkIntentAction(
310 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700311 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
312
Pavel Grafov75c0a892017-05-18 17:28:27 +0100313 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700314 eq(admin1.getPackageName()),
315 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
316 eq(PackageManager.DONT_KILL_APP),
317 eq(DpmMockContext.CALLER_USER_HANDLE),
318 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700319
320 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700321
322 // Make sure it's active admin1.
323 assertTrue(dpm.isAdminActive(admin1));
324 assertFalse(dpm.isAdminActive(admin2));
325 assertFalse(dpm.isAdminActive(admin3));
326
327 // But not admin1 for a different user.
328
329 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
330 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
331 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
332
333 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
334 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
335
336 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
337
338 // Next, add one more admin.
339 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700340 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
341 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700342
343 dpm.setActiveAdmin(admin2, /* replace =*/ false);
344
345 // Now we have two admins.
346 assertTrue(dpm.isAdminActive(admin1));
347 assertTrue(dpm.isAdminActive(admin2));
348 assertFalse(dpm.isAdminActive(admin3));
349
350 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
351 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100352 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700353 eq(admin1.getPackageName()),
354 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
355 eq(PackageManager.DONT_KILL_APP),
356 eq(DpmMockContext.CALLER_USER_HANDLE),
357 anyString());
358
359 // 4. Add the same admin1 again without replace, which should throw.
360 try {
361 dpm.setActiveAdmin(admin1, /* replace =*/ false);
362 fail("Didn't throw");
363 } catch (IllegalArgumentException expected) {
364 }
365
366 // 5. Add the same admin1 again with replace, which should succeed.
367 dpm.setActiveAdmin(admin1, /* replace =*/ true);
368
369 // TODO make sure it's replaced.
370
371 // 6. Test getActiveAdmins()
372 List<ComponentName> admins = dpm.getActiveAdmins();
373 assertEquals(2, admins.size());
374 assertEquals(admin1, admins.get(0));
375 assertEquals(admin2, admins.get(1));
376
377 // Another user has no admins.
378 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
379
380 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
381 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
382
383 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
384 }
385
Makoto Onukid932f762015-09-29 16:53:38 -0700386 public void testSetActiveAdmin_multiUsers() throws Exception {
387
388 final int ANOTHER_USER_ID = 100;
389 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
390
Pavel Grafov75c0a892017-05-18 17:28:27 +0100391 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700392
393 // Set up pacakge manager for the other user.
394 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700395
396 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
397
398 dpm.setActiveAdmin(admin1, /* replace =*/ false);
399
400 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
401 dpm.setActiveAdmin(admin2, /* replace =*/ false);
402
403
404 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
405 assertTrue(dpm.isAdminActive(admin1));
406 assertFalse(dpm.isAdminActive(admin2));
407
408 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
409 assertFalse(dpm.isAdminActive(admin1));
410 assertTrue(dpm.isAdminActive(admin2));
411 }
412
Makoto Onukif76b06a2015-09-22 15:03:44 -0700413 /**
414 * Test for:
415 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800416 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700417 */
418 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
419 // 1. Make sure the caller has proper permissions.
420 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
421
422 dpm.setActiveAdmin(admin1, /* replace =*/ false);
423 assertTrue(dpm.isAdminActive(admin1));
424
425 // Add the same admin1 again without replace, which should throw.
426 try {
427 dpm.setActiveAdmin(admin1, /* replace =*/ false);
428 fail("Didn't throw");
429 } catch (IllegalArgumentException expected) {
430 }
431 }
432
433 /**
434 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800435 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
436 * BIND_DEVICE_ADMIN.
437 */
438 public void testSetActiveAdmin_permissionCheck() throws Exception {
439 // 1. Make sure the caller has proper permissions.
440 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
441
442 try {
443 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
444 fail();
445 } catch (IllegalArgumentException expected) {
446 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
447 }
448 assertFalse(dpm.isAdminActive(adminNoPerm));
449
450 // Change the target API level to MNC. Now it can be set as DA.
451 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
452 VERSION_CODES.M);
453 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
454 assertTrue(dpm.isAdminActive(adminNoPerm));
455
456 // TODO Test the "load from the file" case where DA will still be loaded even without
457 // BIND_DEVICE_ADMIN and target API is N.
458 }
459
460 /**
461 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700462 * {@link DevicePolicyManager#removeActiveAdmin}
463 */
464 public void testRemoveActiveAdmin_SecurityException() {
465 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
466
467 // Add admin.
468
469 dpm.setActiveAdmin(admin1, /* replace =*/ false);
470
471 assertTrue(dpm.isAdminActive(admin1));
472
473 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
474
475 // Directly call the DPMS method with a different userid, which should fail.
476 try {
477 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
478 fail("Didn't throw SecurityException");
479 } catch (SecurityException expected) {
480 }
481
482 // Try to remove active admin with a different caller userid should fail too, without
483 // having MANAGE_DEVICE_ADMINS.
484 mContext.callerPermissions.clear();
485
Makoto Onukid932f762015-09-29 16:53:38 -0700486 // Change the caller, and call into DPMS directly with a different user-id.
487
Makoto Onukif76b06a2015-09-22 15:03:44 -0700488 mContext.binder.callingUid = 1234567;
489 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700490 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700491 fail("Didn't throw SecurityException");
492 } catch (SecurityException expected) {
493 }
494 }
495
496 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800497 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
498 * (because we can't send the remove broadcast).
499 */
500 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
501 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
502
503 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
504
505 // Add admin.
506
507 dpm.setActiveAdmin(admin1, /* replace =*/ false);
508
509 assertTrue(dpm.isAdminActive(admin1));
510
511 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
512
513 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100514 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800515 .thenReturn(false);
516 try {
517 dpm.removeActiveAdmin(admin1);
518 fail("Didn't throw IllegalStateException");
519 } catch (IllegalStateException expected) {
520 MoreAsserts.assertContainsRegex(
521 "User must be running and unlocked", expected.getMessage());
522 }
523
524 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
525
526 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100527 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800528 .thenReturn(true);
529
530 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700531 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800532 }
533
534 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700535 * Test for:
536 * {@link DevicePolicyManager#removeActiveAdmin}
537 */
Makoto Onukid932f762015-09-29 16:53:38 -0700538 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700539 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
540
541 // Add admin1.
542
543 dpm.setActiveAdmin(admin1, /* replace =*/ false);
544
545 assertTrue(dpm.isAdminActive(admin1));
546 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
547
548 // Different user, but should work, because caller has proper permissions.
549 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700550
551 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700552 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700553
554 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700555 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700556
557 // TODO DO Still can't be removed in this case.
558 }
559
560 /**
561 * Test for:
562 * {@link DevicePolicyManager#removeActiveAdmin}
563 */
564 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
565 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
566 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
567
568 // Add admin1.
569
570 dpm.setActiveAdmin(admin1, /* replace =*/ false);
571
572 assertTrue(dpm.isAdminActive(admin1));
573 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
574
575 // Broadcast from saveSettingsLocked().
576 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
577 MockUtils.checkIntentAction(
578 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
579 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
580
581 // Remove. No permissions, but same user, so it'll work.
582 mContext.callerPermissions.clear();
583 dpm.removeActiveAdmin(admin1);
584
Makoto Onukif76b06a2015-09-22 15:03:44 -0700585 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
586 MockUtils.checkIntentAction(
587 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
588 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
589 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700590 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700591 eq(dpms.mHandler),
592 eq(Activity.RESULT_OK),
593 isNull(String.class),
594 isNull(Bundle.class));
595
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700596 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700597
598 // Again broadcast from saveSettingsLocked().
599 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
600 MockUtils.checkIntentAction(
601 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
602 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
603
604 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700605 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700606
607 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000608 * Test for: @{link DevicePolicyManager#setActivePasswordState}
609 *
610 * Validates that when the password for a user changes, the notification broadcast intent
611 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
612 * addition to ones in the original user.
613 */
614 public void testSetActivePasswordState_sendToProfiles() throws Exception {
615 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
616
617 final int MANAGED_PROFILE_USER_ID = 78;
618 final int MANAGED_PROFILE_ADMIN_UID =
619 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
620
621 // Setup device owner.
622 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
623 mContext.packageName = admin1.getPackageName();
624 setupDeviceOwner();
625
626 // Add a managed profile belonging to the system user.
627 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
628
629 // Change the parent user's password.
630 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
631
632 // Both the device owner and the managed profile owner should receive this broadcast.
633 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
634 intent.setComponent(admin1);
635 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
636
637 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
638 MockUtils.checkIntent(intent),
639 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
640 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
641 MockUtils.checkIntent(intent),
642 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
643 }
644
645 /**
646 * Test for: @{link DevicePolicyManager#setActivePasswordState}
647 *
648 * Validates that when the password for a managed profile changes, the notification broadcast
649 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
650 * its parent.
651 */
652 public void testSetActivePasswordState_notSentToParent() throws Exception {
653 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
654
655 final int MANAGED_PROFILE_USER_ID = 78;
656 final int MANAGED_PROFILE_ADMIN_UID =
657 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
658
659 // Setup device owner.
660 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
661 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100662 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000663 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
664 setupDeviceOwner();
665
666 // Add a managed profile belonging to the system user.
667 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
668
669 // Change the profile's password.
670 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
671
672 // Both the device owner and the managed profile owner should receive this broadcast.
673 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
674 intent.setComponent(admin1);
675 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
676
677 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
678 MockUtils.checkIntent(intent),
679 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
680 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
681 MockUtils.checkIntent(intent),
682 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
683 }
684 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000685 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700686 */
687 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000688 setDeviceOwner();
689
690 // Try to set a profile owner on the same user, which should fail.
691 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
692 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
693 try {
694 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
695 fail("IllegalStateException not thrown");
696 } catch (IllegalStateException expected) {
697 assertTrue("Message was: " + expected.getMessage(),
698 expected.getMessage().contains("already has a device owner"));
699 }
700
701 // DO admin can't be deactivated.
702 dpm.removeActiveAdmin(admin1);
703 assertTrue(dpm.isAdminActive(admin1));
704
705 // TODO Test getDeviceOwnerName() too. To do so, we need to change
706 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
707 }
708
709 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700710 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800711 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700712 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
713 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
714
Makoto Onukid932f762015-09-29 16:53:38 -0700715 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700716 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
717
Makoto Onukid932f762015-09-29 16:53:38 -0700718 // Make sure admin1 is installed on system user.
719 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700720
Makoto Onukic8a5a552015-11-19 14:29:12 -0800721 // Check various get APIs.
722 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
723
Makoto Onukib643fb02015-09-22 15:03:44 -0700724 // DO needs to be an DA.
725 dpm.setActiveAdmin(admin1, /* replace =*/ false);
726
727 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700728 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700729
Makoto Onukic8a5a552015-11-19 14:29:12 -0800730 // getDeviceOwnerComponent should return the admin1 component.
731 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
732 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
733
734 // Check various get APIs.
735 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
736
737 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
738 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
739 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
740 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
741
742 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
743
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000744 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100745 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000746 eq(admin1.getPackageName()));
747
Makoto Onukib643fb02015-09-22 15:03:44 -0700748 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100749 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700750 eq(UserHandle.USER_SYSTEM), eq(false));
751
752 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
753 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
754 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
755
Makoto Onukic8a5a552015-11-19 14:29:12 -0800756 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700757 }
758
Makoto Onukic8a5a552015-11-19 14:29:12 -0800759 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
760 final int origCallingUser = mContext.binder.callingUid;
761 final List origPermissions = new ArrayList(mContext.callerPermissions);
762 mContext.callerPermissions.clear();
763
764 mContext.callerPermissions.add(permission.MANAGE_USERS);
765
766 mContext.binder.callingUid = Process.SYSTEM_UID;
767
768 // TODO Test getDeviceOwnerName() too. To do so, we need to change
769 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
770 if (hasDeviceOwner) {
771 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
772 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
773 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
774
775 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
776 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
777 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
778 } else {
779 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
780 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
781 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
782
783 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
784 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
785 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
786 }
787
788 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
789 if (hasDeviceOwner) {
790 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
791 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
792 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
793
794 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
795 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
796 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
797 } else {
798 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
799 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
800 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
801
802 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
803 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
804 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
805 }
806
807 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
808 // Still with MANAGE_USERS.
809 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
810 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
811 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
812
813 if (hasDeviceOwner) {
814 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
815 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
816 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
817 } else {
818 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
819 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
820 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
821 }
822
823 mContext.binder.callingUid = Process.SYSTEM_UID;
824 mContext.callerPermissions.remove(permission.MANAGE_USERS);
825 // System can still call "OnAnyUser" without MANAGE_USERS.
826 if (hasDeviceOwner) {
827 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
828 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
829 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
830
831 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
832 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
833 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
834 } else {
835 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
836 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
837 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
838
839 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
840 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
841 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
842 }
843
844 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
845 // Still no MANAGE_USERS.
846 if (hasDeviceOwner) {
847 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
848 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
849 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
850 } else {
851 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
852 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
853 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
854 }
855
856 try {
857 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
858 fail();
859 } catch (SecurityException expected) {
860 }
861 try {
862 dpm.getDeviceOwnerComponentOnAnyUser();
863 fail();
864 } catch (SecurityException expected) {
865 }
866 try {
867 dpm.getDeviceOwnerUserId();
868 fail();
869 } catch (SecurityException expected) {
870 }
871 try {
872 dpm.getDeviceOwnerNameOnAnyUser();
873 fail();
874 } catch (SecurityException expected) {
875 }
876
877 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
878 // Still no MANAGE_USERS.
879 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
880 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
881 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
882
883 try {
884 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
885 fail();
886 } catch (SecurityException expected) {
887 }
888 try {
889 dpm.getDeviceOwnerComponentOnAnyUser();
890 fail();
891 } catch (SecurityException expected) {
892 }
893 try {
894 dpm.getDeviceOwnerUserId();
895 fail();
896 } catch (SecurityException expected) {
897 }
898 try {
899 dpm.getDeviceOwnerNameOnAnyUser();
900 fail();
901 } catch (SecurityException expected) {
902 }
903
904 // Restore.
905 mContext.binder.callingUid = origCallingUser;
906 mContext.callerPermissions.addAll(origPermissions);
907 }
908
909
Makoto Onukib643fb02015-09-22 15:03:44 -0700910 /**
911 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
912 */
913 public void testSetDeviceOwner_noSuchPackage() {
914 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800915 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700916 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
917 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
918
919 // Call from a process on the system user.
920 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
921
Makoto Onukib643fb02015-09-22 15:03:44 -0700922 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700923 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700924 fail("Didn't throw IllegalArgumentException");
925 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700926 assertTrue("Message was: " + expected.getMessage(),
927 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700928 }
929 }
930
931 public void testSetDeviceOwner_failures() throws Exception {
932 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
933 }
934
Makoto Onukia52562c2015-10-01 16:12:31 -0700935 public void testClearDeviceOwner() throws Exception {
936 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800937 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700938 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
939 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
940
941 // Set admin1 as a DA to the secondary user.
942 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
943
944 dpm.setActiveAdmin(admin1, /* replace =*/ false);
945
946 // Set admin 1 as the DO to the system user.
947
948 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
949 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
950 dpm.setActiveAdmin(admin1, /* replace =*/ false);
951 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
952
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000953 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100954 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000955 eq(admin1.getPackageName()));
956
Makoto Onukic8a5a552015-11-19 14:29:12 -0800957 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700958
Makoto Onuki90b89652016-01-28 14:44:18 -0800959 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100960 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000961 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800962
963 assertTrue(dpm.isAdminActive(admin1));
964 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
965
Makoto Onukia52562c2015-10-01 16:12:31 -0700966 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100967 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -0700968
969 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100970 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
971 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800972
973 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100974 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800975 try {
976 dpm.clearDeviceOwnerApp(admin1.getPackageName());
977 fail("Didn't throw IllegalStateException");
978 } catch (IllegalStateException expected) {
979 MoreAsserts.assertContainsRegex(
980 "User must be running and unlocked", expected.getMessage());
981 }
982
Pavel Grafov75c0a892017-05-18 17:28:27 +0100983 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
984 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700985 dpm.clearDeviceOwnerApp(admin1.getPackageName());
986
987 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800988 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700989
Pavel Grafov75c0a892017-05-18 17:28:27 +0100990 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000991 eq(false),
992 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
993
Pavel Grafov75c0a892017-05-18 17:28:27 +0100994 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -0800995 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100996 eq(null),
997 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800998
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700999 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001000
1001 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1002 // and once for clearing it.
1003 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1004 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1005 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001006 // TODO Check other calls.
1007 }
1008
1009 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1010 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001011 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001012 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1013 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1014
1015 // Set admin1 as a DA to the secondary user.
1016 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1017
1018 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1019
1020 // Set admin 1 as the DO to the system user.
1021
1022 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1023 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1024 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1025 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1026
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001027 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001028 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001029 eq(admin1.getPackageName()));
1030
Makoto Onukic8a5a552015-11-19 14:29:12 -08001031 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001032
1033 // Now call clear from the secondary user, which should throw.
1034 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1035
1036 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001037 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001038 eq(admin1.getPackageName()),
1039 anyInt());
1040 try {
1041 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1042 fail("Didn't throw");
1043 } catch (SecurityException e) {
1044 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
1045 }
1046
Makoto Onukic8a5a552015-11-19 14:29:12 -08001047 // DO shouldn't be removed.
1048 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001049 }
1050
Makoto Onukib643fb02015-09-22 15:03:44 -07001051 public void testSetProfileOwner() throws Exception {
1052 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001053
Makoto Onuki90b89652016-01-28 14:44:18 -08001054 // PO admin can't be deactivated.
1055 dpm.removeActiveAdmin(admin1);
1056 assertTrue(dpm.isAdminActive(admin1));
1057
Makoto Onuki803d6752015-10-30 12:58:39 -07001058 // Try setting DO on the same user, which should fail.
1059 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001060 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1061 runAsCaller(mServiceContext, dpms, dpm -> {
1062 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1063 try {
1064 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1065 fail("IllegalStateException not thrown");
1066 } catch (IllegalStateException expected) {
1067 assertTrue("Message was: " + expected.getMessage(),
1068 expected.getMessage().contains("already has a profile owner"));
1069 }
1070 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001071 }
1072
Makoto Onuki90b89652016-01-28 14:44:18 -08001073 public void testClearProfileOwner() throws Exception {
1074 setAsProfileOwner(admin1);
1075
1076 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1077
1078 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1079 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1080
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001081 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001082 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001083 .thenReturn(false);
1084 try {
1085 dpm.clearProfileOwner(admin1);
1086 fail("Didn't throw IllegalStateException");
1087 } catch (IllegalStateException expected) {
1088 MoreAsserts.assertContainsRegex(
1089 "User must be running and unlocked", expected.getMessage());
1090 }
1091 // Clear, really.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001092 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001093 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001094 dpm.clearProfileOwner(admin1);
1095
1096 // Check
1097 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001098 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001099 }
1100
Makoto Onukib643fb02015-09-22 15:03:44 -07001101 public void testSetProfileOwner_failures() throws Exception {
1102 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1103 }
1104
Makoto Onukia52562c2015-10-01 16:12:31 -07001105 public void testGetDeviceOwnerAdminLocked() throws Exception {
1106 checkDeviceOwnerWithMultipleDeviceAdmins();
1107 }
1108
1109 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1110 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1111 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1112 // make sure it gets the right component from the right user.
1113
1114 final int ANOTHER_USER_ID = 100;
1115 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1116
Pavel Grafov75c0a892017-05-18 17:28:27 +01001117 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001118
1119 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001120 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001121 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1122 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1123
1124 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1125
Pavel Grafov75c0a892017-05-18 17:28:27 +01001126 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001127
Makoto Onukia52562c2015-10-01 16:12:31 -07001128 // Make sure the admin packge is installed to each user.
1129 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1130 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1131
1132 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1133 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1134
1135 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1136
1137
1138 // Set active admins to the users.
1139 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1140 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1141
1142 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1143 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1144
1145 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1146
1147 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001148 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001149 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1150
Makoto Onukic8a5a552015-11-19 14:29:12 -08001151 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001152
1153 // Then check getDeviceOwnerAdminLocked().
1154 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1155 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1156 }
1157
1158 /**
1159 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001160 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1161 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001162 *
1163 * We didn't use to persist the DO component class name, but now we do, and the above method
1164 * finds the right component from a package name upon migration.
1165 */
1166 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001167 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001168 checkDeviceOwnerWithMultipleDeviceAdmins();
1169
1170 // Overwrite the device owner setting and clears the clas name.
1171 dpms.mOwners.setDeviceOwner(
1172 new ComponentName(admin2.getPackageName(), ""),
1173 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1174 dpms.mOwners.writeDeviceOwner();
1175
1176 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001177 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001178
1179 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001180 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001181 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001182 initializeDpms();
1183
1184 // Now the DO component name is a full name.
1185 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1186 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001187 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001188 }
1189
Makoto Onukib643fb02015-09-22 15:03:44 -07001190 public void testSetGetApplicationRestriction() {
1191 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001192 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001193
1194 {
1195 Bundle rest = new Bundle();
1196 rest.putString("KEY_STRING", "Foo1");
1197 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1198 }
1199
1200 {
1201 Bundle rest = new Bundle();
1202 rest.putString("KEY_STRING", "Foo2");
1203 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1204 }
1205
1206 {
1207 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1208 assertNotNull(returned);
1209 assertEquals(returned.size(), 1);
1210 assertEquals(returned.get("KEY_STRING"), "Foo1");
1211 }
1212
1213 {
1214 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1215 assertNotNull(returned);
1216 assertEquals(returned.size(), 1);
1217 assertEquals(returned.get("KEY_STRING"), "Foo2");
1218 }
1219
1220 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1221 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1222 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001223
Edman Anjosf9946772016-11-28 16:35:15 +01001224 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001225 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1226 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001227 *
1228 * @param packageName the name of the package to be setup
1229 * @param appId the application ID to be given to the package
1230 * @return the UID of the package as known by the mock package manager
1231 */
1232 private int setupPackageInPackageManager(final String packageName, final int appId)
1233 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001234 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001235 ApplicationInfo.FLAG_HAS_CODE);
1236 }
1237
1238 /**
1239 * Setup a package in the package manager mock. Useful for faking installed applications.
1240 *
1241 * @param packageName the name of the package to be setup
1242 * @param userId the user id where the package will be "installed"
1243 * @param appId the application ID to be given to the package
1244 * @param flags flags to set in the ApplicationInfo for this package
1245 * @return the UID of the package as known by the mock package manager
1246 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001247 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1248 int flags) throws Exception {
1249 final int uid = UserHandle.getUid(userId, appId);
1250 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001251 final PackageInfo pi = new PackageInfo();
1252 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001253 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001254 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001255 eq(packageName),
1256 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001257 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001258 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001259 eq(packageName),
1260 anyInt(),
1261 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001262 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001263 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001264 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001265 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001266 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001267 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001268 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001269 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001270 return uid;
1271 }
1272
Robin Lee7f5c91c2017-02-08 21:27:02 +00001273 public void testCertificateDisclosure() throws Exception {
1274 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1275 final UserHandle user = UserHandle.of(userId);
1276
1277 mContext.applicationInfo = new ApplicationInfo();
1278 mContext.callerPermissions.add(permission.MANAGE_USERS);
1279 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001280 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001281 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1282
Robin Leeabaa0692017-02-20 20:54:22 +00001283 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1284 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001285
1286 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1287 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1288
1289 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001290 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001291 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001292 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001293 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001294 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001295 .cancelAsUser(anyString(), anyInt(), eq(user));
1296
1297 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001298 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001299 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001300 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1301 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001302 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001303 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001304 .notifyAsUser(anyString(), anyInt(), argThat(
1305 new BaseMatcher<Notification>() {
1306 @Override
1307 public boolean matches(Object item) {
1308 final Notification noti = (Notification) item;
1309 return TEST_STRING.equals(
1310 noti.extras.getString(Notification.EXTRA_TITLE));
1311 }
1312 @Override
1313 public void describeTo(Description description) {
1314 description.appendText(
1315 "Notification{title=\"" + TEST_STRING + "\"}");
1316 }
1317 }), eq(user));
1318 }
1319
Edman Anjosf9946772016-11-28 16:35:15 +01001320 /**
1321 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1322 * privileges can acually be exercised by a delegate are not covered here.
1323 */
1324 public void testDelegation() throws Exception {
1325 setAsProfileOwner(admin1);
1326
1327 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1328
1329 // Given two packages
1330 final String CERT_DELEGATE = "com.delegate.certs";
1331 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1332 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1333 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1334 20989);
1335
1336 // On delegation
1337 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1338 mContext.packageName = admin1.getPackageName();
1339 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1340 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1341
1342 // DPMS correctly stores and retrieves the delegates
1343 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1344 assertEquals(2, policy.mDelegationMap.size());
1345 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1346 DELEGATION_CERT_INSTALL);
1347 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1348 DELEGATION_CERT_INSTALL);
1349 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1350 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1351 DELEGATION_APP_RESTRICTIONS);
1352 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1353 DELEGATION_APP_RESTRICTIONS);
1354 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1355
1356 // On calling install certificate APIs from an unauthorized process
1357 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1358 mContext.packageName = RESTRICTIONS_DELEGATE;
1359
1360 // DPMS throws a SecurityException
1361 try {
1362 dpm.installCaCert(null, null);
1363 fail("Didn't throw SecurityException on unauthorized access");
1364 } catch (SecurityException expected) {
1365 }
1366
1367 // On calling install certificate APIs from an authorized process
1368 mContext.binder.callingUid = CERT_DELEGATE_UID;
1369 mContext.packageName = CERT_DELEGATE;
1370
1371 // DPMS executes without a SecurityException
1372 try {
1373 dpm.installCaCert(null, null);
1374 } catch (SecurityException unexpected) {
1375 fail("Threw SecurityException on authorized access");
1376 } catch (NullPointerException expected) {
1377 }
1378
1379 // On removing a delegate
1380 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1381 mContext.packageName = admin1.getPackageName();
1382 dpm.setCertInstallerPackage(admin1, null);
1383
1384 // DPMS does not allow access to ex-delegate
1385 mContext.binder.callingUid = CERT_DELEGATE_UID;
1386 mContext.packageName = CERT_DELEGATE;
1387 try {
1388 dpm.installCaCert(null, null);
1389 fail("Didn't throw SecurityException on unauthorized access");
1390 } catch (SecurityException expected) {
1391 }
1392
1393 // But still allows access to other existing delegates
1394 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1395 mContext.packageName = RESTRICTIONS_DELEGATE;
1396 try {
1397 dpm.getApplicationRestrictions(null, "pkg");
1398 } catch (SecurityException expected) {
1399 fail("Threw SecurityException on authorized access");
1400 }
1401 }
1402
Esteban Talaverabf60f722015-12-10 16:26:44 +00001403 public void testApplicationRestrictionsManagingApp() throws Exception {
1404 setAsProfileOwner(admin1);
1405
Rubin Xued1928a2016-02-11 17:23:06 +00001406 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001407 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1408 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001409 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1410 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001411
Esteban Talaverabf60f722015-12-10 16:26:44 +00001412 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1413 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001414 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1415 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001416 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1417 Bundle rest = new Bundle();
1418 rest.putString("KEY_STRING", "Foo1");
1419 try {
1420 dpm.setApplicationRestrictions(null, "pkg1", rest);
1421 fail("Didn't throw expected SecurityException");
1422 } catch (SecurityException expected) {
1423 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001424 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1425 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001426 }
1427 try {
1428 dpm.getApplicationRestrictions(null, "pkg1");
1429 fail("Didn't throw expected SecurityException");
1430 } catch (SecurityException expected) {
1431 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001432 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1433 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001434 }
1435
1436 // Check via the profile owner that no restrictions were set.
1437 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001438 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001439 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1440
Rubin Xued1928a2016-02-11 17:23:06 +00001441 // Check the API does not allow setting a non-existent package
1442 try {
1443 dpm.setApplicationRestrictionsManagingPackage(admin1,
1444 nonExistAppRestrictionsManagerPackage);
1445 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001446 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001447 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001448 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001449 }
1450
Esteban Talaverabf60f722015-12-10 16:26:44 +00001451 // Let appRestrictionsManagerPackage manage app restrictions
1452 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1453 assertEquals(appRestrictionsManagerPackage,
1454 dpm.getApplicationRestrictionsManagingPackage(admin1));
1455
1456 // Now that package should be able to set and retrieve app restrictions.
1457 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001458 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001459 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1460 dpm.setApplicationRestrictions(null, "pkg1", rest);
1461 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1462 assertEquals(1, returned.size(), 1);
1463 assertEquals("Foo1", returned.get("KEY_STRING"));
1464
1465 // The same app running on a separate user shouldn't be able to manage app restrictions.
1466 mContext.binder.callingUid = UserHandle.getUid(
1467 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1468 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1469 try {
1470 dpm.setApplicationRestrictions(null, "pkg1", rest);
1471 fail("Didn't throw expected SecurityException");
1472 } catch (SecurityException expected) {
1473 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001474 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1475 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001476 }
1477
1478 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1479 // too.
1480 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001481 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001482 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1483 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1484 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1485
1486 // Removing the ability for the package to manage app restrictions.
1487 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1488 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1489 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001490 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001491 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1492 try {
1493 dpm.setApplicationRestrictions(null, "pkg1", null);
1494 fail("Didn't throw expected SecurityException");
1495 } catch (SecurityException expected) {
1496 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001497 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1498 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001499 }
1500 }
1501
Makoto Onukia4f11972015-10-01 13:19:58 -07001502 public void testSetUserRestriction_asDo() throws Exception {
1503 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001504 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001505 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1506 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1507
1508 // First, set DO.
1509
1510 // Call from a process on the system user.
1511 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1512
1513 // Make sure admin1 is installed on system user.
1514 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001515
1516 // Call.
1517 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001518 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001519 UserHandle.USER_SYSTEM));
1520
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001521 // Check that the user restrictions that are enabled by default are set. Then unset them.
1522 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001523 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001524 DpmTestUtils.assertRestrictions(
1525 DpmTestUtils.newRestrictions(defaultRestrictions),
1526 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1527 );
1528 DpmTestUtils.assertRestrictions(
1529 DpmTestUtils.newRestrictions(defaultRestrictions),
1530 dpm.getUserRestrictions(admin1)
1531 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001532 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001533 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001534 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001535 eq(true) /* isDeviceOwner */,
1536 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001537 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001538 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001539
1540 for (String restriction : defaultRestrictions) {
1541 dpm.clearUserRestriction(admin1, restriction);
1542 }
1543
Esteban Talavera548a04b2016-12-20 15:22:30 +00001544 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001545 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001546
1547 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001548 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001549 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001550 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1551 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001552 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001553
Makoto Onukia4f11972015-10-01 13:19:58 -07001554 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001555 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001556 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001557 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1558 UserManager.DISALLOW_ADD_USER),
1559 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001560 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001561
Makoto Onuki068c54a2015-10-13 14:34:03 -07001562 DpmTestUtils.assertRestrictions(
1563 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001564 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001565 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1566 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001567 DpmTestUtils.assertRestrictions(
1568 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001569 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001570 dpm.getUserRestrictions(admin1)
1571 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001572
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001573 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001574 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001575 eq(UserHandle.USER_SYSTEM),
1576 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001577 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001578 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001579
Makoto Onuki068c54a2015-10-13 14:34:03 -07001580 DpmTestUtils.assertRestrictions(
1581 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1582 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1583 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001584 DpmTestUtils.assertRestrictions(
1585 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1586 dpm.getUserRestrictions(admin1)
1587 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001588
1589 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001590 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001591 eq(UserHandle.USER_SYSTEM),
1592 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001593 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001594 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001595
Esteban Talavera548a04b2016-12-20 15:22:30 +00001596 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001597
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001598 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1599 // DO sets them, the scope is global.
1600 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001601 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001602 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001603 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001604 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001605 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001606 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1607 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001608 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001609
1610 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1611 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001612 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001613
1614 // More tests.
1615 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001616 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001617 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001618 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1619 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001620 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001621
1622 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001623 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001624 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001625 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001626 UserManager.DISALLOW_ADD_USER),
1627 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001628 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001629
1630 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001631 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001632 eq(UserHandle.USER_SYSTEM),
1633 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001634 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001635 UserManager.DISALLOW_ADD_USER),
1636 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001637 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001638
1639 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1640 // locally.
1641 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001642 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001643
1644 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1645 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1646 dpm.setCameraDisabled(admin2, true);
1647
Pavel Grafov75c0a892017-05-18 17:28:27 +01001648 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001650 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001651 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001652 UserManager.DISALLOW_ADD_USER),
1653 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001654 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001655 // TODO Make sure restrictions are written to the file.
1656 }
1657
1658 public void testSetUserRestriction_asPo() {
1659 setAsProfileOwner(admin1);
1660
Makoto Onuki068c54a2015-10-13 14:34:03 -07001661 DpmTestUtils.assertRestrictions(
1662 DpmTestUtils.newRestrictions(),
1663 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1664 .ensureUserRestrictions()
1665 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001666
1667 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001668 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001669 eq(DpmMockContext.CALLER_USER_HANDLE),
1670 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001671 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001672 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001673
Makoto Onukia4f11972015-10-01 13:19:58 -07001674 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001675 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001676 eq(DpmMockContext.CALLER_USER_HANDLE),
1677 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1678 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001679 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001680 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001681
Makoto Onuki068c54a2015-10-13 14:34:03 -07001682 DpmTestUtils.assertRestrictions(
1683 DpmTestUtils.newRestrictions(
1684 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1685 UserManager.DISALLOW_OUTGOING_CALLS
1686 ),
1687 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1688 .ensureUserRestrictions()
1689 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001690 DpmTestUtils.assertRestrictions(
1691 DpmTestUtils.newRestrictions(
1692 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1693 UserManager.DISALLOW_OUTGOING_CALLS
1694 ),
1695 dpm.getUserRestrictions(admin1)
1696 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001697
1698 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001699 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 eq(DpmMockContext.CALLER_USER_HANDLE),
1701 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001702 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001703 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001704
1705 DpmTestUtils.assertRestrictions(
1706 DpmTestUtils.newRestrictions(
1707 UserManager.DISALLOW_OUTGOING_CALLS
1708 ),
1709 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1710 .ensureUserRestrictions()
1711 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001712 DpmTestUtils.assertRestrictions(
1713 DpmTestUtils.newRestrictions(
1714 UserManager.DISALLOW_OUTGOING_CALLS
1715 ),
1716 dpm.getUserRestrictions(admin1)
1717 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001718
1719 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001720 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001721 eq(DpmMockContext.CALLER_USER_HANDLE),
1722 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001723 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001724 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001725
Makoto Onuki068c54a2015-10-13 14:34:03 -07001726 DpmTestUtils.assertRestrictions(
1727 DpmTestUtils.newRestrictions(),
1728 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1729 .ensureUserRestrictions()
1730 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001731 DpmTestUtils.assertRestrictions(
1732 DpmTestUtils.newRestrictions(),
1733 dpm.getUserRestrictions(admin1)
1734 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001735
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001736 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1737 // though when DO sets them they'll be applied globally.
1738 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001739 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001740 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001741 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001742 eq(DpmMockContext.CALLER_USER_HANDLE),
1743 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1744 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001745 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001746 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001747
1748 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001749 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001750 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001751 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001752 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001753 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001754 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001755
Makoto Onukia4f11972015-10-01 13:19:58 -07001756 // TODO Make sure restrictions are written to the file.
1757 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001758
Esteban Talavera548a04b2016-12-20 15:22:30 +00001759
1760 public void testDefaultEnabledUserRestrictions() throws Exception {
1761 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1762 mContext.callerPermissions.add(permission.MANAGE_USERS);
1763 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1764 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1765
1766 // First, set DO.
1767
1768 // Call from a process on the system user.
1769 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1770
1771 // Make sure admin1 is installed on system user.
1772 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1773
1774 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1775 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1776 UserHandle.USER_SYSTEM));
1777
1778 // Check that the user restrictions that are enabled by default are set. Then unset them.
1779 String[] defaultRestrictions = UserRestrictionsUtils
1780 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1781 assertTrue(defaultRestrictions.length > 0);
1782 DpmTestUtils.assertRestrictions(
1783 DpmTestUtils.newRestrictions(defaultRestrictions),
1784 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1785 );
1786 DpmTestUtils.assertRestrictions(
1787 DpmTestUtils.newRestrictions(defaultRestrictions),
1788 dpm.getUserRestrictions(admin1)
1789 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001790 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001791 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001792 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001793 eq(true) /* isDeviceOwner */,
1794 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001795 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001796 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001797
1798 for (String restriction : defaultRestrictions) {
1799 dpm.clearUserRestriction(admin1, restriction);
1800 }
1801
1802 assertNoDeviceOwnerRestrictions();
1803
1804 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001805 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001806 initializeDpms();
1807 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1808 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1809
1810 assertNoDeviceOwnerRestrictions();
1811
1812 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1813 // is set as it wasn't enabled during setDeviceOwner.
1814 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1815 assertFalse(UserRestrictionsUtils
1816 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1817 UserRestrictionsUtils
1818 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1819 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001820 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001821 initializeDpms();
1822 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1823 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1824
1825 DpmTestUtils.assertRestrictions(
1826 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1827 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1828 );
1829 DpmTestUtils.assertRestrictions(
1830 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1831 dpm.getUserRestrictions(admin1)
1832 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001833 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001834 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001835 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001836 eq(true) /* isDeviceOwner */,
1837 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001838 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001839 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001840
1841 // Remove the restriction.
1842 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1843
1844 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1845 initializeDpms();
1846 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1847 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1848 assertNoDeviceOwnerRestrictions();
1849 } finally {
1850 UserRestrictionsUtils
1851 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1852 }
1853 }
1854
1855 private void assertNoDeviceOwnerRestrictions() {
1856 DpmTestUtils.assertRestrictions(
1857 DpmTestUtils.newRestrictions(),
1858 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1859 );
1860 DpmTestUtils.assertRestrictions(
1861 DpmTestUtils.newRestrictions(),
1862 dpm.getUserRestrictions(admin1)
1863 );
1864 }
1865
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001866 public void testGetMacAddress() throws Exception {
1867 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1868 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1869 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1870
1871 // In this test, change the caller user to "system".
1872 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1873
1874 // Make sure admin1 is installed on system user.
1875 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1876
1877 // Test 1. Caller doesn't have DO or DA.
1878 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001879 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001880 fail();
1881 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001882 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001883 }
1884
1885 // DO needs to be an DA.
1886 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1887 assertTrue(dpm.isAdminActive(admin1));
1888
1889 // Test 2. Caller has DA, but not DO.
1890 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001891 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001892 fail();
1893 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001894 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001895 }
1896
1897 // Test 3. Caller has PO, but not DO.
1898 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1899 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001900 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001901 fail();
1902 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001903 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001904 }
1905
1906 // Remove PO.
1907 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001908 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001909 // Test 4, Caller is DO now.
1910 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1911
1912 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001913 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001914
1915 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001916 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001917 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001918
1919 // 4-3. With a real MAC address.
1920 final WifiInfo wi = new WifiInfo();
1921 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001922 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001923 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001924 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001925
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001926 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001927 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1928 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1929
1930 // In this test, change the caller user to "system".
1931 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1932
1933 // Make sure admin1 is installed on system user.
1934 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1935
1936 // Set admin1 as DA.
1937 dpm.setActiveAdmin(admin1, false);
1938 assertTrue(dpm.isAdminActive(admin1));
1939 try {
1940 dpm.reboot(admin1);
1941 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1942 } catch (SecurityException expected) {
1943 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1944 }
1945
1946 // Set admin1 as PO.
1947 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1948 try {
1949 dpm.reboot(admin1);
1950 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1951 } catch (SecurityException expected) {
1952 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1953 }
1954
1955 // Remove PO and add DO.
1956 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001957 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001958 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1959
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001960 // admin1 is DO.
1961 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001962 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001963 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1964 try {
1965 dpm.reboot(admin1);
1966 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1967 } catch (IllegalStateException expected) {
1968 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1969 }
1970
1971 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001972 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001973 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1974 try {
1975 dpm.reboot(admin1);
1976 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1977 } catch (IllegalStateException expected) {
1978 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1979 }
1980
1981 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001982 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001983 dpm.reboot(admin1);
1984 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001985
1986 public void testSetGetSupportText() {
1987 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1988 dpm.setActiveAdmin(admin1, true);
1989 dpm.setActiveAdmin(admin2, true);
1990 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1991
1992 // Null default support messages.
1993 {
1994 assertNull(dpm.getLongSupportMessage(admin1));
1995 assertNull(dpm.getShortSupportMessage(admin1));
1996 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1997 assertNull(dpm.getShortSupportMessageForUser(admin1,
1998 DpmMockContext.CALLER_USER_HANDLE));
1999 assertNull(dpm.getLongSupportMessageForUser(admin1,
2000 DpmMockContext.CALLER_USER_HANDLE));
2001 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2002 }
2003
2004 // Only system can call the per user versions.
2005 {
2006 try {
2007 dpm.getShortSupportMessageForUser(admin1,
2008 DpmMockContext.CALLER_USER_HANDLE);
2009 fail("Only system should be able to call getXXXForUser versions");
2010 } catch (SecurityException expected) {
2011 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
2012 }
2013 try {
2014 dpm.getLongSupportMessageForUser(admin1,
2015 DpmMockContext.CALLER_USER_HANDLE);
2016 fail("Only system should be able to call getXXXForUser versions");
2017 } catch (SecurityException expected) {
2018 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
2019 }
2020 }
2021
2022 // Can't set message for admin in another uid.
2023 {
2024 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
2025 try {
2026 dpm.setShortSupportMessage(admin1, "Some text");
2027 fail("Admins should only be able to change their own support text.");
2028 } catch (SecurityException expected) {
2029 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
2030 }
2031 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2032 }
2033
2034 // Set/Get short returns what it sets and other admins text isn't changed.
2035 {
2036 final String supportText = "Some text to test with.";
2037 dpm.setShortSupportMessage(admin1, supportText);
2038 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2039 assertNull(dpm.getLongSupportMessage(admin1));
2040 assertNull(dpm.getShortSupportMessage(admin2));
2041
2042 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2043 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2044 DpmMockContext.CALLER_USER_HANDLE));
2045 assertNull(dpm.getShortSupportMessageForUser(admin2,
2046 DpmMockContext.CALLER_USER_HANDLE));
2047 assertNull(dpm.getLongSupportMessageForUser(admin1,
2048 DpmMockContext.CALLER_USER_HANDLE));
2049 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2050
2051 dpm.setShortSupportMessage(admin1, null);
2052 assertNull(dpm.getShortSupportMessage(admin1));
2053 }
2054
2055 // Set/Get long returns what it sets and other admins text isn't changed.
2056 {
2057 final String supportText = "Some text to test with.\nWith more text.";
2058 dpm.setLongSupportMessage(admin1, supportText);
2059 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2060 assertNull(dpm.getShortSupportMessage(admin1));
2061 assertNull(dpm.getLongSupportMessage(admin2));
2062
2063 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2064 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2065 DpmMockContext.CALLER_USER_HANDLE));
2066 assertNull(dpm.getLongSupportMessageForUser(admin2,
2067 DpmMockContext.CALLER_USER_HANDLE));
2068 assertNull(dpm.getShortSupportMessageForUser(admin1,
2069 DpmMockContext.CALLER_USER_HANDLE));
2070 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2071
2072 dpm.setLongSupportMessage(admin1, null);
2073 assertNull(dpm.getLongSupportMessage(admin1));
2074 }
2075 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002076
phweiss73145f42017-01-17 19:06:38 +01002077 public void testCreateAdminSupportIntent() throws Exception {
2078 // Setup device owner.
2079 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2080 setupDeviceOwner();
2081
2082 // Nonexisting permission returns null
2083 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2084 assertNull(intent);
2085
2086 // Existing permission that is not set returns null
2087 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2088 assertNull(intent);
2089
2090 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002091 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002092 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2093 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2094 .thenReturn(true);
2095 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2096 assertNull(intent);
2097
2098 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002099 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002100 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2101 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2102 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2103 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2104 assertNotNull(intent);
2105 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2106 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2107 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2108 assertEquals(admin1,
2109 (ComponentName) intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
2110 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2111 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2112
2113 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2114 // user restrictions
2115
2116 // Camera is not disabled
2117 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2118 assertNull(intent);
2119
2120 // Camera is disabled
2121 dpm.setCameraDisabled(admin1, true);
2122 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2123 assertNotNull(intent);
2124 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2125 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2126
2127 // Screen capture is not disabled
2128 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2129 assertNull(intent);
2130
2131 // Screen capture is disabled
2132 dpm.setScreenCaptureDisabled(admin1, true);
2133 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2134 assertNotNull(intent);
2135 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2136 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2137
2138 // Same checks for different user
2139 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2140 // Camera should be disabled by device owner
2141 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2142 assertNotNull(intent);
2143 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2144 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2145 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2146 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2147 // ScreenCapture should not be disabled by device owner
2148 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2149 assertNull(intent);
2150 }
2151
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002152 /**
2153 * Test for:
2154 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002155 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002156 * {@link DevicePolicyManager#isAffiliatedUser}
2157 */
2158 public void testUserAffiliation() throws Exception {
2159 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2160 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2161 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2162
2163 // Check that the system user is unaffiliated.
2164 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2165 assertFalse(dpm.isAffiliatedUser());
2166
2167 // Set a device owner on the system user. Check that the system user becomes affiliated.
2168 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2169 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2170 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2171 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002172 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002173
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002174 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002175 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2176 setAsProfileOwner(admin2);
2177 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002178 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002179
2180 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2181 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002182 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002183 userAffiliationIds.add("red");
2184 userAffiliationIds.add("green");
2185 userAffiliationIds.add("blue");
2186 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002187 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002188 assertFalse(dpm.isAffiliatedUser());
2189
2190 // Have the device owner specify a set of affiliation ids that do not intersect with those
2191 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002192 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002193 deviceAffiliationIds.add("cyan");
2194 deviceAffiliationIds.add("yellow");
2195 deviceAffiliationIds.add("magenta");
2196 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2197 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002198 MoreAsserts.assertContentsInAnyOrder(
2199 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002200 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2201 assertFalse(dpm.isAffiliatedUser());
2202
2203 // Have the profile owner specify a set of affiliation ids that intersect with those
2204 // specified by the device owner. Check that the test user becomes affiliated.
2205 userAffiliationIds.add("yellow");
2206 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002207 MoreAsserts.assertContentsInAnyOrder(
2208 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002209 assertTrue(dpm.isAffiliatedUser());
2210
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002211 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002212 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002213 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002214 assertFalse(dpm.isAffiliatedUser());
2215
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002216 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2217 dpm.setAffiliationIds(admin2, userAffiliationIds);
2218 assertTrue(dpm.isAffiliatedUser());
2219 dpm.clearProfileOwner(admin2);
2220 assertFalse(dpm.isAffiliatedUser());
2221
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002222 // Check that the system user remains affiliated.
2223 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2224 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002225
2226 // Clear the device owner - the user becomes unaffiliated.
2227 clearDeviceOwner();
2228 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002229 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002230
2231 public void testGetUserProvisioningState_defaultResult() {
2232 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2233 }
2234
2235 public void testSetUserProvisioningState_permission() throws Exception {
2236 setupProfileOwner();
2237 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2238
2239 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2240 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2241 }
2242
2243 public void testSetUserProvisioningState_unprivileged() throws Exception {
2244 setupProfileOwner();
2245 try {
2246 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2247 DpmMockContext.CALLER_USER_HANDLE);
2248 fail("Expected SecurityException");
2249 } catch (SecurityException expected) {
2250 }
2251 }
2252
2253 public void testSetUserProvisioningState_noManagement() {
2254 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2255 try {
2256 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2257 DpmMockContext.CALLER_USER_HANDLE);
2258 fail("IllegalStateException expected");
2259 } catch (IllegalStateException e) {
2260 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
2261 e.getMessage());
2262 }
2263 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2264 }
2265
2266 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2267 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2268 setupDeviceOwner();
2269 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2270
2271 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2272 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2273 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2274 }
2275
2276 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2277 throws Exception {
2278 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2279 setupDeviceOwner();
2280 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2281
2282 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2283 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2284 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2285 }
2286
2287 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2288 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2289 setupDeviceOwner();
2290 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2291
2292 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2293 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2294 }
2295
2296 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2297 throws Exception {
2298 setupProfileOwner();
2299 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2300
2301 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2302 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2303 DevicePolicyManager.STATE_USER_UNMANAGED);
2304 }
2305
2306 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2307 throws Exception {
2308 setupProfileOwner();
2309 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2310
2311 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2312 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2313 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2314 }
2315
2316 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2317 setupProfileOwner();
2318 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2319
2320 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2321 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2322 }
2323
2324 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2325 setupProfileOwner();
2326 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2327
2328 try {
2329 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2330 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2331 DevicePolicyManager.STATE_USER_UNMANAGED);
2332 fail("Expected IllegalStateException");
2333 } catch (IllegalStateException e) {
2334 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2335 e.getMessage());
2336 }
2337 }
2338
2339 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2340 throws Exception {
2341 setupProfileOwner();
2342 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2343
2344 try {
2345 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2346 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2347 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2348 fail("Expected IllegalStateException");
2349 } catch (IllegalStateException e) {
2350 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2351 e.getMessage());
2352 }
2353 }
2354
2355 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2356 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2357 for (int state : states) {
2358 dpm.setUserProvisioningState(state, userId);
2359 assertEquals(state, dpm.getUserProvisioningState());
2360 }
2361 }
2362
2363 private void setupProfileOwner() throws Exception {
2364 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2365
2366 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2367 dpm.setActiveAdmin(admin1, false);
2368 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2369
2370 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2371 }
2372
2373 private void setupDeviceOwner() throws Exception {
2374 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2375
2376 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2377 dpm.setActiveAdmin(admin1, false);
2378 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2379
2380 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2381 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002382
2383 public void testSetMaximumTimeToLock() {
2384 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2385
2386 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2387 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2388
Pavel Grafov75c0a892017-05-18 17:28:27 +01002389 reset(getServices().powerManagerInternal);
2390 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002391
2392 dpm.setMaximumTimeToLock(admin1, 0);
2393 verifyScreenTimeoutCall(null, false);
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(admin1, 1);
2398 verifyScreenTimeoutCall(1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002399 reset(getServices().powerManagerInternal);
2400 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002401
2402 dpm.setMaximumTimeToLock(admin2, 10);
2403 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002404 reset(getServices().powerManagerInternal);
2405 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002406
2407 dpm.setMaximumTimeToLock(admin1, 5);
2408 verifyScreenTimeoutCall(5, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002409 reset(getServices().powerManagerInternal);
2410 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002411
2412 dpm.setMaximumTimeToLock(admin2, 4);
2413 verifyScreenTimeoutCall(4, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002414 reset(getServices().powerManagerInternal);
2415 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002416
2417 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002418 reset(getServices().powerManagerInternal);
2419 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002420
2421 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2422 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002423 reset(getServices().powerManagerInternal);
2424 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002425
2426 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2427 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002428 reset(getServices().powerManagerInternal);
2429 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002430
2431 dpm.setMaximumTimeToLock(admin2, 10);
2432 verifyScreenTimeoutCall(10, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002433 reset(getServices().powerManagerInternal);
2434 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002435
2436 // There's no restriction; shold be set to MAX.
2437 dpm.setMaximumTimeToLock(admin2, 0);
2438 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2439 }
2440
Michal Karpinski943aabd2016-10-06 11:09:25 +01002441 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2442 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2443 setupDeviceOwner();
2444 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2445
Michal Karpinskid084ca52017-01-18 15:54:18 +00002446 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2447 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2448 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2449 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2450 - ONE_MINUTE;
2451
2452 // verify that the minimum timeout cannot be modified on user builds (system property is
2453 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002454 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002455
2456 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2457 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2458 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2459
Pavel Grafov75c0a892017-05-18 17:28:27 +01002460 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002461
2462 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002463 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002464
2465 // Always return the default (second arg) when getting system property for long type
Pavel Grafov75c0a892017-05-18 17:28:27 +01002466 when(getServices().systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2467 invocation -> invocation.getArguments()[1]
Michal Karpinskid084ca52017-01-18 15:54:18 +00002468 );
2469
2470 // reset to default (0 means the admin is not participating, so default should be returned)
2471 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002472
2473 // aggregation should be the default if unset by any admin
2474 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2475 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2476
2477 // admin not participating by default
2478 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2479
2480 //clamping from the top
2481 dpm.setRequiredStrongAuthTimeout(admin1,
2482 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2483 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2484 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2485 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2486 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2487
Michal Karpinskid084ca52017-01-18 15:54:18 +00002488 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002489 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2490 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2491 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2492 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2493
2494 // clamping from the bottom
2495 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2496 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2497 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2498
Michal Karpinskid084ca52017-01-18 15:54:18 +00002499 // values within range
2500 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2501 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2502 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2503
2504 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2505 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2506 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002507
2508 // reset to default
2509 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2510 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2511 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2512 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2513
2514 // negative value
2515 try {
2516 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2517 fail("Didn't throw IllegalArgumentException");
2518 } catch (IllegalArgumentException iae) {
2519 }
2520 }
2521
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002522 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2523 boolean shouldStayOnWhilePluggedInBeCleared) {
2524 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002525 verify(getServices().powerManagerInternal, times(0))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002526 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2527 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002528 verify(getServices().powerManagerInternal, times(1))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002529 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2530 }
2531 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2532 // UnfinishedVerificationException.
2533 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002534
Esteban Talavera01576862016-12-15 11:16:44 +00002535 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002536 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002537 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002538 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002539 .thenReturn(false);
2540 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002541 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2542 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002543 .thenReturn(true);
2544 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2545
2546 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002547 }
Victor Chang3e794af2016-03-04 13:48:17 +00002548
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002549 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2550 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002551 mContext.packageName = admin1.getPackageName();
2552 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002553 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2554 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2555 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2556 false);
2557 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2558 }
2559
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002560 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2561 setup_DeviceAdminFeatureOff();
2562 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2563 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2564 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2565 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2566 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2567 assertCheckProvisioningPreCondition(
2568 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2569 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2570 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2571 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2572 }
2573
Esteban Talavera01576862016-12-15 11:16:44 +00002574 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002575 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002576 .thenReturn(false);
2577 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002578 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2579 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002580 .thenReturn(true);
2581 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2582
2583 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002584 }
Victor Chang3e794af2016-03-04 13:48:17 +00002585
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002586 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2587 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002588 mContext.packageName = admin1.getPackageName();
2589 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002590 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2591 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2592 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2593 false);
2594 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2595
2596 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002597 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002598 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2599 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2600 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2601 true);
2602 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2603 }
2604
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002605 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2606 setup_ManagedProfileFeatureOff();
2607 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2608 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2609 DevicePolicyManager.CODE_OK);
2610 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2611 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2612 assertCheckProvisioningPreCondition(
2613 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2614 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2615 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2616 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2617
2618 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002619 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002620 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2621 DevicePolicyManager.CODE_OK);
2622 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2623 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2624 assertCheckProvisioningPreCondition(
2625 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2626 DevicePolicyManager.CODE_OK);
2627 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2628 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2629 }
2630
Esteban Talavera01576862016-12-15 11:16:44 +00002631 private void setup_nonSplitUser_firstBoot_primaryUser() 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(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002634 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2635 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002636 .thenReturn(true);
2637 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2638
2639 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002640 }
Victor Chang3e794af2016-03-04 13:48:17 +00002641
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002642 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2643 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002644 mContext.packageName = admin1.getPackageName();
2645 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002646 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2647 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2648 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2649 false /* because of non-split user */);
2650 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2651 false /* because of non-split user */);
2652 }
2653
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002654 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002655 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002656 setup_nonSplitUser_firstBoot_primaryUser();
2657 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2658 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2659 DevicePolicyManager.CODE_OK);
2660 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2661 DevicePolicyManager.CODE_OK);
2662 assertCheckProvisioningPreCondition(
2663 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2664 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2665 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2666 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2667 }
2668
Esteban Talavera01576862016-12-15 11:16:44 +00002669 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002670 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002671 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002672 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2673 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002674 .thenReturn(true);
2675 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2676
2677 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002678 }
Victor Chang3e794af2016-03-04 13:48:17 +00002679
Nicolas Prevot45d29072017-01-18 16:11:19 +00002680 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2681 setDeviceOwner();
2682 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2683 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2684 }
2685
2686 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2687 setup_nonSplitUser_withDo_primaryUser();
2688 final int MANAGED_PROFILE_USER_ID = 18;
2689 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2690 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002691 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002692 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002693 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002694 true)).thenReturn(true);
2695 }
2696
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002697 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2698 throws Exception {
2699 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002700 mContext.packageName = admin1.getPackageName();
2701 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002702 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2703 false/* because of completed device setup */);
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_afterDeviceSetup_primaryUser()
2712 throws Exception {
2713 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2714 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2715 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2716 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
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
Nicolas Prevot45d29072017-01-18 16:11:19 +00002726 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2727 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002728 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002729 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2730
2731 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2732 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002733 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002734
2735 // COMP mode is allowed.
2736 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2737 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002738 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002739
Nicolas Prevot45d29072017-01-18 16:11:19 +00002740 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002741 assertCheckProvisioningPreCondition(
2742 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002743 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002744 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002745 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2746 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2747 }
Esteban Talavera01576862016-12-15 11:16:44 +00002748
Nicolas Prevot45d29072017-01-18 16:11:19 +00002749 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2750 setup_nonSplitUser_withDo_primaryUser();
2751 mContext.packageName = admin1.getPackageName();
2752 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2753 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2754 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002755 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002756 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2757 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2758 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002759 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002760 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2761 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2762 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2763 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2764 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002765 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002766 assertCheckProvisioningPreCondition(
2767 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002768 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002769 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002770 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2771 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2772 }
Esteban Talavera01576862016-12-15 11:16:44 +00002773
Nicolas Prevot45d29072017-01-18 16:11:19 +00002774 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2775 throws Exception {
2776 setup_nonSplitUser_withDo_primaryUser();
2777 mContext.packageName = admin1.getPackageName();
2778 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002779 // The DO should not be allowed to initiate provisioning if the restriction is set by
2780 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002781 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002782 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2783 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2784 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002785 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002786 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2787 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2788 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2789 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2790 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002791 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2792
2793 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002794 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002795 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002796 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002797 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2798 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2799 }
2800
2801 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2802 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2803 mContext.packageName = admin1.getPackageName();
2804 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2805
2806 // We can delete the managed profile to create a new one, so provisioning is allowed.
2807 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2808 DevicePolicyManager.CODE_OK);
2809 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2810 assertCheckProvisioningPreCondition(
2811 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2812 DpmMockContext.ANOTHER_PACKAGE_NAME,
2813 DevicePolicyManager.CODE_OK);
2814 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2815 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2816 }
2817
2818 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2819 throws Exception {
2820 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2821 mContext.packageName = admin1.getPackageName();
2822 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002823 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002824 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2825 eq(UserHandle.SYSTEM)))
2826 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002827 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002828 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2829 eq(UserHandle.SYSTEM)))
2830 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002831
2832 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002833 assertCheckProvisioningPreCondition(
2834 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2835 DpmMockContext.ANOTHER_PACKAGE_NAME,
2836 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2837 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2838 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002839
2840 // But the device owner can still do it because it has set the restriction itself.
2841 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2842 DevicePolicyManager.CODE_OK);
2843 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002844 }
2845
2846 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002847 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002848 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002849 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2850 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002851 .thenReturn(false);
2852 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2853
2854 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002855 }
Victor Chang3e794af2016-03-04 13:48:17 +00002856
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002857 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2858 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002859 mContext.packageName = admin1.getPackageName();
2860 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002861 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2862 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2863 false /* because canAddMoreManagedProfiles returns false */);
2864 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2865 true);
2866 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2867 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002868 }
2869
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002870 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2871 throws Exception {
2872 setup_splitUser_firstBoot_systemUser();
2873 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2874 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2875 DevicePolicyManager.CODE_OK);
2876 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002877 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002878 assertCheckProvisioningPreCondition(
2879 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2880 DevicePolicyManager.CODE_OK);
2881 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2882 DevicePolicyManager.CODE_SYSTEM_USER);
2883 }
2884
Esteban Talavera01576862016-12-15 11:16:44 +00002885 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002886 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002887 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002888 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2889 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002890 .thenReturn(false);
2891 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2892
2893 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002894 }
Victor Chang3e794af2016-03-04 13:48:17 +00002895
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002896 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2897 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002898 mContext.packageName = admin1.getPackageName();
2899 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002900 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2901 true/* it's undefined behavior. Can be changed into false in the future */);
2902 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2903 false /* because canAddMoreManagedProfiles returns false */);
2904 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2905 true/* it's undefined behavior. Can be changed into false in the future */);
2906 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2907 false/* because calling uid is system user */);
2908 }
2909
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002910 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2911 throws Exception {
2912 setup_splitUser_afterDeviceSetup_systemUser();
2913 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2914 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2915 DevicePolicyManager.CODE_OK);
2916 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002917 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002918 assertCheckProvisioningPreCondition(
2919 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2920 DevicePolicyManager.CODE_OK);
2921 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2922 DevicePolicyManager.CODE_SYSTEM_USER);
2923 }
2924
Esteban Talavera01576862016-12-15 11:16:44 +00002925 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002926 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002927 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002928 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2929 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002930 true)).thenReturn(true);
2931 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2932
2933 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002934 }
Victor Chang3e794af2016-03-04 13:48:17 +00002935
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002936 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2937 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002938 mContext.packageName = admin1.getPackageName();
2939 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002940 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2941 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2942 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2943 true);
2944 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002945 }
2946
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002947 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002948 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002949 setup_splitUser_firstBoot_primaryUser();
2950 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2951 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2952 DevicePolicyManager.CODE_OK);
2953 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2954 DevicePolicyManager.CODE_OK);
2955 assertCheckProvisioningPreCondition(
2956 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2957 DevicePolicyManager.CODE_OK);
2958 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2959 DevicePolicyManager.CODE_OK);
2960 }
2961
Esteban Talavera01576862016-12-15 11:16:44 +00002962 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002963 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002964 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002965 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2966 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002967 true)).thenReturn(true);
2968 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2969
2970 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002971 }
Victor Chang3e794af2016-03-04 13:48:17 +00002972
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002973 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2974 throws Exception {
2975 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002976 mContext.packageName = admin1.getPackageName();
2977 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002978 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2979 true/* it's undefined behavior. Can be changed into false in the future */);
2980 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2981 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2982 true/* it's undefined behavior. Can be changed into false in the future */);
2983 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2984 false/* because user setup completed */);
2985 }
2986
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002987 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002988 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002989 setup_splitUser_afterDeviceSetup_primaryUser();
2990 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2991 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2992 DevicePolicyManager.CODE_OK);
2993 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2994 DevicePolicyManager.CODE_OK);
2995 assertCheckProvisioningPreCondition(
2996 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2997 DevicePolicyManager.CODE_OK);
2998 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2999 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3000 }
3001
Esteban Talavera01576862016-12-15 11:16:44 +00003002 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003003 setDeviceOwner();
3004
Pavel Grafov75c0a892017-05-18 17:28:27 +01003005 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003006 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003007 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3008 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003009 .thenReturn(false);
3010 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3011
3012 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003013 }
Victor Chang3e794af2016-03-04 13:48:17 +00003014
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003015 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3016 throws Exception {
3017 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003018 mContext.packageName = admin1.getPackageName();
3019 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003020 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3021 false /* can't provision managed profile on system user */);
3022 }
3023
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003024 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003025 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003026 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3027 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3028 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3029 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3030 }
3031
3032 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003033 setDeviceOwner();
3034
Pavel Grafov75c0a892017-05-18 17:28:27 +01003035 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003036 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003037 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3038 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003039 true)).thenReturn(true);
3040 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3041
3042 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003043 }
Victor Chang3e794af2016-03-04 13:48:17 +00003044
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003045 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3046 throws Exception {
3047 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003048 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3049 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003050 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3051 }
3052
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003053 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003054 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003055 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3056 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003057
3058 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003059 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3060 DevicePolicyManager.CODE_OK);
3061 }
3062
3063 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003064 setDeviceOwner();
3065
Pavel Grafov75c0a892017-05-18 17:28:27 +01003066 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003067 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003068 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3069 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003070 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3071 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003072 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003073 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003074 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003075 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003076 true)).thenReturn(true);
3077 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3078
3079 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003080 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003081
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003082 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3083 throws Exception {
3084 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003085 mContext.packageName = admin1.getPackageName();
3086 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003087 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3088 }
3089
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003090 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3091 throws Exception {
3092 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3093 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3094 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3095 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3096 }
3097
3098 public void testCheckProvisioningPreCondition_permission() {
3099 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3100 try {
Esteban Talavera01576862016-12-15 11:16:44 +00003101 dpm.checkProvisioningPreCondition(
3102 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003103 fail("Didn't throw SecurityException");
3104 } catch (SecurityException expected) {
3105 }
3106 }
3107
Victor Chang3577ed22016-08-25 18:49:26 +01003108 public void testForceUpdateUserSetupComplete_permission() {
3109 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3110 try {
3111 dpm.forceUpdateUserSetupComplete();
3112 fail("Didn't throw SecurityException");
3113 } catch (SecurityException expected) {
3114 }
3115 }
3116
3117 public void testForceUpdateUserSetupComplete_systemUser() {
3118 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3119 // GIVEN calling from user 20
3120 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3121 try {
3122 dpm.forceUpdateUserSetupComplete();
3123 fail("Didn't throw SecurityException");
3124 } catch (SecurityException expected) {
3125 }
3126 }
3127
3128 public void testForceUpdateUserSetupComplete_userbuild() {
3129 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3130 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3131
3132 final int userId = UserHandle.USER_SYSTEM;
3133 // GIVEN userComplete is false in SettingsProvider
3134 setUserSetupCompleteForUser(false, userId);
3135
3136 // GIVEN userComplete is true in DPM
3137 DevicePolicyManagerService.DevicePolicyData userData =
3138 new DevicePolicyManagerService.DevicePolicyData(userId);
3139 userData.mUserSetupComplete = true;
3140 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3141
3142 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003143 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003144
3145 assertTrue(dpms.hasUserSetupCompleted());
3146
3147 dpm.forceUpdateUserSetupComplete();
3148
3149 // THEN the state in dpms is not changed
3150 assertTrue(dpms.hasUserSetupCompleted());
3151 }
3152
3153 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3154 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3155 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3156
3157 final int userId = UserHandle.USER_SYSTEM;
3158 // GIVEN userComplete is false in SettingsProvider
3159 setUserSetupCompleteForUser(false, userId);
3160
3161 // GIVEN userComplete is true in DPM
3162 DevicePolicyManagerService.DevicePolicyData userData =
3163 new DevicePolicyManagerService.DevicePolicyData(userId);
3164 userData.mUserSetupComplete = true;
3165 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3166
3167 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003168 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003169
3170 assertTrue(dpms.hasUserSetupCompleted());
3171
3172 dpm.forceUpdateUserSetupComplete();
3173
3174 // THEN the state in dpms is not changed
3175 assertFalse(dpms.hasUserSetupCompleted());
3176 }
3177
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003178 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003179 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003180 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003181
3182 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3183 runAsCaller(mAdmin1Context, dpms, dpm -> {
3184 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3185 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003186 }
3187
3188 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3189 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3190 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003191
3192 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3193 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003194 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003195 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3196 .thenReturn(true);
3197
3198 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003199 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003200
3201 // Enabling logging should not change the timestamp.
3202 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003203 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003204 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003205 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003206 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003207 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003208
3209 // Retrieving the logs should update the timestamp.
3210 final long beforeRetrieval = System.currentTimeMillis();
3211 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003212 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003213 final long afterRetrieval = System.currentTimeMillis();
3214 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3215 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3216
3217 // Retrieving the pre-boot logs should update the timestamp.
3218 Thread.sleep(2);
3219 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003220 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003221 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3222
3223 // Checking the timestamp again should not change it.
3224 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003225 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003226
3227 // Retrieving the logs again should update the timestamp.
3228 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003229 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003230 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3231
3232 // Disabling logging should not change the timestamp.
3233 Thread.sleep(2);
3234 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003235 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003236
3237 // Restarting the DPMS should not lose the timestamp.
3238 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003239 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003240
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003241 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3242 mContext.binder.callingUid = 1234567;
3243 mContext.callerPermissions.add(permission.MANAGE_USERS);
3244 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3245 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3246
3247 // System can retrieve the timestamp.
3248 mContext.binder.clearCallingIdentity();
3249 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3250
3251 // Removing the device owner should clear the timestamp.
3252 clearDeviceOwner();
3253 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003254 }
3255
3256 public void testGetLastBugReportRequestTime() throws Exception {
3257 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3258 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003259
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003260 mContext.packageName = admin1.getPackageName();
3261 mContext.applicationInfo = new ApplicationInfo();
3262 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3263 .thenReturn(Color.WHITE);
3264 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3265 anyObject())).thenReturn(Color.WHITE);
3266
Esteban Talaverad36dd152016-12-15 08:51:45 +00003267 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3268 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003269 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003270
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003271 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003272 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003273
3274 // Requesting a bug report should update the timestamp.
3275 final long beforeRequest = System.currentTimeMillis();
3276 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003277 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003278 final long afterRequest = System.currentTimeMillis();
3279 assertTrue(bugReportRequestTime >= beforeRequest);
3280 assertTrue(bugReportRequestTime <= afterRequest);
3281
3282 // Checking the timestamp again should not change it.
3283 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003284 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003285
3286 // Restarting the DPMS should not lose the timestamp.
3287 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003288 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003289
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003290 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3291 mContext.binder.callingUid = 1234567;
3292 mContext.callerPermissions.add(permission.MANAGE_USERS);
3293 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3294 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3295
3296 // System can retrieve the timestamp.
3297 mContext.binder.clearCallingIdentity();
3298 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3299
3300 // Removing the device owner should clear the timestamp.
3301 clearDeviceOwner();
3302 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003303 }
3304
3305 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3306 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3307 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003308 mContext.packageName = admin1.getPackageName();
3309 mContext.applicationInfo = new ApplicationInfo();
3310 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3311 .thenReturn(Color.WHITE);
3312 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3313 anyObject())).thenReturn(Color.WHITE);
3314
3315 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3316 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003317 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
3318 when(getServices().iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003319 .thenReturn(true);
3320
3321 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003322 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003323
3324 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3325 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003326 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003327
3328 // Enabling logging should not change the timestamp.
3329 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003330 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003331
3332 // Retrieving the logs should update the timestamp.
3333 final long beforeRetrieval = System.currentTimeMillis();
3334 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003335 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003336 final long afterRetrieval = System.currentTimeMillis();
3337 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3338 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3339
3340 // Checking the timestamp again should not change it.
3341 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003342 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003343
3344 // Retrieving the logs again should update the timestamp.
3345 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003346 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003347 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3348
3349 // Disabling logging should not change the timestamp.
3350 Thread.sleep(2);
3351 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003352 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003353
3354 // Restarting the DPMS should not lose the timestamp.
3355 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003356 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3357
3358 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3359 mContext.binder.callingUid = 1234567;
3360 mContext.callerPermissions.add(permission.MANAGE_USERS);
3361 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3362 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3363
3364 // System can retrieve the timestamp.
3365 mContext.binder.clearCallingIdentity();
3366 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3367
3368 // Removing the device owner should clear the timestamp.
3369 clearDeviceOwner();
3370 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003371 }
3372
Tony Mak2f26b792016-11-28 17:54:51 +00003373 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3374 // Setup device owner.
3375 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3376 setupDeviceOwner();
3377
3378 // Only device owner is setup, the result list should be empty.
3379 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3380 MoreAsserts.assertEmpty(targetUsers);
3381
3382 // Setup a managed profile managed by the same admin.
3383 final int MANAGED_PROFILE_USER_ID = 15;
3384 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3385 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3386
3387 // Add a secondary user, it should never talk with.
3388 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003389 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003390
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003391 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3392 // other.
3393 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3394 MoreAsserts.assertEmpty(targetUsers);
3395
3396 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3397 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3398 MoreAsserts.assertEmpty(targetUsers);
3399
3400 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003401 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003402 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3403 dpm.setAffiliationIds(admin1, userAffiliationIds);
3404
3405 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3406 dpm.setAffiliationIds(admin1, userAffiliationIds);
3407
Tony Mak2f26b792016-11-28 17:54:51 +00003408 // Calling from device owner admin, the result list should just contain the managed
3409 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003410 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003411 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3412 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3413
3414 // Calling from managed profile admin, the result list should just contain the system
3415 // user id.
3416 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3417 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3418 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003419
3420 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003421 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003422
3423 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3424 // to each other.
3425 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3426 MoreAsserts.assertEmpty(targetUsers);
3427
3428 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3429 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3430 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003431 }
3432
3433 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3434 // Setup a device owner.
3435 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3436 setupDeviceOwner();
3437
3438 // Set up a managed profile managed by different package.
3439 final int MANAGED_PROFILE_USER_ID = 15;
3440 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3441 final ComponentName adminDifferentPackage =
3442 new ComponentName("another.package", "whatever.class");
3443 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3444
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003445 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003446 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003447 dpm.setAffiliationIds(admin1, userAffiliationIds);
3448
3449 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3450 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3451
Tony Mak2f26b792016-11-28 17:54:51 +00003452 // Calling from device owner admin, we should get zero bind device admin target users as
3453 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003454 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003455 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3456 MoreAsserts.assertEmpty(targetUsers);
3457
3458 // Calling from managed profile admin, we should still get zero target users for the same
3459 // reason.
3460 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3461 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3462 MoreAsserts.assertEmpty(targetUsers);
3463 }
3464
Esteban Talaverabdcada92017-02-01 14:20:06 +00003465 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3466 // Setup a device owner.
3467 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3468 setupDeviceOwner();
3469 // Lock task packages are updated when loading user data.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003470 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003471 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3472
3473 // Set up a managed profile managed by different package (package name shouldn't matter)
3474 final int MANAGED_PROFILE_USER_ID = 15;
3475 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3476 final ComponentName adminDifferentPackage =
3477 new ComponentName("another.package", "whatever.class");
3478 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003479 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003480 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3481
3482 // The DO can still set lock task packages
3483 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3484 final String[] doPackages = {"doPackage1", "doPackage2"};
3485 dpm.setLockTaskPackages(admin1, doPackages);
3486 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3487 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3488 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003489 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003490 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3491
3492 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3493 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3494 final String[] poPackages = {"poPackage1", "poPackage2"};
3495 try {
3496 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3497 fail("Didn't throw expected security exception.");
3498 } catch (SecurityException expected) {
3499 }
3500 try {
3501 dpm.getLockTaskPackages(adminDifferentPackage);
3502 fail("Didn't throw expected security exception.");
3503 } catch (SecurityException expected) {
3504 }
3505 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3506
3507 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003508 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003509 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3510 dpm.setAffiliationIds(admin1, userAffiliationIds);
3511
3512 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3513 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3514
3515 // Now the managed profile can set lock task packages.
3516 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3517 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3518 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3519 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003520 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003521 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3522
3523 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003524 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003525 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3526 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003527 verify(getServices().iactivityManager, times(2))
Esteban Talaverabdcada92017-02-01 14:20:06 +00003528 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3529
3530 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3531 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3532 }
3533
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003534 public void testIsDeviceManaged() throws Exception {
3535 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3536 setupDeviceOwner();
3537
3538 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3539 // find out that the device has a device owner.
3540 assertTrue(dpm.isDeviceManaged());
3541 mContext.binder.callingUid = 1234567;
3542 mContext.callerPermissions.add(permission.MANAGE_USERS);
3543 assertTrue(dpm.isDeviceManaged());
3544 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3545 mContext.binder.clearCallingIdentity();
3546 assertTrue(dpm.isDeviceManaged());
3547
3548 clearDeviceOwner();
3549
3550 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3551 // not have a device owner.
3552 mContext.binder.callingUid = 1234567;
3553 mContext.callerPermissions.add(permission.MANAGE_USERS);
3554 assertFalse(dpm.isDeviceManaged());
3555 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3556 mContext.binder.clearCallingIdentity();
3557 assertFalse(dpm.isDeviceManaged());
3558 }
3559
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003560 public void testDeviceOwnerOrganizationName() throws Exception {
3561 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3562 setupDeviceOwner();
3563
3564 dpm.setOrganizationName(admin1, "organization");
3565
3566 // Device owner can retrieve organization managing the device.
3567 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3568
3569 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3570 mContext.binder.callingUid = 1234567;
3571 mContext.callerPermissions.add(permission.MANAGE_USERS);
3572 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3573 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3574
3575 // System can retrieve organization managing the device.
3576 mContext.binder.clearCallingIdentity();
3577 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3578
3579 // Removing the device owner clears the organization managing the device.
3580 clearDeviceOwner();
3581 assertNull(dpm.getDeviceOwnerOrganizationName());
3582 }
3583
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003584 public void testWipeDataManagedProfile() throws Exception {
3585 final int MANAGED_PROFILE_USER_ID = 15;
3586 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3587 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3588 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3589
3590 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003591 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003592 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3593
3594 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003595 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003596 MANAGED_PROFILE_USER_ID);
3597 }
3598
3599 public void testWipeDataManagedProfileDisallowed() throws Exception {
3600 final int MANAGED_PROFILE_USER_ID = 15;
3601 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3602 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3603
3604 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003605 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003606 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3607
Pavel Grafov75c0a892017-05-18 17:28:27 +01003608 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003609 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3610 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3611 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3612 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3613 try {
3614 // The PO is not allowed to remove the profile if the user restriction was set on the
3615 // profile by the system
3616 dpm.wipeData(0);
3617 fail("SecurityException not thrown");
3618 } catch (SecurityException expected) {
3619 }
3620 }
3621
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003622 public void testWipeDataDeviceOwner() throws Exception {
3623 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003624 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003625 UserManager.DISALLOW_FACTORY_RESET,
3626 UserHandle.SYSTEM))
3627 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3628
3629 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003630 verify(getServices().recoverySystem).rebootWipeUserData(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003631 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3632 }
3633
3634 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3635 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003636 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003637 UserManager.DISALLOW_FACTORY_RESET,
3638 UserHandle.SYSTEM))
3639 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3640 try {
3641 // The DO is not allowed to wipe the device if the user restriction was set
3642 // by the system
3643 dpm.wipeData(0);
3644 fail("SecurityException not thrown");
3645 } catch (SecurityException expected) {
3646 }
3647 }
3648
3649 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3650 final int MANAGED_PROFILE_USER_ID = 15;
3651 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3652 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3653
3654 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003655 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003656 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3657
Pavel Grafov75c0a892017-05-18 17:28:27 +01003658 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003659 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3660 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3661 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3662
3663 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3664 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3665
3666 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3667 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3668 // Failed password attempts on the parent user are taken into account, as there isn't a
3669 // separate work challenge.
3670 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3671 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3672 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3673
3674 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3675 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003676 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003677 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003678 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003679 }
3680
3681 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3682 throws Exception {
3683 final int MANAGED_PROFILE_USER_ID = 15;
3684 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3685 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3686
3687 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003688 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003689 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3690
Pavel Grafov75c0a892017-05-18 17:28:27 +01003691 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003692 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3693 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3694 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3695
3696 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3697 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3698
3699 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3700 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3701 // Failed password attempts on the parent user are taken into account, as there isn't a
3702 // separate work challenge.
3703 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3704 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3705 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3706
3707 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3708 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003709 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003710 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003711 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003712 }
3713
3714 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3715 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003716 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003717 UserManager.DISALLOW_FACTORY_RESET,
3718 UserHandle.SYSTEM))
3719 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3720
3721 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3722
3723 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3724 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3725 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3726 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3727 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3728
3729 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3730 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003731 verify(getServices().recoverySystem).rebootWipeUserData(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003732 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3733 }
3734
3735 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3736 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003737 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003738 UserManager.DISALLOW_FACTORY_RESET,
3739 UserHandle.SYSTEM))
3740 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3741
3742 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3743
3744 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3745 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3746 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3747 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3748 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3749
3750 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003751 verifyZeroInteractions(getServices().recoverySystem);
3752 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003753 .removeUserEvenWhenDisallowed(anyInt());
3754 }
3755
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003756 public void testGetPermissionGrantState() throws Exception {
3757 final String permission = "some.permission";
3758 final String app1 = "com.example.app1";
3759 final String app2 = "com.example.app2";
3760
Pavel Grafov75c0a892017-05-18 17:28:27 +01003761 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003762 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003763 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003764 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003765 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003766 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3767 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003768 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003769 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003770 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003771 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003772 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003773 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3774
3775 // System can retrieve permission grant state.
3776 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003777 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003778 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3779 dpm.getPermissionGrantState(null, app1, permission));
3780 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3781 dpm.getPermissionGrantState(null, app2, permission));
3782
3783 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003784 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3785 mContext.packageName = app1;
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003786 try {
3787 dpm.getPermissionGrantState(null, app1, permission);
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003788 fail("Didn't throw SecurityException");
3789 } catch (SecurityException expected) {
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003790 }
3791
3792 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003793 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3794 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003795 setAsProfileOwner(admin1);
3796 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3797 dpm.getPermissionGrantState(admin1, app1, permission));
3798 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3799 dpm.getPermissionGrantState(admin1, app2, permission));
3800 }
3801
Rubin Xuaab7a412016-12-30 21:13:29 +00003802 public void testResetPasswordWithToken() throws Exception {
3803 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3804 setupDeviceOwner();
3805 // test token validation
3806 try {
3807 dpm.setResetPasswordToken(admin1, new byte[31]);
3808 fail("should not have accepted tokens too short");
3809 } catch (IllegalArgumentException expected) {
3810 }
3811 // test adding a token
3812 final byte[] token = new byte[32];
3813 final long handle = 123456;
3814 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003815 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003816 .thenReturn(handle);
3817 assertTrue(dpm.setResetPasswordToken(admin1, token));
3818
3819 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003820 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003821 .thenReturn(true);
3822 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3823
3824 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003825 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xuaab7a412016-12-30 21:13:29 +00003826 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3827 eq(UserHandle.USER_SYSTEM)))
3828 .thenReturn(true);
3829 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3830
3831 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003832 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003833 .thenReturn(true);
3834 assertTrue(dpm.clearResetPasswordToken(admin1));
3835 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003836
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003837 public void testIsActivePasswordSufficient() throws Exception {
3838 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3839 mContext.packageName = admin1.getPackageName();
3840 setupDeviceOwner();
3841
3842 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3843 dpm.setPasswordMinimumLength(admin1, 8);
3844 dpm.setPasswordMinimumLetters(admin1, 6);
3845 dpm.setPasswordMinimumLowerCase(admin1, 3);
3846 dpm.setPasswordMinimumUpperCase(admin1, 1);
3847 dpm.setPasswordMinimumNonLetter(admin1, 1);
3848 dpm.setPasswordMinimumNumeric(admin1, 1);
3849 dpm.setPasswordMinimumSymbols(admin1, 0);
3850
3851 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3852 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3853 8, 2,
3854 6, 1,
3855 0, 1);
3856
3857 setActivePasswordState(passwordMetricsNoSymbols);
3858 assertTrue(dpm.isActivePasswordSufficient());
3859
3860 initializeDpms();
3861 reset(mContext.spiedContext);
3862 assertTrue(dpm.isActivePasswordSufficient());
3863
3864 // This call simulates the user entering the password for the first time after a reboot.
3865 // This causes password metrics to be reloaded into memory. Until this happens,
3866 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3867 // even if the DPC changes password requirements so that the password no longer meets the
3868 // requirements. This is a known limitation of the current implementation of
3869 // isActivePasswordSufficient() - see b/34218769.
3870 setActivePasswordState(passwordMetricsNoSymbols);
3871 assertTrue(dpm.isActivePasswordSufficient());
3872
3873 dpm.setPasswordMinimumSymbols(admin1, 1);
3874 // This assertion would fail if we had not called setActivePasswordState() again after
3875 // initializeDpms() - see previous comment.
3876 assertFalse(dpm.isActivePasswordSufficient());
3877
3878 initializeDpms();
3879 reset(mContext.spiedContext);
3880 assertFalse(dpm.isActivePasswordSufficient());
3881
3882 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3883 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3884 7, 2,
3885 5, 1,
3886 1, 2);
3887
3888 setActivePasswordState(passwordMetricsWithSymbols);
3889 assertTrue(dpm.isActivePasswordSufficient());
3890 }
3891
Pavel Grafov75c0a892017-05-18 17:28:27 +01003892 private void setActivePasswordState(PasswordMetrics passwordMetrics)
3893 throws Exception {
3894 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003895 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003896
Pavel Grafov75c0a892017-05-18 17:28:27 +01003897 dpm.setActivePasswordState(passwordMetrics, userHandle);
3898 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003899
Pavel Grafov75c0a892017-05-18 17:28:27 +01003900 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3901 intent.setComponent(admin1);
3902 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3903
3904 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3905 MockUtils.checkIntent(intent),
3906 MockUtils.checkUserHandle(userHandle));
3907
3908 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
3909 // let it finish with system uid, otherwise it will throw and crash.
3910 flushTasks();
3911
3912 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003913 }
3914
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003915 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3916 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3917 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3918 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3919 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3920 DpmMockContext.SYSTEM_UID);
3921 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3922 DpmMockContext.SYSTEM_UID);
3923
3924 // Set up a device owner.
3925 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003926 setupDeviceOwner();
3927
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003928 // First and second user set IMEs manually.
3929 mContext.binder.callingUid = firstUserSystemUid;
3930 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3931 mContext.binder.callingUid = secondUserSystemUid;
3932 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003933
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003934 // Device owner changes IME for first user.
3935 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003936 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003937 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003938 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003939 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003940 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003941 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003942 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3943 mContext.binder.callingUid = firstUserSystemUid;
3944 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3945 mContext.binder.callingUid = secondUserSystemUid;
3946 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003947
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003948 // Second user changes IME manually.
3949 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3950 mContext.binder.callingUid = firstUserSystemUid;
3951 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3952 mContext.binder.callingUid = secondUserSystemUid;
3953 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003954
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003955 // First user changes IME manually.
3956 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3957 mContext.binder.callingUid = firstUserSystemUid;
3958 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3959 mContext.binder.callingUid = secondUserSystemUid;
3960 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003961
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003962 // Device owner changes IME for first user again.
3963 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003964 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003965 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003966 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003967 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003968 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003969 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3970 mContext.binder.callingUid = firstUserSystemUid;
3971 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3972 mContext.binder.callingUid = secondUserSystemUid;
3973 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003974
3975 // Restarting the DPMS should not lose information.
3976 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003977 mContext.binder.callingUid = firstUserSystemUid;
3978 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3979 mContext.binder.callingUid = secondUserSystemUid;
3980 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003981
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003982 // Device owner can find out whether it set the current IME itself.
3983 mContext.binder.callingUid = deviceOwnerUid;
3984 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003985
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003986 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003987 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003988 mContext.binder.callingUid = firstUserSystemUid;
3989 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3990 mContext.binder.callingUid = secondUserSystemUid;
3991 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003992 }
3993
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003994 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3995 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3996 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3997 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3998 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3999 DpmMockContext.SYSTEM_UID);
4000 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4001 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004002
4003 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004004 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004005 setupProfileOwner();
4006
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004007 // First and second user set IMEs manually.
4008 mContext.binder.callingUid = firstUserSystemUid;
4009 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4010 mContext.binder.callingUid = secondUserSystemUid;
4011 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004012
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004013 // Profile owner changes IME for second user.
4014 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004015 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004016 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004017 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004018 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004019 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004020 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004021 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4022 mContext.binder.callingUid = firstUserSystemUid;
4023 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4024 mContext.binder.callingUid = secondUserSystemUid;
4025 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004026
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004027 // First user changes IME manually.
4028 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4029 mContext.binder.callingUid = firstUserSystemUid;
4030 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4031 mContext.binder.callingUid = secondUserSystemUid;
4032 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004033
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004034 // Second user changes IME manually.
4035 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4036 mContext.binder.callingUid = firstUserSystemUid;
4037 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4038 mContext.binder.callingUid = secondUserSystemUid;
4039 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004040
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004041 // Profile owner changes IME for second user again.
4042 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004043 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004044 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004045 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004046 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004047 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004048 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4049 mContext.binder.callingUid = firstUserSystemUid;
4050 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4051 mContext.binder.callingUid = secondUserSystemUid;
4052 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004053
4054 // Restarting the DPMS should not lose information.
4055 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004056 mContext.binder.callingUid = firstUserSystemUid;
4057 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4058 mContext.binder.callingUid = secondUserSystemUid;
4059 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004060
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004061 // Profile owner can find out whether it set the current IME itself.
4062 mContext.binder.callingUid = profileOwnerUid;
4063 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004064
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004065 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004066 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004067 mContext.binder.callingUid = firstUserSystemUid;
4068 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4069 mContext.binder.callingUid = secondUserSystemUid;
4070 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004071 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004072
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004073 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4074 throws Exception {
4075 // Set up a device owner.
4076 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4077 setupDeviceOwner();
4078 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4079 }
4080
4081 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4082 throws Exception {
4083 // Set up a profile owner.
4084 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4085 setupProfileOwner();
4086 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4087 }
4088
4089 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4090 int adminUid) throws Exception {
4091 mContext.binder.callingUid = adminUid;
4092 final int userId = UserHandle.getUserId(adminUid);
4093
4094 final String packageName = "some.package";
4095 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4096 admin1, Collections.singletonList(packageName)));
4097 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4098
4099 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4100 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4101
4102 // Attempt to set to empty list (which means no listener is whitelisted)
4103 mContext.binder.callingUid = adminUid;
4104 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004105 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004106 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4107
4108 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4109 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4110 }
4111
4112 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4113 // Set up a managed profile
4114 final int MANAGED_PROFILE_USER_ID = 15;
4115 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4116 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4117 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4118
4119 final String permittedListener = "some.package";
4120 setupPackageInPackageManager(
4121 permittedListener,
4122 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4123 /*appId=*/ 12345, /*flags=*/ 0);
4124
4125 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4126 admin1, Collections.singletonList(permittedListener)));
4127
4128 try {
4129 dpms.isNotificationListenerServicePermitted(
4130 permittedListener, MANAGED_PROFILE_USER_ID);
4131 fail("isNotificationListenerServicePermitted should throw if not called from System");
4132 } catch (SecurityException expected) {
4133 }
4134
4135 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4136 assertTrue(dpms.isNotificationListenerServicePermitted(
4137 permittedListener, MANAGED_PROFILE_USER_ID));
4138 }
4139
4140 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4141 throws Exception {
4142 // Set up a managed profile
4143 final int MANAGED_PROFILE_USER_ID = 15;
4144 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4145 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4146 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4147
4148 final String permittedListener = "permitted.package";
4149 int appId = 12345;
4150 setupPackageInPackageManager(
4151 permittedListener,
4152 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4153 appId, /*flags=*/ 0);
4154
4155 final String notPermittedListener = "not.permitted.package";
4156 setupPackageInPackageManager(
4157 notPermittedListener,
4158 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4159 ++appId, /*flags=*/ 0);
4160
4161 final String systemListener = "system.package";
4162 setupPackageInPackageManager(
4163 systemListener,
4164 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4165 ++appId, ApplicationInfo.FLAG_SYSTEM);
4166
4167 // By default all packages are allowed
4168 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4169
4170 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4171 assertTrue(dpms.isNotificationListenerServicePermitted(
4172 permittedListener, MANAGED_PROFILE_USER_ID));
4173 assertTrue(dpms.isNotificationListenerServicePermitted(
4174 notPermittedListener, MANAGED_PROFILE_USER_ID));
4175 assertTrue(dpms.isNotificationListenerServicePermitted(
4176 systemListener, MANAGED_PROFILE_USER_ID));
4177
4178 // Setting only one package in the whitelist
4179 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4180 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4181 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004182 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004183 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4184 assertEquals(1, permittedListeners.size());
4185 assertEquals(permittedListener, permittedListeners.get(0));
4186
4187 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4188 assertTrue(dpms.isNotificationListenerServicePermitted(
4189 permittedListener, MANAGED_PROFILE_USER_ID));
4190 assertFalse(dpms.isNotificationListenerServicePermitted(
4191 notPermittedListener, MANAGED_PROFILE_USER_ID));
4192 // System packages are always allowed (even if not in the whitelist)
4193 assertTrue(dpms.isNotificationListenerServicePermitted(
4194 systemListener, MANAGED_PROFILE_USER_ID));
4195
4196 // Setting an empty whitelist - only system listeners allowed
4197 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4198 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004199 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004200 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4201
4202 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4203 assertFalse(dpms.isNotificationListenerServicePermitted(
4204 permittedListener, MANAGED_PROFILE_USER_ID));
4205 assertFalse(dpms.isNotificationListenerServicePermitted(
4206 notPermittedListener, MANAGED_PROFILE_USER_ID));
4207 // System packages are always allowed (even if not in the whitelist)
4208 assertTrue(dpms.isNotificationListenerServicePermitted(
4209 systemListener, MANAGED_PROFILE_USER_ID));
4210
4211 // Setting a null whitelist - all listeners allowed
4212 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4213 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4214 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4215
4216 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4217 assertTrue(dpms.isNotificationListenerServicePermitted(
4218 permittedListener, MANAGED_PROFILE_USER_ID));
4219 assertTrue(dpms.isNotificationListenerServicePermitted(
4220 notPermittedListener, MANAGED_PROFILE_USER_ID));
4221 assertTrue(dpms.isNotificationListenerServicePermitted(
4222 systemListener, MANAGED_PROFILE_USER_ID));
4223 }
4224
4225 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4226 throws Exception {
4227 // Set up a managed profile
4228 final int MANAGED_PROFILE_USER_ID = 15;
4229 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4230 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4231 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4232
4233 final String nonSystemPackage = "non.system.package";
4234 int appId = 12345;
4235 setupPackageInPackageManager(
4236 nonSystemPackage,
4237 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4238 appId, /*flags=*/ 0);
4239
4240 final String systemListener = "system.package";
4241 setupPackageInPackageManager(
4242 systemListener,
4243 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4244 ++appId, ApplicationInfo.FLAG_SYSTEM);
4245
4246 // By default all packages are allowed (for all profiles)
4247 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4248
4249 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4250 assertTrue(dpms.isNotificationListenerServicePermitted(
4251 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4252 assertTrue(dpms.isNotificationListenerServicePermitted(
4253 systemListener, MANAGED_PROFILE_USER_ID));
4254 assertTrue(dpms.isNotificationListenerServicePermitted(
4255 nonSystemPackage, UserHandle.USER_SYSTEM));
4256 assertTrue(dpms.isNotificationListenerServicePermitted(
4257 systemListener, UserHandle.USER_SYSTEM));
4258
4259 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4260 // all allowed in primary profile
4261 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4262 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004263 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004264 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4265
4266 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4267 assertFalse(dpms.isNotificationListenerServicePermitted(
4268 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4269 assertTrue(dpms.isNotificationListenerServicePermitted(
4270 systemListener, MANAGED_PROFILE_USER_ID));
4271 assertTrue(dpms.isNotificationListenerServicePermitted(
4272 nonSystemPackage, UserHandle.USER_SYSTEM));
4273 assertTrue(dpms.isNotificationListenerServicePermitted(
4274 systemListener, UserHandle.USER_SYSTEM));
4275 }
4276
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004277 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004278 mServiceContext.packageName = mRealTestContext.getPackageName();
4279 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4280 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004281 setDeviceOwner();
4282
Pavel Grafov75c0a892017-05-18 17:28:27 +01004283 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004284 }
4285
4286 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004287 mServiceContext.packageName = mRealTestContext.getPackageName();
4288 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4289 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004290 setAsProfileOwner(admin1);
4291
Pavel Grafov75c0a892017-05-18 17:28:27 +01004292 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4293 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004294 }
4295
4296 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004297 mServiceContext.packageName = mRealTestContext.getPackageName();
4298 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4299 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004300 setAsProfileOwner(admin1);
4301
Pavel Grafov75c0a892017-05-18 17:28:27 +01004302 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4303 caller.packageName = "com.example.delegate";
4304 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4305 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004306
Pavel Grafov75c0a892017-05-18 17:28:27 +01004307 // Make caller a delegated cert installer.
4308 runAsCaller(mAdmin1Context, dpms,
4309 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004310
4311 verifyCanGetOwnerInstalledCaCerts(null, caller);
4312 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004313 }
4314
Robin Lee2c68dad2017-03-17 12:50:24 +00004315 private void verifyCanGetOwnerInstalledCaCerts(
4316 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004317 final String alias = "cert";
4318 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004319
4320 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004321 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004322 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4323 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004324 }
4325 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4326
4327 // caller: device admin or delegated certificate installer
4328 callerContext.applicationInfo = new ApplicationInfo();
4329 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4330
4331 // system_server
4332 final DpmMockContext serviceContext = mContext;
4333 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004334 getServices().addPackageContext(callerUser, admin1Context);
4335 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004336
4337 // Install a CA cert.
4338 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004339 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004340 .thenReturn(alias);
4341 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004342 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004343 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004344 });
4345
Pavel Grafov75c0a892017-05-18 17:28:27 +01004346 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4347 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4348 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004349 flushTasks();
4350
Robin Lee2c68dad2017-03-17 12:50:24 +00004351 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4352
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004353 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004354 runAsCaller(admin1Context, dpms, (dpm) -> {
4355 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004356 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004357 ownerInstalledCaCerts.addAll(installedCaCerts);
4358 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004359
4360 // Restarting the DPMS should not lose information.
4361 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004362 runAsCaller(admin1Context, dpms, (dpm) ->
4363 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004364
4365 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004366 runAsCaller(serviceContext, dpms, (dpm) -> {
4367 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004368
Robin Lee2c68dad2017-03-17 12:50:24 +00004369 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004370 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004371 });
4372
Pavel Grafov75c0a892017-05-18 17:28:27 +01004373 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4374 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4375 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004376 flushTasks();
4377
4378 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4379 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004380 runAsCaller(admin1Context, dpms, (dpm) -> {
4381 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4382 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004383 }
4384
Robin Lee2c68dad2017-03-17 12:50:24 +00004385 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4386 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004387 final String alias = "cert";
4388 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004389
4390 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004391 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004392 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4393 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004394 }
4395 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4396
4397 // caller: device admin or delegated certificate installer
4398 callerContext.applicationInfo = new ApplicationInfo();
4399 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4400
4401 // system_server
4402 final DpmMockContext serviceContext = mContext;
4403 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004404 getServices().addPackageContext(callerUser, admin1Context);
4405 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004406
4407 // Install a CA cert as caller
4408 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004409 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004410 .thenReturn(alias);
4411 assertTrue(dpm.installCaCert(callerName, caCert));
4412 });
4413
4414 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004415 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004416 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004417 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4418 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4419 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004420 flushTasks();
4421
Robin Lee2c68dad2017-03-17 12:50:24 +00004422 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004423 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004424
4425 runAsCaller(serviceContext, dpms, (dpm) -> {
4426 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4427 assertNotNull(ownerInstalledCaCerts);
4428 assertTrue(ownerInstalledCaCerts.isEmpty());
4429 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004430 }
4431
Victor Chang3e794af2016-03-04 13:48:17 +00004432 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004433 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004434 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4435 dpms.notifyChangeToContentObserver(
4436 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4437 }
4438
4439 private void assertProvisioningAllowed(String action, boolean expected) {
4440 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4441 dpm.isProvisioningAllowed(action));
4442 }
Tony Mak2f26b792016-11-28 17:54:51 +00004443
Nicolas Prevot45d29072017-01-18 16:11:19 +00004444 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4445 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004446 final String previousPackageName = mContext.packageName;
4447 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004448
4449 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4450 mContext.packageName = packageName;
4451 mMockContext.binder.callingUid = uid;
4452 assertProvisioningAllowed(action, expected);
4453
4454 // Set the previous package name / calling uid to go back to the initial state.
4455 mContext.packageName = previousPackageName;
4456 mMockContext.binder.callingUid = previousUid;
4457 }
4458
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004459 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004460 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4461 }
4462
4463 private void assertCheckProvisioningPreCondition(
4464 String action, String packageName, int provisioningCondition) {
4465 assertEquals("checkProvisioningPreCondition("
4466 + action + ", " + packageName + ") returning unexpected result",
4467 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004468 }
4469
Tony Mak2f26b792016-11-28 17:54:51 +00004470 /**
4471 * Setup a managed profile with the specified admin and its uid.
4472 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4473 * @param adminUid uid of the admin package.
4474 * @param copyFromAdmin package information for {@code admin} will be built based on this
4475 * component's information.
4476 */
4477 private void addManagedProfile(
4478 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4479 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004480 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004481 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4482 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4483 dpm.setActiveAdmin(admin, false, userId);
4484 assertTrue(dpm.setProfileOwner(admin, null, userId));
4485 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4486 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004487
4488 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004489 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004490 */
Robin Leeabaa0692017-02-20 20:54:22 +00004491 private static StringParceledListSlice asSlice(String[] s) {
4492 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004493 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004494
4495 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004496 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4497 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004498
Robin Lee2c68dad2017-03-17 12:50:24 +00004499 // We can't let exceptions happen on the background thread. Throw them here if they happen
4500 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004501 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004502 }
Victor Chang3e794af2016-03-04 13:48:17 +00004503}