blob: 6393b0b4018e10df435014ee4ca3a6cb24c13f1b [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 Grafova1ea8d92017-05-25 21:55:24 +010024import static com.android.server.testutis.TestUtils.assertExpectException;
25
Pavel Grafov75c0a892017-05-18 17:28:27 +010026import static org.mockito.Matchers.any;
27import static org.mockito.Matchers.anyInt;
28import static org.mockito.Matchers.anyLong;
29import static org.mockito.Matchers.anyObject;
30import static org.mockito.Matchers.anyString;
31import static org.mockito.Matchers.eq;
32import static org.mockito.Matchers.isNull;
33import static org.mockito.Mockito.atLeast;
34import static org.mockito.Mockito.doAnswer;
35import static org.mockito.Mockito.doReturn;
36import static org.mockito.Mockito.never;
37import static org.mockito.Mockito.nullable;
38import static org.mockito.Mockito.reset;
39import static org.mockito.Mockito.timeout;
40import static org.mockito.Mockito.times;
41import static org.mockito.Mockito.verify;
42import static org.mockito.Mockito.verifyZeroInteractions;
43import static org.mockito.Mockito.when;
44import static org.mockito.hamcrest.MockitoHamcrest.argThat;
45
Makoto Onukif76b06a2015-09-22 15:03:44 -070046import android.Manifest.permission;
47import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000048import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070049import android.app.admin.DeviceAdminReceiver;
50import android.app.admin.DevicePolicyManager;
51import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010052import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070053import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070054import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000055import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000056import android.content.pm.ApplicationInfo;
57import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070058import android.content.pm.PackageManager;
Robin Leeabaa0692017-02-20 20:54:22 +000059import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000060import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010061import android.graphics.Color;
62import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080063import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080064import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070065import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080066import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070067import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070068import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080069import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010070import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000071import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080072import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000073import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010074import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070075import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070076
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010077import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000078import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000079import com.android.server.LocalServices;
80import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000081import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000082
Robin Lee7f5c91c2017-02-08 21:27:02 +000083import org.hamcrest.BaseMatcher;
84import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070085import org.mockito.invocation.InvocationOnMock;
86import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070087
Makoto Onukic8a5a552015-11-19 14:29:12 -080088import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000089import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000090import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070091import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070092import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070093import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010094import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000095import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070096
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070097/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070098 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +000099 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100 m FrameworksServicesTests &&
101 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000102 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800104 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700105
106 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000107 *
108 * , or:
109 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700110 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000111@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700112public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000113 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
114 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
115 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100116 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
117 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000118
Pavel Grafov75c0a892017-05-18 17:28:27 +0100119 // TODO replace all instances of this with explicit {@link #mServiceContext}.
120 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100122
123 private DpmMockContext mServiceContext;
124 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700125 public DevicePolicyManager dpm;
126 public DevicePolicyManagerServiceTestable dpms;
127
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100128 /*
129 * The CA cert below is the content of cacert.pem as generated by:
130 *
131 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
132 */
133 private static final String TEST_CA =
134 "-----BEGIN CERTIFICATE-----\n" +
135 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
136 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
137 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
138 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
139 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
140 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
141 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
142 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
143 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
144 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
145 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
146 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
147 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
148 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
149 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
150 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
151 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
152 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
153 "wQ==\n" +
154 "-----END CERTIFICATE-----\n";
155
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700156 @Override
157 protected void setUp() throws Exception {
158 super.setUp();
159
160 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100161 mServiceContext = mContext;
162 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
163 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700164 .thenReturn(true);
165
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800166 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100167 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800168
Makoto Onukia52562c2015-10-01 16:12:31 -0700169 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700170
Makoto Onukid932f762015-09-29 16:53:38 -0700171 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
172 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
173 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800174 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700175
Pavel Grafov75c0a892017-05-18 17:28:27 +0100176 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
177 mAdmin1Context.packageName = admin1.getPackageName();
178 mAdmin1Context.applicationInfo = new ApplicationInfo();
179 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
180
Makoto Onukib643fb02015-09-22 15:03:44 -0700181 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700182 }
183
Robin Lee2c68dad2017-03-17 12:50:24 +0000184 @Override
185 protected void tearDown() throws Exception {
186 flushTasks();
187 super.tearDown();
188 }
189
Makoto Onukia52562c2015-10-01 16:12:31 -0700190 private void initializeDpms() {
191 // Need clearCallingIdentity() to pass permission checks.
192 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100193 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700194
Pavel Grafov75c0a892017-05-18 17:28:27 +0100195 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
196 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
197 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700198
Pavel Grafov75c0a892017-05-18 17:28:27 +0100199 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700200
Pavel Grafov75c0a892017-05-18 17:28:27 +0100201 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700202 }
203
Makoto Onukib643fb02015-09-22 15:03:44 -0700204 private void setUpUserManager() {
205 // Emulate UserManager.set/getApplicationRestriction().
206 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
207
208 // UM.setApplicationRestrictions() will save to appRestrictions.
209 doAnswer(new Answer<Void>() {
210 @Override
211 public Void answer(InvocationOnMock invocation) throws Throwable {
212 String pkg = (String) invocation.getArguments()[0];
213 Bundle bundle = (Bundle) invocation.getArguments()[1];
214 UserHandle user = (UserHandle) invocation.getArguments()[2];
215
216 appRestrictions.put(Pair.create(pkg, user), bundle);
217
218 return null;
219 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100220 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100221 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700222
223 // UM.getApplicationRestrictions() will read from appRestrictions.
224 doAnswer(new Answer<Bundle>() {
225 @Override
226 public Bundle answer(InvocationOnMock invocation) throws Throwable {
227 String pkg = (String) invocation.getArguments()[0];
228 UserHandle user = (UserHandle) invocation.getArguments()[1];
229
230 return appRestrictions.get(Pair.create(pkg, user));
231 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100232 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700233 anyString(), any(UserHandle.class));
234
Makoto Onukid932f762015-09-29 16:53:38 -0700235 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100236 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700237 }
238
239 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100240 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700241
Pavel Grafov75c0a892017-05-18 17:28:27 +0100242 mServiceContext.binder.callingUid =
243 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
244 runAsCaller(mServiceContext, dpms, dpm -> {
245 // PO needs to be a DA.
246 dpm.setActiveAdmin(admin, /*replace=*/ false);
247 // Fire!
248 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
249 // Check
250 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
251 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700252
Pavel Grafov75c0a892017-05-18 17:28:27 +0100253 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700254 }
255
256 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100257 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700258 .thenReturn(false);
259
260 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100261 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700262
263 // If the device has no DPMS feature, it shouldn't register the local service.
264 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
265 }
266
267 /**
268 * Caller doesn't have proper permissions.
269 */
270 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700271 // 1. Failure cases.
272
273 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100274 assertExpectException(SecurityException.class, /* messageRegex= */ null,
275 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700276
277 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
278 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100279
280 assertExpectException(SecurityException.class, /* messageRegex= */ null,
281 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700282 }
283
Makoto Onukif76b06a2015-09-22 15:03:44 -0700284 /**
285 * Test for:
286 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800287 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700288 * {@link DevicePolicyManager#isAdminActive}
289 * {@link DevicePolicyManager#isAdminActiveAsUser}
290 * {@link DevicePolicyManager#getActiveAdmins}
291 * {@link DevicePolicyManager#getActiveAdminsAsUser}
292 */
293 public void testSetActiveAdmin() throws Exception {
294 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700295 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
296
Makoto Onukif76b06a2015-09-22 15:03:44 -0700297 // 2. Call the API.
298 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700299
300 // 3. Verify internal calls.
301
302 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700303 verify(mContext.spiedContext).sendBroadcastAsUser(
304 MockUtils.checkIntentAction(
305 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
306 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
307 verify(mContext.spiedContext).sendBroadcastAsUser(
308 MockUtils.checkIntentAction(
309 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700310 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
311
Pavel Grafov75c0a892017-05-18 17:28:27 +0100312 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700313 eq(admin1.getPackageName()),
314 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
315 eq(PackageManager.DONT_KILL_APP),
316 eq(DpmMockContext.CALLER_USER_HANDLE),
317 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700318
319 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700320
321 // Make sure it's active admin1.
322 assertTrue(dpm.isAdminActive(admin1));
323 assertFalse(dpm.isAdminActive(admin2));
324 assertFalse(dpm.isAdminActive(admin3));
325
326 // But not admin1 for a different user.
327
328 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
329 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
330 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
331
332 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
333 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
334
335 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
336
337 // Next, add one more admin.
338 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700339 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
340 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700341
342 dpm.setActiveAdmin(admin2, /* replace =*/ false);
343
344 // Now we have two admins.
345 assertTrue(dpm.isAdminActive(admin1));
346 assertTrue(dpm.isAdminActive(admin2));
347 assertFalse(dpm.isAdminActive(admin3));
348
349 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
350 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100351 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700352 eq(admin1.getPackageName()),
353 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
354 eq(PackageManager.DONT_KILL_APP),
355 eq(DpmMockContext.CALLER_USER_HANDLE),
356 anyString());
357
358 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100359 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
360 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700361
362 // 5. Add the same admin1 again with replace, which should succeed.
363 dpm.setActiveAdmin(admin1, /* replace =*/ true);
364
365 // TODO make sure it's replaced.
366
367 // 6. Test getActiveAdmins()
368 List<ComponentName> admins = dpm.getActiveAdmins();
369 assertEquals(2, admins.size());
370 assertEquals(admin1, admins.get(0));
371 assertEquals(admin2, admins.get(1));
372
373 // Another user has no admins.
374 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
375
376 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
377 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
378
379 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
380 }
381
Makoto Onukid932f762015-09-29 16:53:38 -0700382 public void testSetActiveAdmin_multiUsers() throws Exception {
383
384 final int ANOTHER_USER_ID = 100;
385 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
386
Pavel Grafov75c0a892017-05-18 17:28:27 +0100387 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700388
389 // Set up pacakge manager for the other user.
390 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700391
392 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
393
394 dpm.setActiveAdmin(admin1, /* replace =*/ false);
395
396 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
397 dpm.setActiveAdmin(admin2, /* replace =*/ false);
398
399
400 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
401 assertTrue(dpm.isAdminActive(admin1));
402 assertFalse(dpm.isAdminActive(admin2));
403
404 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
405 assertFalse(dpm.isAdminActive(admin1));
406 assertTrue(dpm.isAdminActive(admin2));
407 }
408
Makoto Onukif76b06a2015-09-22 15:03:44 -0700409 /**
410 * Test for:
411 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800412 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700413 */
414 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
415 // 1. Make sure the caller has proper permissions.
416 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
417
418 dpm.setActiveAdmin(admin1, /* replace =*/ false);
419 assertTrue(dpm.isAdminActive(admin1));
420
421 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100422 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
423 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700424 }
425
426 /**
427 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800428 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
429 * BIND_DEVICE_ADMIN.
430 */
431 public void testSetActiveAdmin_permissionCheck() throws Exception {
432 // 1. Make sure the caller has proper permissions.
433 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
434
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100435 assertExpectException(IllegalArgumentException.class,
436 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
437 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800438 assertFalse(dpm.isAdminActive(adminNoPerm));
439
440 // Change the target API level to MNC. Now it can be set as DA.
441 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
442 VERSION_CODES.M);
443 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
444 assertTrue(dpm.isAdminActive(adminNoPerm));
445
446 // TODO Test the "load from the file" case where DA will still be loaded even without
447 // BIND_DEVICE_ADMIN and target API is N.
448 }
449
450 /**
451 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700452 * {@link DevicePolicyManager#removeActiveAdmin}
453 */
454 public void testRemoveActiveAdmin_SecurityException() {
455 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
456
457 // Add admin.
458
459 dpm.setActiveAdmin(admin1, /* replace =*/ false);
460
461 assertTrue(dpm.isAdminActive(admin1));
462
463 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
464
465 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100466 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
467 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700468
469 // Try to remove active admin with a different caller userid should fail too, without
470 // having MANAGE_DEVICE_ADMINS.
471 mContext.callerPermissions.clear();
472
Makoto Onukid932f762015-09-29 16:53:38 -0700473 // Change the caller, and call into DPMS directly with a different user-id.
474
Makoto Onukif76b06a2015-09-22 15:03:44 -0700475 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100476 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
477 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700478 }
479
480 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800481 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
482 * (because we can't send the remove broadcast).
483 */
484 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
485 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
486
487 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
488
489 // Add admin.
490
491 dpm.setActiveAdmin(admin1, /* replace =*/ false);
492
493 assertTrue(dpm.isAdminActive(admin1));
494
495 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
496
497 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100498 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800499 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100500 assertExpectException(IllegalStateException.class,
501 /* messageRegex= */ "User must be running and unlocked",
502 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800503
504 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
505
506 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100507 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800508 .thenReturn(true);
509
510 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700511 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800512 }
513
514 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700515 * Test for:
516 * {@link DevicePolicyManager#removeActiveAdmin}
517 */
Makoto Onukid932f762015-09-29 16:53:38 -0700518 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700519 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
520
521 // Add admin1.
522
523 dpm.setActiveAdmin(admin1, /* replace =*/ false);
524
525 assertTrue(dpm.isAdminActive(admin1));
526 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
527
528 // Different user, but should work, because caller has proper permissions.
529 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700530
531 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700532 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700533
534 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700535 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700536
537 // TODO DO Still can't be removed in this case.
538 }
539
540 /**
541 * Test for:
542 * {@link DevicePolicyManager#removeActiveAdmin}
543 */
544 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
545 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
546 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
547
548 // Add admin1.
549
550 dpm.setActiveAdmin(admin1, /* replace =*/ false);
551
552 assertTrue(dpm.isAdminActive(admin1));
553 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
554
555 // Broadcast from saveSettingsLocked().
556 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
557 MockUtils.checkIntentAction(
558 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
559 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
560
561 // Remove. No permissions, but same user, so it'll work.
562 mContext.callerPermissions.clear();
563 dpm.removeActiveAdmin(admin1);
564
Makoto Onukif76b06a2015-09-22 15:03:44 -0700565 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
566 MockUtils.checkIntentAction(
567 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
568 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
569 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700570 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700571 eq(dpms.mHandler),
572 eq(Activity.RESULT_OK),
573 isNull(String.class),
574 isNull(Bundle.class));
575
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700576 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700577
578 // Again broadcast from saveSettingsLocked().
579 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
580 MockUtils.checkIntentAction(
581 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
582 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
583
584 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700585 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700586
587 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000588 * Test for: @{link DevicePolicyManager#setActivePasswordState}
589 *
590 * Validates that when the password for a user changes, the notification broadcast intent
591 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
592 * addition to ones in the original user.
593 */
594 public void testSetActivePasswordState_sendToProfiles() throws Exception {
595 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
596
597 final int MANAGED_PROFILE_USER_ID = 78;
598 final int MANAGED_PROFILE_ADMIN_UID =
599 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
600
601 // Setup device owner.
602 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
603 mContext.packageName = admin1.getPackageName();
604 setupDeviceOwner();
605
606 // Add a managed profile belonging to the system user.
607 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
608
609 // Change the parent user's password.
610 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
611
612 // Both the device owner and the managed profile owner should receive this broadcast.
613 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
614 intent.setComponent(admin1);
615 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
616
617 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
618 MockUtils.checkIntent(intent),
619 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
620 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
621 MockUtils.checkIntent(intent),
622 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
623 }
624
625 /**
626 * Test for: @{link DevicePolicyManager#setActivePasswordState}
627 *
628 * Validates that when the password for a managed profile changes, the notification broadcast
629 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
630 * its parent.
631 */
632 public void testSetActivePasswordState_notSentToParent() throws Exception {
633 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
634
635 final int MANAGED_PROFILE_USER_ID = 78;
636 final int MANAGED_PROFILE_ADMIN_UID =
637 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
638
639 // Setup device owner.
640 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
641 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100642 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000643 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
644 setupDeviceOwner();
645
646 // Add a managed profile belonging to the system user.
647 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
648
649 // Change the profile's password.
650 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
651
652 // Both the device owner and the managed profile owner should receive this broadcast.
653 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
654 intent.setComponent(admin1);
655 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
656
657 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
658 MockUtils.checkIntent(intent),
659 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
660 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
661 MockUtils.checkIntent(intent),
662 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
663 }
664 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000665 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700666 */
667 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000668 setDeviceOwner();
669
670 // Try to set a profile owner on the same user, which should fail.
671 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
672 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100673 assertExpectException(IllegalStateException.class,
674 /* messageRegex= */ "already has a device owner",
675 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000676
677 // DO admin can't be deactivated.
678 dpm.removeActiveAdmin(admin1);
679 assertTrue(dpm.isAdminActive(admin1));
680
681 // TODO Test getDeviceOwnerName() too. To do so, we need to change
682 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
683 }
684
685 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700686 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800687 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700688 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
689 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
690
Makoto Onukid932f762015-09-29 16:53:38 -0700691 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700692 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
693
Makoto Onukid932f762015-09-29 16:53:38 -0700694 // Make sure admin1 is installed on system user.
695 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700696
Makoto Onukic8a5a552015-11-19 14:29:12 -0800697 // Check various get APIs.
698 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
699
Makoto Onukib643fb02015-09-22 15:03:44 -0700700 // DO needs to be an DA.
701 dpm.setActiveAdmin(admin1, /* replace =*/ false);
702
703 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700704 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700705
Makoto Onukic8a5a552015-11-19 14:29:12 -0800706 // getDeviceOwnerComponent should return the admin1 component.
707 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
708 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
709
710 // Check various get APIs.
711 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
712
713 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
714 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
715 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
716 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
717
718 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
719
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000720 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100721 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000722 eq(admin1.getPackageName()));
723
Makoto Onukib643fb02015-09-22 15:03:44 -0700724 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100725 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700726 eq(UserHandle.USER_SYSTEM), eq(false));
727
728 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
729 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
730 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
731
Makoto Onukic8a5a552015-11-19 14:29:12 -0800732 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700733 }
734
Makoto Onukic8a5a552015-11-19 14:29:12 -0800735 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
736 final int origCallingUser = mContext.binder.callingUid;
737 final List origPermissions = new ArrayList(mContext.callerPermissions);
738 mContext.callerPermissions.clear();
739
740 mContext.callerPermissions.add(permission.MANAGE_USERS);
741
742 mContext.binder.callingUid = Process.SYSTEM_UID;
743
744 // TODO Test getDeviceOwnerName() too. To do so, we need to change
745 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
746 if (hasDeviceOwner) {
747 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
748 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
749 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
750
751 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
752 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
753 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
754 } else {
755 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
756 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
757 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
758
759 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
760 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
761 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
762 }
763
764 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
765 if (hasDeviceOwner) {
766 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
767 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
768 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
769
770 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
771 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
772 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
773 } else {
774 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
775 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
776 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
777
778 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
779 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
780 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
781 }
782
783 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
784 // Still with MANAGE_USERS.
785 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
786 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
787 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
788
789 if (hasDeviceOwner) {
790 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
791 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
792 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
793 } else {
794 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
795 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
796 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
797 }
798
799 mContext.binder.callingUid = Process.SYSTEM_UID;
800 mContext.callerPermissions.remove(permission.MANAGE_USERS);
801 // System can still call "OnAnyUser" without MANAGE_USERS.
802 if (hasDeviceOwner) {
803 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
804 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
805 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
806
807 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
808 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
809 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
810 } else {
811 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
812 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
813 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
814
815 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
816 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
817 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
818 }
819
820 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
821 // Still no MANAGE_USERS.
822 if (hasDeviceOwner) {
823 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
824 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
825 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
826 } else {
827 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
828 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
829 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
830 }
831
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100832 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
833 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
834 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
835 dpm::getDeviceOwnerComponentOnAnyUser);
836 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
837 dpm::getDeviceOwnerUserId);
838 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
839 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800840
841 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
842 // Still no MANAGE_USERS.
843 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
844 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
845 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
846
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100847 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
848 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
849 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
850 dpm::getDeviceOwnerComponentOnAnyUser);
851 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
852 dpm::getDeviceOwnerUserId);
853 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
854 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800855
856 // Restore.
857 mContext.binder.callingUid = origCallingUser;
858 mContext.callerPermissions.addAll(origPermissions);
859 }
860
861
Makoto Onukib643fb02015-09-22 15:03:44 -0700862 /**
863 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
864 */
865 public void testSetDeviceOwner_noSuchPackage() {
866 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800867 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700868 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
869 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
870
871 // Call from a process on the system user.
872 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
873
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100874 assertExpectException(IllegalArgumentException.class,
875 /* messageRegex= */ "Invalid component",
876 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -0700877 }
878
879 public void testSetDeviceOwner_failures() throws Exception {
880 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
881 }
882
Makoto Onukia52562c2015-10-01 16:12:31 -0700883 public void testClearDeviceOwner() throws Exception {
884 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800885 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700886 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
887 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
888
889 // Set admin1 as a DA to the secondary user.
890 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
891
892 dpm.setActiveAdmin(admin1, /* replace =*/ false);
893
894 // Set admin 1 as the DO to the system user.
895
896 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
897 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
898 dpm.setActiveAdmin(admin1, /* replace =*/ false);
899 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
900
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000901 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100902 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000903 eq(admin1.getPackageName()));
904
Makoto Onukic8a5a552015-11-19 14:29:12 -0800905 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700906
Makoto Onuki90b89652016-01-28 14:44:18 -0800907 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100908 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000909 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800910
911 assertTrue(dpm.isAdminActive(admin1));
912 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
913
Makoto Onukia52562c2015-10-01 16:12:31 -0700914 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100915 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -0700916
917 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100918 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
919 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800920
921 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100922 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100923 assertExpectException(IllegalStateException.class,
924 /* messageRegex= */ "User must be running and unlocked",
925 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800926
Pavel Grafov75c0a892017-05-18 17:28:27 +0100927 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
928 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700929 dpm.clearDeviceOwnerApp(admin1.getPackageName());
930
931 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800932 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700933
Pavel Grafov75c0a892017-05-18 17:28:27 +0100934 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000935 eq(false),
936 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
937
Pavel Grafov75c0a892017-05-18 17:28:27 +0100938 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -0800939 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100940 eq(null),
941 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800942
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700943 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100944
945 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
946 // and once for clearing it.
947 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
948 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
949 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700950 // TODO Check other calls.
951 }
952
953 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
954 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800955 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700956 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
957 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
958
959 // Set admin1 as a DA to the secondary user.
960 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
961
962 dpm.setActiveAdmin(admin1, /* replace =*/ false);
963
964 // Set admin 1 as the DO to the system user.
965
966 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
967 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
968 dpm.setActiveAdmin(admin1, /* replace =*/ false);
969 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
970
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000971 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100972 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000973 eq(admin1.getPackageName()));
974
Makoto Onukic8a5a552015-11-19 14:29:12 -0800975 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700976
977 // Now call clear from the secondary user, which should throw.
978 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
979
980 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100981 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700982 eq(admin1.getPackageName()),
983 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100984 assertExpectException(SecurityException.class,
985 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
986 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -0700987
Makoto Onukic8a5a552015-11-19 14:29:12 -0800988 // DO shouldn't be removed.
989 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700990 }
991
Makoto Onukib643fb02015-09-22 15:03:44 -0700992 public void testSetProfileOwner() throws Exception {
993 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700994
Makoto Onuki90b89652016-01-28 14:44:18 -0800995 // PO admin can't be deactivated.
996 dpm.removeActiveAdmin(admin1);
997 assertTrue(dpm.isAdminActive(admin1));
998
Makoto Onuki803d6752015-10-30 12:58:39 -0700999 // Try setting DO on the same user, which should fail.
1000 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001001 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1002 runAsCaller(mServiceContext, dpms, dpm -> {
1003 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001004 assertExpectException(IllegalStateException.class,
1005 /* messageRegex= */ "already has a profile owner",
1006 () -> dpm.setDeviceOwner(admin2, "owner-name",
1007 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001008 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001009 }
1010
Makoto Onuki90b89652016-01-28 14:44:18 -08001011 public void testClearProfileOwner() throws Exception {
1012 setAsProfileOwner(admin1);
1013
1014 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1015
1016 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1017 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1018
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001019 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001020 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001021 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001022 assertExpectException(IllegalStateException.class,
1023 /* messageRegex= */ "User must be running and unlocked",
1024 () -> dpm.clearProfileOwner(admin1));
1025
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001026 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001027 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001028 dpm.clearProfileOwner(admin1);
1029
1030 // Check
1031 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001032 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001033 }
1034
Makoto Onukib643fb02015-09-22 15:03:44 -07001035 public void testSetProfileOwner_failures() throws Exception {
1036 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1037 }
1038
Makoto Onukia52562c2015-10-01 16:12:31 -07001039 public void testGetDeviceOwnerAdminLocked() throws Exception {
1040 checkDeviceOwnerWithMultipleDeviceAdmins();
1041 }
1042
1043 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1044 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1045 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1046 // make sure it gets the right component from the right user.
1047
1048 final int ANOTHER_USER_ID = 100;
1049 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1050
Pavel Grafov75c0a892017-05-18 17:28:27 +01001051 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001052
1053 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001054 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001055 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1056 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1057
1058 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1059
Pavel Grafov75c0a892017-05-18 17:28:27 +01001060 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001061
Makoto Onukia52562c2015-10-01 16:12:31 -07001062 // Make sure the admin packge is installed to each user.
1063 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1064 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1065
1066 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1067 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1068
1069 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1070
1071
1072 // Set active admins to the users.
1073 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1074 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1075
1076 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1077 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1078
1079 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1080
1081 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001082 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001083 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1084
Makoto Onukic8a5a552015-11-19 14:29:12 -08001085 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001086
1087 // Then check getDeviceOwnerAdminLocked().
1088 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1089 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1090 }
1091
1092 /**
1093 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001094 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1095 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001096 *
1097 * We didn't use to persist the DO component class name, but now we do, and the above method
1098 * finds the right component from a package name upon migration.
1099 */
1100 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001101 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001102 checkDeviceOwnerWithMultipleDeviceAdmins();
1103
1104 // Overwrite the device owner setting and clears the clas name.
1105 dpms.mOwners.setDeviceOwner(
1106 new ComponentName(admin2.getPackageName(), ""),
1107 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1108 dpms.mOwners.writeDeviceOwner();
1109
1110 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001111 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001112
1113 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001114 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001115 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001116 initializeDpms();
1117
1118 // Now the DO component name is a full name.
1119 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1120 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001121 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001122 }
1123
Makoto Onukib643fb02015-09-22 15:03:44 -07001124 public void testSetGetApplicationRestriction() {
1125 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001126 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001127
1128 {
1129 Bundle rest = new Bundle();
1130 rest.putString("KEY_STRING", "Foo1");
1131 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1132 }
1133
1134 {
1135 Bundle rest = new Bundle();
1136 rest.putString("KEY_STRING", "Foo2");
1137 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1138 }
1139
1140 {
1141 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1142 assertNotNull(returned);
1143 assertEquals(returned.size(), 1);
1144 assertEquals(returned.get("KEY_STRING"), "Foo1");
1145 }
1146
1147 {
1148 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1149 assertNotNull(returned);
1150 assertEquals(returned.size(), 1);
1151 assertEquals(returned.get("KEY_STRING"), "Foo2");
1152 }
1153
1154 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1155 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1156 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001157
Edman Anjosf9946772016-11-28 16:35:15 +01001158 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001159 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1160 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001161 *
1162 * @param packageName the name of the package to be setup
1163 * @param appId the application ID to be given to the package
1164 * @return the UID of the package as known by the mock package manager
1165 */
1166 private int setupPackageInPackageManager(final String packageName, final int appId)
1167 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001168 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001169 ApplicationInfo.FLAG_HAS_CODE);
1170 }
1171
1172 /**
1173 * Setup a package in the package manager mock. Useful for faking installed applications.
1174 *
1175 * @param packageName the name of the package to be setup
1176 * @param userId the user id where the package will be "installed"
1177 * @param appId the application ID to be given to the package
1178 * @param flags flags to set in the ApplicationInfo for this package
1179 * @return the UID of the package as known by the mock package manager
1180 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001181 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1182 int flags) throws Exception {
1183 final int uid = UserHandle.getUid(userId, appId);
1184 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001185 final PackageInfo pi = new PackageInfo();
1186 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001187 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001188 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001189 eq(packageName),
1190 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001191 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001192 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001193 eq(packageName),
1194 anyInt(),
1195 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001196 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001197 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001198 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001199 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001200 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001201 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001202 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001203 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001204 return uid;
1205 }
1206
Robin Lee7f5c91c2017-02-08 21:27:02 +00001207 public void testCertificateDisclosure() throws Exception {
1208 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1209 final UserHandle user = UserHandle.of(userId);
1210
1211 mContext.applicationInfo = new ApplicationInfo();
1212 mContext.callerPermissions.add(permission.MANAGE_USERS);
1213 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001214 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001215 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1216
Robin Leeabaa0692017-02-20 20:54:22 +00001217 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1218 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001219
1220 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1221 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1222
1223 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001224 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001225 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001226 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001227 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001228 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001229 .cancelAsUser(anyString(), anyInt(), eq(user));
1230
1231 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001232 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001233 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001234 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1235 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001236 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001237 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001238 .notifyAsUser(anyString(), anyInt(), argThat(
1239 new BaseMatcher<Notification>() {
1240 @Override
1241 public boolean matches(Object item) {
1242 final Notification noti = (Notification) item;
1243 return TEST_STRING.equals(
1244 noti.extras.getString(Notification.EXTRA_TITLE));
1245 }
1246 @Override
1247 public void describeTo(Description description) {
1248 description.appendText(
1249 "Notification{title=\"" + TEST_STRING + "\"}");
1250 }
1251 }), eq(user));
1252 }
1253
Edman Anjosf9946772016-11-28 16:35:15 +01001254 /**
1255 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1256 * privileges can acually be exercised by a delegate are not covered here.
1257 */
1258 public void testDelegation() throws Exception {
1259 setAsProfileOwner(admin1);
1260
1261 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1262
1263 // Given two packages
1264 final String CERT_DELEGATE = "com.delegate.certs";
1265 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1266 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1267 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1268 20989);
1269
1270 // On delegation
1271 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1272 mContext.packageName = admin1.getPackageName();
1273 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1274 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1275
1276 // DPMS correctly stores and retrieves the delegates
1277 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1278 assertEquals(2, policy.mDelegationMap.size());
1279 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1280 DELEGATION_CERT_INSTALL);
1281 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1282 DELEGATION_CERT_INSTALL);
1283 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1284 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1285 DELEGATION_APP_RESTRICTIONS);
1286 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1287 DELEGATION_APP_RESTRICTIONS);
1288 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1289
1290 // On calling install certificate APIs from an unauthorized process
1291 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1292 mContext.packageName = RESTRICTIONS_DELEGATE;
1293
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001294 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1295 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001296
1297 // On calling install certificate APIs from an authorized process
1298 mContext.binder.callingUid = CERT_DELEGATE_UID;
1299 mContext.packageName = CERT_DELEGATE;
1300
1301 // DPMS executes without a SecurityException
1302 try {
1303 dpm.installCaCert(null, null);
1304 } catch (SecurityException unexpected) {
1305 fail("Threw SecurityException on authorized access");
1306 } catch (NullPointerException expected) {
1307 }
1308
1309 // On removing a delegate
1310 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1311 mContext.packageName = admin1.getPackageName();
1312 dpm.setCertInstallerPackage(admin1, null);
1313
1314 // DPMS does not allow access to ex-delegate
1315 mContext.binder.callingUid = CERT_DELEGATE_UID;
1316 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001317 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1318 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001319
1320 // But still allows access to other existing delegates
1321 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1322 mContext.packageName = RESTRICTIONS_DELEGATE;
1323 try {
1324 dpm.getApplicationRestrictions(null, "pkg");
1325 } catch (SecurityException expected) {
1326 fail("Threw SecurityException on authorized access");
1327 }
1328 }
1329
Esteban Talaverabf60f722015-12-10 16:26:44 +00001330 public void testApplicationRestrictionsManagingApp() throws Exception {
1331 setAsProfileOwner(admin1);
1332
Rubin Xued1928a2016-02-11 17:23:06 +00001333 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001334 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001335 final String nonDelegateExceptionMessageRegex =
1336 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001337 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001338 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1339 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001340
Esteban Talaverabf60f722015-12-10 16:26:44 +00001341 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1342 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001343 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1344 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001345 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001346 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001347 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001348 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1349 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001350
1351 // Check via the profile owner that no restrictions were set.
1352 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001353 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001354 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1355
Rubin Xued1928a2016-02-11 17:23:06 +00001356 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001357 assertExpectException(PackageManager.NameNotFoundException.class,
1358 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1359 () -> dpm.setApplicationRestrictionsManagingPackage(
1360 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001361
Esteban Talaverabf60f722015-12-10 16:26:44 +00001362 // Let appRestrictionsManagerPackage manage app restrictions
1363 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1364 assertEquals(appRestrictionsManagerPackage,
1365 dpm.getApplicationRestrictionsManagingPackage(admin1));
1366
1367 // Now that package should be able to set and retrieve app restrictions.
1368 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001369 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001370 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1371 dpm.setApplicationRestrictions(null, "pkg1", rest);
1372 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1373 assertEquals(1, returned.size(), 1);
1374 assertEquals("Foo1", returned.get("KEY_STRING"));
1375
1376 // The same app running on a separate user shouldn't be able to manage app restrictions.
1377 mContext.binder.callingUid = UserHandle.getUid(
1378 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1379 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001380 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1381 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001382
1383 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1384 // too.
1385 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001386 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001387 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1388 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1389 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1390
1391 // Removing the ability for the package to manage app restrictions.
1392 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1393 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1394 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001395 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001396 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001397 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1398 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001399 }
1400
Makoto Onukia4f11972015-10-01 13:19:58 -07001401 public void testSetUserRestriction_asDo() throws Exception {
1402 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001403 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001404 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1405 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1406
1407 // First, set DO.
1408
1409 // Call from a process on the system user.
1410 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1411
1412 // Make sure admin1 is installed on system user.
1413 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001414
1415 // Call.
1416 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001417 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001418 UserHandle.USER_SYSTEM));
1419
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001420 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001421 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001422 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001423 DpmTestUtils.assertRestrictions(
1424 DpmTestUtils.newRestrictions(defaultRestrictions),
1425 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1426 );
1427 DpmTestUtils.assertRestrictions(
1428 DpmTestUtils.newRestrictions(defaultRestrictions),
1429 dpm.getUserRestrictions(admin1)
1430 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001431 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001432 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001433 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001434 eq(true) /* isDeviceOwner */,
1435 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001436 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001437 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001438
1439 for (String restriction : defaultRestrictions) {
1440 dpm.clearUserRestriction(admin1, restriction);
1441 }
1442
Esteban Talavera548a04b2016-12-20 15:22:30 +00001443 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001444 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001445
1446 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001447 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001449 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1450 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001451 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001452
Makoto Onukia4f11972015-10-01 13:19:58 -07001453 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001454 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001455 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001456 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1457 UserManager.DISALLOW_ADD_USER),
1458 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001459 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001460
Makoto Onuki068c54a2015-10-13 14:34:03 -07001461 DpmTestUtils.assertRestrictions(
1462 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001463 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001464 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1465 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001466 DpmTestUtils.assertRestrictions(
1467 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001468 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001469 dpm.getUserRestrictions(admin1)
1470 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001471
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001472 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001473 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001474 eq(UserHandle.USER_SYSTEM),
1475 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001476 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001477 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001478
Makoto Onuki068c54a2015-10-13 14:34:03 -07001479 DpmTestUtils.assertRestrictions(
1480 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1481 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1482 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001483 DpmTestUtils.assertRestrictions(
1484 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1485 dpm.getUserRestrictions(admin1)
1486 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001487
1488 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001489 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001490 eq(UserHandle.USER_SYSTEM),
1491 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001492 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001493 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001494
Esteban Talavera548a04b2016-12-20 15:22:30 +00001495 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001496
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001497 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1498 // DO sets them, the scope is global.
1499 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001500 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001501 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001502 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001503 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001504 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001505 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1506 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001507 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001508
1509 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1510 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001511 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001512
1513 // More tests.
1514 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001515 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001516 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001517 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1518 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001519 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001520
1521 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001522 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001523 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001524 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001525 UserManager.DISALLOW_ADD_USER),
1526 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001527 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001528
1529 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001530 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001531 eq(UserHandle.USER_SYSTEM),
1532 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001533 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001534 UserManager.DISALLOW_ADD_USER),
1535 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001536 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001537
1538 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1539 // locally.
1540 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001541 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001542
1543 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1544 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1545 dpm.setCameraDisabled(admin2, true);
1546
Pavel Grafov75c0a892017-05-18 17:28:27 +01001547 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001548 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001549 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001550 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001551 UserManager.DISALLOW_ADD_USER),
1552 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001553 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001554 // TODO Make sure restrictions are written to the file.
1555 }
1556
1557 public void testSetUserRestriction_asPo() {
1558 setAsProfileOwner(admin1);
1559
Makoto Onuki068c54a2015-10-13 14:34:03 -07001560 DpmTestUtils.assertRestrictions(
1561 DpmTestUtils.newRestrictions(),
1562 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1563 .ensureUserRestrictions()
1564 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001565
1566 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001567 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001568 eq(DpmMockContext.CALLER_USER_HANDLE),
1569 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001570 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001571 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001572
Makoto Onukia4f11972015-10-01 13:19:58 -07001573 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001574 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001575 eq(DpmMockContext.CALLER_USER_HANDLE),
1576 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1577 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001578 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001579 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001580
Makoto Onuki068c54a2015-10-13 14:34:03 -07001581 DpmTestUtils.assertRestrictions(
1582 DpmTestUtils.newRestrictions(
1583 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1584 UserManager.DISALLOW_OUTGOING_CALLS
1585 ),
1586 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1587 .ensureUserRestrictions()
1588 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001589 DpmTestUtils.assertRestrictions(
1590 DpmTestUtils.newRestrictions(
1591 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1592 UserManager.DISALLOW_OUTGOING_CALLS
1593 ),
1594 dpm.getUserRestrictions(admin1)
1595 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001596
1597 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001598 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001599 eq(DpmMockContext.CALLER_USER_HANDLE),
1600 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001601 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001602 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001603
1604 DpmTestUtils.assertRestrictions(
1605 DpmTestUtils.newRestrictions(
1606 UserManager.DISALLOW_OUTGOING_CALLS
1607 ),
1608 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1609 .ensureUserRestrictions()
1610 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001611 DpmTestUtils.assertRestrictions(
1612 DpmTestUtils.newRestrictions(
1613 UserManager.DISALLOW_OUTGOING_CALLS
1614 ),
1615 dpm.getUserRestrictions(admin1)
1616 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001617
1618 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001619 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001620 eq(DpmMockContext.CALLER_USER_HANDLE),
1621 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001622 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001623 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001624
Makoto Onuki068c54a2015-10-13 14:34:03 -07001625 DpmTestUtils.assertRestrictions(
1626 DpmTestUtils.newRestrictions(),
1627 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1628 .ensureUserRestrictions()
1629 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001630 DpmTestUtils.assertRestrictions(
1631 DpmTestUtils.newRestrictions(),
1632 dpm.getUserRestrictions(admin1)
1633 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001634
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001635 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1636 // though when DO sets them they'll be applied globally.
1637 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001638 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001639 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001640 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001641 eq(DpmMockContext.CALLER_USER_HANDLE),
1642 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1643 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001644 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001645 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001646
1647 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001648 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001650 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001651 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001652 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001653 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001654
Makoto Onukia4f11972015-10-01 13:19:58 -07001655 // TODO Make sure restrictions are written to the file.
1656 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001657
Esteban Talavera548a04b2016-12-20 15:22:30 +00001658
1659 public void testDefaultEnabledUserRestrictions() throws Exception {
1660 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1661 mContext.callerPermissions.add(permission.MANAGE_USERS);
1662 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1663 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1664
1665 // First, set DO.
1666
1667 // Call from a process on the system user.
1668 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1669
1670 // Make sure admin1 is installed on system user.
1671 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1672
1673 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1674 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1675 UserHandle.USER_SYSTEM));
1676
1677 // Check that the user restrictions that are enabled by default are set. Then unset them.
1678 String[] defaultRestrictions = UserRestrictionsUtils
1679 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1680 assertTrue(defaultRestrictions.length > 0);
1681 DpmTestUtils.assertRestrictions(
1682 DpmTestUtils.newRestrictions(defaultRestrictions),
1683 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1684 );
1685 DpmTestUtils.assertRestrictions(
1686 DpmTestUtils.newRestrictions(defaultRestrictions),
1687 dpm.getUserRestrictions(admin1)
1688 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001689 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001690 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001691 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001692 eq(true) /* isDeviceOwner */,
1693 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001694 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001695 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001696
1697 for (String restriction : defaultRestrictions) {
1698 dpm.clearUserRestriction(admin1, restriction);
1699 }
1700
1701 assertNoDeviceOwnerRestrictions();
1702
1703 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001704 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001705 initializeDpms();
1706 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1707 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1708
1709 assertNoDeviceOwnerRestrictions();
1710
1711 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1712 // is set as it wasn't enabled during setDeviceOwner.
1713 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1714 assertFalse(UserRestrictionsUtils
1715 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1716 UserRestrictionsUtils
1717 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1718 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001719 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001720 initializeDpms();
1721 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1722 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1723
1724 DpmTestUtils.assertRestrictions(
1725 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1726 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1727 );
1728 DpmTestUtils.assertRestrictions(
1729 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1730 dpm.getUserRestrictions(admin1)
1731 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001732 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001733 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001734 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001735 eq(true) /* isDeviceOwner */,
1736 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001737 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001738 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001739
1740 // Remove the restriction.
1741 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1742
1743 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1744 initializeDpms();
1745 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1746 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1747 assertNoDeviceOwnerRestrictions();
1748 } finally {
1749 UserRestrictionsUtils
1750 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1751 }
1752 }
1753
1754 private void assertNoDeviceOwnerRestrictions() {
1755 DpmTestUtils.assertRestrictions(
1756 DpmTestUtils.newRestrictions(),
1757 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1758 );
1759 DpmTestUtils.assertRestrictions(
1760 DpmTestUtils.newRestrictions(),
1761 dpm.getUserRestrictions(admin1)
1762 );
1763 }
1764
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001765 public void testGetMacAddress() throws Exception {
1766 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1767 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1768 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1769
1770 // In this test, change the caller user to "system".
1771 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1772
1773 // Make sure admin1 is installed on system user.
1774 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1775
1776 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001777 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1778 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001779
1780 // DO needs to be an DA.
1781 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1782 assertTrue(dpm.isAdminActive(admin1));
1783
1784 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001785 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1786 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001787
1788 // Test 3. Caller has PO, but not DO.
1789 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001790 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1791 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001792
1793 // Remove PO.
1794 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001795 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001796 // Test 4, Caller is DO now.
1797 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1798
1799 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001800 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001801
1802 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001803 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001804 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001805
1806 // 4-3. With a real MAC address.
1807 final WifiInfo wi = new WifiInfo();
1808 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001809 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001810 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001811 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001812
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001813 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001814 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1815 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1816
1817 // In this test, change the caller user to "system".
1818 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1819
1820 // Make sure admin1 is installed on system user.
1821 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1822
1823 // Set admin1 as DA.
1824 dpm.setActiveAdmin(admin1, false);
1825 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001826 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1827 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001828
1829 // Set admin1 as PO.
1830 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001831 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1832 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001833
1834 // Remove PO and add DO.
1835 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001836 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001837 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1838
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001839 // admin1 is DO.
1840 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001841 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001842 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001843 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1844 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001845
1846 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001847 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001848 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001849 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1850 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001851
1852 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001853 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001854 dpm.reboot(admin1);
1855 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001856
1857 public void testSetGetSupportText() {
1858 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1859 dpm.setActiveAdmin(admin1, true);
1860 dpm.setActiveAdmin(admin2, true);
1861 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1862
1863 // Null default support messages.
1864 {
1865 assertNull(dpm.getLongSupportMessage(admin1));
1866 assertNull(dpm.getShortSupportMessage(admin1));
1867 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1868 assertNull(dpm.getShortSupportMessageForUser(admin1,
1869 DpmMockContext.CALLER_USER_HANDLE));
1870 assertNull(dpm.getLongSupportMessageForUser(admin1,
1871 DpmMockContext.CALLER_USER_HANDLE));
1872 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1873 }
1874
1875 // Only system can call the per user versions.
1876 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001877 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1878 () -> dpm.getShortSupportMessageForUser(admin1,
1879 DpmMockContext.CALLER_USER_HANDLE));
1880 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1881 () -> dpm.getLongSupportMessageForUser(admin1,
1882 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00001883 }
1884
1885 // Can't set message for admin in another uid.
1886 {
1887 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001888 assertExpectException(SecurityException.class,
1889 /* messageRegex= */ "is not owned by uid",
1890 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00001891 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1892 }
1893
1894 // Set/Get short returns what it sets and other admins text isn't changed.
1895 {
1896 final String supportText = "Some text to test with.";
1897 dpm.setShortSupportMessage(admin1, supportText);
1898 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1899 assertNull(dpm.getLongSupportMessage(admin1));
1900 assertNull(dpm.getShortSupportMessage(admin2));
1901
1902 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1903 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1904 DpmMockContext.CALLER_USER_HANDLE));
1905 assertNull(dpm.getShortSupportMessageForUser(admin2,
1906 DpmMockContext.CALLER_USER_HANDLE));
1907 assertNull(dpm.getLongSupportMessageForUser(admin1,
1908 DpmMockContext.CALLER_USER_HANDLE));
1909 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1910
1911 dpm.setShortSupportMessage(admin1, null);
1912 assertNull(dpm.getShortSupportMessage(admin1));
1913 }
1914
1915 // Set/Get long returns what it sets and other admins text isn't changed.
1916 {
1917 final String supportText = "Some text to test with.\nWith more text.";
1918 dpm.setLongSupportMessage(admin1, supportText);
1919 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1920 assertNull(dpm.getShortSupportMessage(admin1));
1921 assertNull(dpm.getLongSupportMessage(admin2));
1922
1923 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1924 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1925 DpmMockContext.CALLER_USER_HANDLE));
1926 assertNull(dpm.getLongSupportMessageForUser(admin2,
1927 DpmMockContext.CALLER_USER_HANDLE));
1928 assertNull(dpm.getShortSupportMessageForUser(admin1,
1929 DpmMockContext.CALLER_USER_HANDLE));
1930 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1931
1932 dpm.setLongSupportMessage(admin1, null);
1933 assertNull(dpm.getLongSupportMessage(admin1));
1934 }
1935 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001936
phweiss73145f42017-01-17 19:06:38 +01001937 public void testCreateAdminSupportIntent() throws Exception {
1938 // Setup device owner.
1939 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1940 setupDeviceOwner();
1941
1942 // Nonexisting permission returns null
1943 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
1944 assertNull(intent);
1945
1946 // Existing permission that is not set returns null
1947 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1948 assertNull(intent);
1949
1950 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01001951 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01001952 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1953 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1954 .thenReturn(true);
1955 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1956 assertNull(intent);
1957
1958 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01001959 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01001960 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1961 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1962 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
1963 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1964 assertNotNull(intent);
1965 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
1966 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
1967 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001968 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01001969 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
1970 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1971
1972 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
1973 // user restrictions
1974
1975 // Camera is not disabled
1976 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1977 assertNull(intent);
1978
1979 // Camera is disabled
1980 dpm.setCameraDisabled(admin1, true);
1981 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1982 assertNotNull(intent);
1983 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
1984 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1985
1986 // Screen capture is not disabled
1987 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1988 assertNull(intent);
1989
1990 // Screen capture is disabled
1991 dpm.setScreenCaptureDisabled(admin1, true);
1992 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1993 assertNotNull(intent);
1994 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
1995 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1996
1997 // Same checks for different user
1998 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1999 // Camera should be disabled by device owner
2000 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2001 assertNotNull(intent);
2002 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2003 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2004 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2005 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2006 // ScreenCapture should not be disabled by device owner
2007 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2008 assertNull(intent);
2009 }
2010
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002011 /**
2012 * Test for:
2013 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002014 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002015 * {@link DevicePolicyManager#isAffiliatedUser}
2016 */
2017 public void testUserAffiliation() throws Exception {
2018 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2019 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2020 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2021
2022 // Check that the system user is unaffiliated.
2023 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2024 assertFalse(dpm.isAffiliatedUser());
2025
2026 // Set a device owner on the system user. Check that the system user becomes affiliated.
2027 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2028 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2029 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2030 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002031 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002032
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002033 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002034 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2035 setAsProfileOwner(admin2);
2036 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002037 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002038
2039 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2040 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002041 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002042 userAffiliationIds.add("red");
2043 userAffiliationIds.add("green");
2044 userAffiliationIds.add("blue");
2045 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002046 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002047 assertFalse(dpm.isAffiliatedUser());
2048
2049 // Have the device owner specify a set of affiliation ids that do not intersect with those
2050 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002051 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002052 deviceAffiliationIds.add("cyan");
2053 deviceAffiliationIds.add("yellow");
2054 deviceAffiliationIds.add("magenta");
2055 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2056 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002057 MoreAsserts.assertContentsInAnyOrder(
2058 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002059 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2060 assertFalse(dpm.isAffiliatedUser());
2061
2062 // Have the profile owner specify a set of affiliation ids that intersect with those
2063 // specified by the device owner. Check that the test user becomes affiliated.
2064 userAffiliationIds.add("yellow");
2065 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002066 MoreAsserts.assertContentsInAnyOrder(
2067 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002068 assertTrue(dpm.isAffiliatedUser());
2069
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002070 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002071 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002072 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002073 assertFalse(dpm.isAffiliatedUser());
2074
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002075 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2076 dpm.setAffiliationIds(admin2, userAffiliationIds);
2077 assertTrue(dpm.isAffiliatedUser());
2078 dpm.clearProfileOwner(admin2);
2079 assertFalse(dpm.isAffiliatedUser());
2080
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002081 // Check that the system user remains affiliated.
2082 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2083 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002084
2085 // Clear the device owner - the user becomes unaffiliated.
2086 clearDeviceOwner();
2087 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002088 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002089
2090 public void testGetUserProvisioningState_defaultResult() {
2091 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2092 }
2093
2094 public void testSetUserProvisioningState_permission() throws Exception {
2095 setupProfileOwner();
2096 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2097
2098 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2099 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2100 }
2101
2102 public void testSetUserProvisioningState_unprivileged() throws Exception {
2103 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002104 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2105 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2106 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002107 }
2108
2109 public void testSetUserProvisioningState_noManagement() {
2110 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002111 assertExpectException(IllegalStateException.class,
2112 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2113 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2114 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002115 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2116 }
2117
2118 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2119 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2120 setupDeviceOwner();
2121 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2122
2123 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2124 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2125 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2126 }
2127
2128 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2129 throws Exception {
2130 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2131 setupDeviceOwner();
2132 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2133
2134 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2135 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2136 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2137 }
2138
2139 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2140 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2141 setupDeviceOwner();
2142 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2143
2144 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2145 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2146 }
2147
2148 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2149 throws Exception {
2150 setupProfileOwner();
2151 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2152
2153 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2154 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2155 DevicePolicyManager.STATE_USER_UNMANAGED);
2156 }
2157
2158 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2159 throws Exception {
2160 setupProfileOwner();
2161 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2162
2163 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2164 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2165 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2166 }
2167
2168 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2169 setupProfileOwner();
2170 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2171
2172 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2173 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2174 }
2175
2176 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2177 setupProfileOwner();
2178 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2179
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002180 assertExpectException(IllegalStateException.class,
2181 /* messageRegex= */ "Cannot move to user provisioning state",
2182 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2183 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2184 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002185 }
2186
2187 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2188 throws Exception {
2189 setupProfileOwner();
2190 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2191
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002192 assertExpectException(IllegalStateException.class,
2193 /* messageRegex= */ "Cannot move to user provisioning state",
2194 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2195 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2196 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002197 }
2198
2199 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2200 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2201 for (int state : states) {
2202 dpm.setUserProvisioningState(state, userId);
2203 assertEquals(state, dpm.getUserProvisioningState());
2204 }
2205 }
2206
2207 private void setupProfileOwner() throws Exception {
2208 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2209
2210 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2211 dpm.setActiveAdmin(admin1, false);
2212 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2213
2214 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2215 }
2216
2217 private void setupDeviceOwner() throws Exception {
2218 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2219
2220 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2221 dpm.setActiveAdmin(admin1, false);
2222 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2223
2224 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2225 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002226
2227 public void testSetMaximumTimeToLock() {
2228 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2229
2230 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2231 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2232
Pavel Grafov75c0a892017-05-18 17:28:27 +01002233 reset(getServices().powerManagerInternal);
2234 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002235
2236 dpm.setMaximumTimeToLock(admin1, 0);
2237 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002238 reset(getServices().powerManagerInternal);
2239 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002240
2241 dpm.setMaximumTimeToLock(admin1, 1);
2242 verifyScreenTimeoutCall(1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002243 reset(getServices().powerManagerInternal);
2244 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002245
2246 dpm.setMaximumTimeToLock(admin2, 10);
2247 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002248 reset(getServices().powerManagerInternal);
2249 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002250
2251 dpm.setMaximumTimeToLock(admin1, 5);
2252 verifyScreenTimeoutCall(5, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002253 reset(getServices().powerManagerInternal);
2254 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002255
2256 dpm.setMaximumTimeToLock(admin2, 4);
2257 verifyScreenTimeoutCall(4, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002258 reset(getServices().powerManagerInternal);
2259 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002260
2261 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002262 reset(getServices().powerManagerInternal);
2263 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002264
2265 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2266 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002267 reset(getServices().powerManagerInternal);
2268 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002269
2270 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2271 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002272 reset(getServices().powerManagerInternal);
2273 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002274
2275 dpm.setMaximumTimeToLock(admin2, 10);
2276 verifyScreenTimeoutCall(10, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002277 reset(getServices().powerManagerInternal);
2278 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002279
2280 // There's no restriction; shold be set to MAX.
2281 dpm.setMaximumTimeToLock(admin2, 0);
2282 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2283 }
2284
Michal Karpinski943aabd2016-10-06 11:09:25 +01002285 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2286 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2287 setupDeviceOwner();
2288 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2289
Michal Karpinskid084ca52017-01-18 15:54:18 +00002290 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2291 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2292 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2293 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2294 - ONE_MINUTE;
2295
2296 // verify that the minimum timeout cannot be modified on user builds (system property is
2297 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002298 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002299
2300 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2301 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2302 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2303
Pavel Grafov75c0a892017-05-18 17:28:27 +01002304 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002305
2306 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002307 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002308
2309 // Always return the default (second arg) when getting system property for long type
Pavel Grafov75c0a892017-05-18 17:28:27 +01002310 when(getServices().systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2311 invocation -> invocation.getArguments()[1]
Michal Karpinskid084ca52017-01-18 15:54:18 +00002312 );
2313
2314 // reset to default (0 means the admin is not participating, so default should be returned)
2315 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002316
2317 // aggregation should be the default if unset by any admin
2318 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2319 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2320
2321 // admin not participating by default
2322 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2323
2324 //clamping from the top
2325 dpm.setRequiredStrongAuthTimeout(admin1,
2326 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2327 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2328 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2329 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2330 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2331
Michal Karpinskid084ca52017-01-18 15:54:18 +00002332 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002333 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2334 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2335 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2336 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2337
2338 // clamping from the bottom
2339 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2340 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2341 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2342
Michal Karpinskid084ca52017-01-18 15:54:18 +00002343 // values within range
2344 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2345 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2346 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2347
2348 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2349 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2350 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002351
2352 // reset to default
2353 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2354 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2355 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2356 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2357
2358 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002359 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2360 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002361 }
2362
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002363 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2364 boolean shouldStayOnWhilePluggedInBeCleared) {
2365 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002366 verify(getServices().powerManagerInternal, times(0))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002367 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2368 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002369 verify(getServices().powerManagerInternal, times(1))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002370 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2371 }
2372 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2373 // UnfinishedVerificationException.
2374 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002375
Esteban Talavera01576862016-12-15 11:16:44 +00002376 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002377 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002378 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002379 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002380 .thenReturn(false);
2381 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002382 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2383 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002384 .thenReturn(true);
2385 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2386
2387 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002388 }
Victor Chang3e794af2016-03-04 13:48:17 +00002389
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002390 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2391 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002392 mContext.packageName = admin1.getPackageName();
2393 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002394 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2395 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2396 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2397 false);
2398 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2399 }
2400
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002401 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2402 setup_DeviceAdminFeatureOff();
2403 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2404 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2405 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2406 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2407 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2408 assertCheckProvisioningPreCondition(
2409 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2410 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2411 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2412 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2413 }
2414
Esteban Talavera01576862016-12-15 11:16:44 +00002415 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002416 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002417 .thenReturn(false);
2418 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002419 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2420 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002421 .thenReturn(true);
2422 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2423
2424 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002425 }
Victor Chang3e794af2016-03-04 13:48:17 +00002426
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002427 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2428 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002429 mContext.packageName = admin1.getPackageName();
2430 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002431 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2432 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2433 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2434 false);
2435 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2436
2437 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002438 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002439 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2440 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2441 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2442 true);
2443 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2444 }
2445
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002446 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2447 setup_ManagedProfileFeatureOff();
2448 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2449 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2450 DevicePolicyManager.CODE_OK);
2451 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2452 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2453 assertCheckProvisioningPreCondition(
2454 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2455 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2456 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2457 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2458
2459 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002460 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002461 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2462 DevicePolicyManager.CODE_OK);
2463 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2464 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2465 assertCheckProvisioningPreCondition(
2466 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2467 DevicePolicyManager.CODE_OK);
2468 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2469 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2470 }
2471
Esteban Talavera01576862016-12-15 11:16:44 +00002472 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002473 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002474 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002475 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2476 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002477 .thenReturn(true);
2478 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2479
2480 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002481 }
Victor Chang3e794af2016-03-04 13:48:17 +00002482
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002483 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2484 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002485 mContext.packageName = admin1.getPackageName();
2486 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002487 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2488 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2489 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2490 false /* because of non-split user */);
2491 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2492 false /* because of non-split user */);
2493 }
2494
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002495 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002496 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002497 setup_nonSplitUser_firstBoot_primaryUser();
2498 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2499 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2500 DevicePolicyManager.CODE_OK);
2501 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2502 DevicePolicyManager.CODE_OK);
2503 assertCheckProvisioningPreCondition(
2504 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2505 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2506 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2507 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2508 }
2509
Esteban Talavera01576862016-12-15 11:16:44 +00002510 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002511 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002512 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002513 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2514 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002515 .thenReturn(true);
2516 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2517
2518 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002519 }
Victor Chang3e794af2016-03-04 13:48:17 +00002520
Nicolas Prevot45d29072017-01-18 16:11:19 +00002521 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2522 setDeviceOwner();
2523 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2524 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2525 }
2526
2527 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2528 setup_nonSplitUser_withDo_primaryUser();
2529 final int MANAGED_PROFILE_USER_ID = 18;
2530 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2531 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002532 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002533 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002534 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002535 true)).thenReturn(true);
2536 }
2537
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002538 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2539 throws Exception {
2540 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002541 mContext.packageName = admin1.getPackageName();
2542 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002543 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2544 false/* because of completed device setup */);
2545 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2546 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2547 false/* because of non-split user */);
2548 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2549 false/* because of non-split user */);
2550 }
2551
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002552 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2553 throws Exception {
2554 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2555 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2556 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2557 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2558 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2559 DevicePolicyManager.CODE_OK);
2560 assertCheckProvisioningPreCondition(
2561 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2562 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2563 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2564 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2565 }
2566
Nicolas Prevot45d29072017-01-18 16:11:19 +00002567 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2568 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002569 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002570 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2571
2572 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2573 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002574 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002575
2576 // COMP mode is allowed.
2577 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2578 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002579 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002580
Nicolas Prevot45d29072017-01-18 16:11:19 +00002581 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002582 assertCheckProvisioningPreCondition(
2583 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002584 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002585 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002586 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2587 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2588 }
Esteban Talavera01576862016-12-15 11:16:44 +00002589
Nicolas Prevot45d29072017-01-18 16:11:19 +00002590 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2591 setup_nonSplitUser_withDo_primaryUser();
2592 mContext.packageName = admin1.getPackageName();
2593 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2594 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2595 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002596 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002597 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2598 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2599 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002600 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002601 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2602 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2603 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2604 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2605 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002606 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002607 assertCheckProvisioningPreCondition(
2608 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002609 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002610 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002611 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2612 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2613 }
Esteban Talavera01576862016-12-15 11:16:44 +00002614
Nicolas Prevot45d29072017-01-18 16:11:19 +00002615 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2616 throws Exception {
2617 setup_nonSplitUser_withDo_primaryUser();
2618 mContext.packageName = admin1.getPackageName();
2619 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002620 // The DO should not be allowed to initiate provisioning if the restriction is set by
2621 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002622 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002623 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2624 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2625 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002626 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002627 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2628 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2629 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2630 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2631 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002632 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2633
2634 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002635 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002636 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002637 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002638 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2639 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2640 }
2641
2642 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2643 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2644 mContext.packageName = admin1.getPackageName();
2645 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2646
2647 // We can delete the managed profile to create a new one, so provisioning is allowed.
2648 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2649 DevicePolicyManager.CODE_OK);
2650 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2651 assertCheckProvisioningPreCondition(
2652 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2653 DpmMockContext.ANOTHER_PACKAGE_NAME,
2654 DevicePolicyManager.CODE_OK);
2655 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2656 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2657 }
2658
2659 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2660 throws Exception {
2661 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2662 mContext.packageName = admin1.getPackageName();
2663 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002664 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002665 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2666 eq(UserHandle.SYSTEM)))
2667 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002668 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002669 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2670 eq(UserHandle.SYSTEM)))
2671 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002672
2673 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002674 assertCheckProvisioningPreCondition(
2675 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2676 DpmMockContext.ANOTHER_PACKAGE_NAME,
2677 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2678 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2679 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002680
2681 // But the device owner can still do it because it has set the restriction itself.
2682 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2683 DevicePolicyManager.CODE_OK);
2684 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002685 }
2686
2687 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002688 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002689 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002690 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2691 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002692 .thenReturn(false);
2693 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2694
2695 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002696 }
Victor Chang3e794af2016-03-04 13:48:17 +00002697
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002698 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2699 setup_splitUser_firstBoot_systemUser();
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, true);
2703 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2704 false /* because canAddMoreManagedProfiles returns false */);
2705 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2706 true);
2707 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2708 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002709 }
2710
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002711 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2712 throws Exception {
2713 setup_splitUser_firstBoot_systemUser();
2714 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2715 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2716 DevicePolicyManager.CODE_OK);
2717 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002718 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002719 assertCheckProvisioningPreCondition(
2720 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2721 DevicePolicyManager.CODE_OK);
2722 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2723 DevicePolicyManager.CODE_SYSTEM_USER);
2724 }
2725
Esteban Talavera01576862016-12-15 11:16:44 +00002726 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002727 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002728 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002729 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2730 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002731 .thenReturn(false);
2732 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2733
2734 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002735 }
Victor Chang3e794af2016-03-04 13:48:17 +00002736
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002737 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2738 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002739 mContext.packageName = admin1.getPackageName();
2740 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002741 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2742 true/* it's undefined behavior. Can be changed into false in the future */);
2743 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2744 false /* because canAddMoreManagedProfiles returns false */);
2745 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2746 true/* it's undefined behavior. Can be changed into false in the future */);
2747 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2748 false/* because calling uid is system user */);
2749 }
2750
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002751 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2752 throws Exception {
2753 setup_splitUser_afterDeviceSetup_systemUser();
2754 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2755 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2756 DevicePolicyManager.CODE_OK);
2757 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002758 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002759 assertCheckProvisioningPreCondition(
2760 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2761 DevicePolicyManager.CODE_OK);
2762 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2763 DevicePolicyManager.CODE_SYSTEM_USER);
2764 }
2765
Esteban Talavera01576862016-12-15 11:16:44 +00002766 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002767 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002768 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002769 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2770 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002771 true)).thenReturn(true);
2772 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2773
2774 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002775 }
Victor Chang3e794af2016-03-04 13:48:17 +00002776
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002777 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2778 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002779 mContext.packageName = admin1.getPackageName();
2780 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002781 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2782 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2784 true);
2785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002786 }
2787
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002788 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002789 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002790 setup_splitUser_firstBoot_primaryUser();
2791 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2792 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2793 DevicePolicyManager.CODE_OK);
2794 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2795 DevicePolicyManager.CODE_OK);
2796 assertCheckProvisioningPreCondition(
2797 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2798 DevicePolicyManager.CODE_OK);
2799 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2800 DevicePolicyManager.CODE_OK);
2801 }
2802
Esteban Talavera01576862016-12-15 11:16:44 +00002803 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002804 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002805 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002806 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2807 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002808 true)).thenReturn(true);
2809 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2810
2811 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002812 }
Victor Chang3e794af2016-03-04 13:48:17 +00002813
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002814 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2815 throws Exception {
2816 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002817 mContext.packageName = admin1.getPackageName();
2818 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002819 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2820 true/* it's undefined behavior. Can be changed into false in the future */);
2821 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2822 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2823 true/* it's undefined behavior. Can be changed into false in the future */);
2824 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2825 false/* because user setup completed */);
2826 }
2827
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002828 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002829 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002830 setup_splitUser_afterDeviceSetup_primaryUser();
2831 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2832 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2833 DevicePolicyManager.CODE_OK);
2834 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2835 DevicePolicyManager.CODE_OK);
2836 assertCheckProvisioningPreCondition(
2837 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2838 DevicePolicyManager.CODE_OK);
2839 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2840 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2841 }
2842
Esteban Talavera01576862016-12-15 11:16:44 +00002843 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002844 setDeviceOwner();
2845
Pavel Grafov75c0a892017-05-18 17:28:27 +01002846 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002847 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002848 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2849 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002850 .thenReturn(false);
2851 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2852
2853 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002854 }
Victor Chang3e794af2016-03-04 13:48:17 +00002855
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002856 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2857 throws Exception {
2858 setup_provisionManagedProfileWithDeviceOwner_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_PROFILE,
2862 false /* can't provision managed profile on system user */);
2863 }
2864
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002865 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002866 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002867 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2868 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2869 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2870 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2871 }
2872
2873 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002874 setDeviceOwner();
2875
Pavel Grafov75c0a892017-05-18 17:28:27 +01002876 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002877 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002878 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2879 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002880 true)).thenReturn(true);
2881 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2882
2883 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002884 }
Victor Chang3e794af2016-03-04 13:48:17 +00002885
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002886 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2887 throws Exception {
2888 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002889 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2890 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002891 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2892 }
2893
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002894 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002895 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002896 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2897 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002898
2899 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002900 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2901 DevicePolicyManager.CODE_OK);
2902 }
2903
2904 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002905 setDeviceOwner();
2906
Pavel Grafov75c0a892017-05-18 17:28:27 +01002907 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002908 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002909 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2910 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002911 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2912 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002913 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002914 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002915 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002916 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00002917 true)).thenReturn(true);
2918 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2919
2920 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002921 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002922
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002923 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2924 throws Exception {
2925 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002926 mContext.packageName = admin1.getPackageName();
2927 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002928 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2929 }
2930
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002931 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2932 throws Exception {
2933 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2934 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2935 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2936 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2937 }
2938
2939 public void testCheckProvisioningPreCondition_permission() {
2940 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002941 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2942 () -> dpm.checkProvisioningPreCondition(
2943 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002944 }
2945
Victor Chang3577ed22016-08-25 18:49:26 +01002946 public void testForceUpdateUserSetupComplete_permission() {
2947 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002948 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2949 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01002950 }
2951
2952 public void testForceUpdateUserSetupComplete_systemUser() {
2953 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2954 // GIVEN calling from user 20
2955 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002956 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2957 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01002958 }
2959
2960 public void testForceUpdateUserSetupComplete_userbuild() {
2961 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2962 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2963
2964 final int userId = UserHandle.USER_SYSTEM;
2965 // GIVEN userComplete is false in SettingsProvider
2966 setUserSetupCompleteForUser(false, userId);
2967
2968 // GIVEN userComplete is true in DPM
2969 DevicePolicyManagerService.DevicePolicyData userData =
2970 new DevicePolicyManagerService.DevicePolicyData(userId);
2971 userData.mUserSetupComplete = true;
2972 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2973
2974 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01002975 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01002976
2977 assertTrue(dpms.hasUserSetupCompleted());
2978
2979 dpm.forceUpdateUserSetupComplete();
2980
2981 // THEN the state in dpms is not changed
2982 assertTrue(dpms.hasUserSetupCompleted());
2983 }
2984
2985 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2986 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2987 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2988
2989 final int userId = UserHandle.USER_SYSTEM;
2990 // GIVEN userComplete is false in SettingsProvider
2991 setUserSetupCompleteForUser(false, userId);
2992
2993 // GIVEN userComplete is true in DPM
2994 DevicePolicyManagerService.DevicePolicyData userData =
2995 new DevicePolicyManagerService.DevicePolicyData(userId);
2996 userData.mUserSetupComplete = true;
2997 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2998
2999 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003000 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003001
3002 assertTrue(dpms.hasUserSetupCompleted());
3003
3004 dpm.forceUpdateUserSetupComplete();
3005
3006 // THEN the state in dpms is not changed
3007 assertFalse(dpms.hasUserSetupCompleted());
3008 }
3009
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003010 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003011 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003012 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003013
3014 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3015 runAsCaller(mAdmin1Context, dpms, dpm -> {
3016 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3017 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003018 }
3019
3020 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3021 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3022 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003023
3024 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3025 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003026 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003027 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3028 .thenReturn(true);
3029
3030 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003031 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003032
3033 // Enabling logging should not change the timestamp.
3034 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003035 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003036 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003037 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003038 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003039 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003040
3041 // Retrieving the logs should update the timestamp.
3042 final long beforeRetrieval = System.currentTimeMillis();
3043 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003044 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003045 final long afterRetrieval = System.currentTimeMillis();
3046 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3047 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3048
3049 // Retrieving the pre-boot logs should update the timestamp.
3050 Thread.sleep(2);
3051 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003052 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003053 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3054
3055 // Checking the timestamp again should not change it.
3056 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003057 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003058
3059 // Retrieving the logs again should update the timestamp.
3060 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003061 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003062 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3063
3064 // Disabling logging should not change the timestamp.
3065 Thread.sleep(2);
3066 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003067 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003068
3069 // Restarting the DPMS should not lose the timestamp.
3070 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003071 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003072
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003073 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3074 mContext.binder.callingUid = 1234567;
3075 mContext.callerPermissions.add(permission.MANAGE_USERS);
3076 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3077 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3078
3079 // System can retrieve the timestamp.
3080 mContext.binder.clearCallingIdentity();
3081 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3082
3083 // Removing the device owner should clear the timestamp.
3084 clearDeviceOwner();
3085 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003086 }
3087
3088 public void testGetLastBugReportRequestTime() throws Exception {
3089 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3090 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003091
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003092 mContext.packageName = admin1.getPackageName();
3093 mContext.applicationInfo = new ApplicationInfo();
3094 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3095 .thenReturn(Color.WHITE);
3096 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3097 anyObject())).thenReturn(Color.WHITE);
3098
Esteban Talaverad36dd152016-12-15 08:51:45 +00003099 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3100 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003101 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003102
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003103 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003104 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003105
3106 // Requesting a bug report should update the timestamp.
3107 final long beforeRequest = System.currentTimeMillis();
3108 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003109 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003110 final long afterRequest = System.currentTimeMillis();
3111 assertTrue(bugReportRequestTime >= beforeRequest);
3112 assertTrue(bugReportRequestTime <= afterRequest);
3113
3114 // Checking the timestamp again should not change it.
3115 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003116 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003117
3118 // Restarting the DPMS should not lose the timestamp.
3119 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003120 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003121
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003122 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3123 mContext.binder.callingUid = 1234567;
3124 mContext.callerPermissions.add(permission.MANAGE_USERS);
3125 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3126 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3127
3128 // System can retrieve the timestamp.
3129 mContext.binder.clearCallingIdentity();
3130 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3131
3132 // Removing the device owner should clear the timestamp.
3133 clearDeviceOwner();
3134 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003135 }
3136
3137 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3138 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3139 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003140 mContext.packageName = admin1.getPackageName();
3141 mContext.applicationInfo = new ApplicationInfo();
3142 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3143 .thenReturn(Color.WHITE);
3144 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3145 anyObject())).thenReturn(Color.WHITE);
3146
3147 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3148 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003149 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
3150 when(getServices().iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003151 .thenReturn(true);
3152
3153 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003154 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003155
3156 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3157 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003158 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003159
3160 // Enabling logging should not change the timestamp.
3161 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003162 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003163
3164 // Retrieving the logs should update the timestamp.
3165 final long beforeRetrieval = System.currentTimeMillis();
3166 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003167 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003168 final long afterRetrieval = System.currentTimeMillis();
3169 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3170 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3171
3172 // Checking the timestamp again should not change it.
3173 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003174 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003175
3176 // Retrieving the logs again should update the timestamp.
3177 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003178 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003179 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3180
3181 // Disabling logging should not change the timestamp.
3182 Thread.sleep(2);
3183 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003184 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003185
3186 // Restarting the DPMS should not lose the timestamp.
3187 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003188 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3189
3190 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3191 mContext.binder.callingUid = 1234567;
3192 mContext.callerPermissions.add(permission.MANAGE_USERS);
3193 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3194 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3195
3196 // System can retrieve the timestamp.
3197 mContext.binder.clearCallingIdentity();
3198 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3199
3200 // Removing the device owner should clear the timestamp.
3201 clearDeviceOwner();
3202 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003203 }
3204
Tony Mak2f26b792016-11-28 17:54:51 +00003205 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3206 // Setup device owner.
3207 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3208 setupDeviceOwner();
3209
3210 // Only device owner is setup, the result list should be empty.
3211 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3212 MoreAsserts.assertEmpty(targetUsers);
3213
3214 // Setup a managed profile managed by the same admin.
3215 final int MANAGED_PROFILE_USER_ID = 15;
3216 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3217 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3218
3219 // Add a secondary user, it should never talk with.
3220 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003221 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003222
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003223 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3224 // other.
3225 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3226 MoreAsserts.assertEmpty(targetUsers);
3227
3228 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3229 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3230 MoreAsserts.assertEmpty(targetUsers);
3231
3232 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003233 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003234 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3235 dpm.setAffiliationIds(admin1, userAffiliationIds);
3236
3237 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3238 dpm.setAffiliationIds(admin1, userAffiliationIds);
3239
Tony Mak2f26b792016-11-28 17:54:51 +00003240 // Calling from device owner admin, the result list should just contain the managed
3241 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003242 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003243 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3244 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3245
3246 // Calling from managed profile admin, the result list should just contain the system
3247 // user id.
3248 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3249 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3250 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003251
3252 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003253 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003254
3255 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3256 // to each other.
3257 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3258 MoreAsserts.assertEmpty(targetUsers);
3259
3260 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3261 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3262 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003263 }
3264
3265 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3266 // Setup a device owner.
3267 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3268 setupDeviceOwner();
3269
3270 // Set up a managed profile managed by different package.
3271 final int MANAGED_PROFILE_USER_ID = 15;
3272 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3273 final ComponentName adminDifferentPackage =
3274 new ComponentName("another.package", "whatever.class");
3275 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3276
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003277 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003278 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003279 dpm.setAffiliationIds(admin1, userAffiliationIds);
3280
3281 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3282 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3283
Tony Mak2f26b792016-11-28 17:54:51 +00003284 // Calling from device owner admin, we should get zero bind device admin target users as
3285 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003286 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003287 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3288 MoreAsserts.assertEmpty(targetUsers);
3289
3290 // Calling from managed profile admin, we should still get zero target users for the same
3291 // reason.
3292 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3293 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3294 MoreAsserts.assertEmpty(targetUsers);
3295 }
3296
Esteban Talaverabdcada92017-02-01 14:20:06 +00003297 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3298 // Setup a device owner.
3299 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3300 setupDeviceOwner();
3301 // Lock task packages are updated when loading user data.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003302 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003303 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3304
3305 // Set up a managed profile managed by different package (package name shouldn't matter)
3306 final int MANAGED_PROFILE_USER_ID = 15;
3307 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3308 final ComponentName adminDifferentPackage =
3309 new ComponentName("another.package", "whatever.class");
3310 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003311 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003312 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3313
3314 // The DO can still set lock task packages
3315 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3316 final String[] doPackages = {"doPackage1", "doPackage2"};
3317 dpm.setLockTaskPackages(admin1, doPackages);
3318 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3319 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3320 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003321 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003322 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3323
3324 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3325 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3326 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003327 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3328 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3329 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3330 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003331 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3332
3333 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003334 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003335 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3336 dpm.setAffiliationIds(admin1, userAffiliationIds);
3337
3338 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3339 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3340
3341 // Now the managed profile can set lock task packages.
3342 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3343 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3344 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3345 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003346 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003347 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3348
3349 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003350 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003351 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3352 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003353 verify(getServices().iactivityManager, times(2))
Esteban Talaverabdcada92017-02-01 14:20:06 +00003354 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3355
3356 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3357 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3358 }
3359
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003360 public void testIsDeviceManaged() throws Exception {
3361 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3362 setupDeviceOwner();
3363
3364 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3365 // find out that the device has a device owner.
3366 assertTrue(dpm.isDeviceManaged());
3367 mContext.binder.callingUid = 1234567;
3368 mContext.callerPermissions.add(permission.MANAGE_USERS);
3369 assertTrue(dpm.isDeviceManaged());
3370 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3371 mContext.binder.clearCallingIdentity();
3372 assertTrue(dpm.isDeviceManaged());
3373
3374 clearDeviceOwner();
3375
3376 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3377 // not have a device owner.
3378 mContext.binder.callingUid = 1234567;
3379 mContext.callerPermissions.add(permission.MANAGE_USERS);
3380 assertFalse(dpm.isDeviceManaged());
3381 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3382 mContext.binder.clearCallingIdentity();
3383 assertFalse(dpm.isDeviceManaged());
3384 }
3385
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003386 public void testDeviceOwnerOrganizationName() throws Exception {
3387 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3388 setupDeviceOwner();
3389
3390 dpm.setOrganizationName(admin1, "organization");
3391
3392 // Device owner can retrieve organization managing the device.
3393 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3394
3395 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3396 mContext.binder.callingUid = 1234567;
3397 mContext.callerPermissions.add(permission.MANAGE_USERS);
3398 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3399 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3400
3401 // System can retrieve organization managing the device.
3402 mContext.binder.clearCallingIdentity();
3403 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3404
3405 // Removing the device owner clears the organization managing the device.
3406 clearDeviceOwner();
3407 assertNull(dpm.getDeviceOwnerOrganizationName());
3408 }
3409
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003410 public void testWipeDataManagedProfile() throws Exception {
3411 final int MANAGED_PROFILE_USER_ID = 15;
3412 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3413 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3414 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3415
3416 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003417 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003418 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3419
3420 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003421 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003422 MANAGED_PROFILE_USER_ID);
3423 }
3424
3425 public void testWipeDataManagedProfileDisallowed() throws Exception {
3426 final int MANAGED_PROFILE_USER_ID = 15;
3427 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3428 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3429
3430 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003431 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003432 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3433
Pavel Grafov75c0a892017-05-18 17:28:27 +01003434 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003435 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3436 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3437 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3438 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003439 // The PO is not allowed to remove the profile if the user restriction was set on the
3440 // profile by the system
3441 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3442 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003443 }
3444
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003445 public void testWipeDataDeviceOwner() throws Exception {
3446 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003447 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003448 UserManager.DISALLOW_FACTORY_RESET,
3449 UserHandle.SYSTEM))
3450 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3451
3452 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003453 verify(getServices().recoverySystem).rebootWipeUserData(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003454 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3455 }
3456
3457 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3458 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003459 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003460 UserManager.DISALLOW_FACTORY_RESET,
3461 UserHandle.SYSTEM))
3462 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003463 // The DO is not allowed to wipe the device if the user restriction was set
3464 // by the system
3465 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3466 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003467 }
3468
3469 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3470 final int MANAGED_PROFILE_USER_ID = 15;
3471 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3472 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3473
3474 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003475 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003476 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3477
Pavel Grafov75c0a892017-05-18 17:28:27 +01003478 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003479 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3480 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3481 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3482
3483 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3484 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3485
3486 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3487 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3488 // Failed password attempts on the parent user are taken into account, as there isn't a
3489 // separate work challenge.
3490 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3491 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3492 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3493
3494 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3495 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003496 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003497 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003498 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003499 }
3500
3501 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3502 throws Exception {
3503 final int MANAGED_PROFILE_USER_ID = 15;
3504 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3505 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3506
3507 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003508 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003509 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3510
Pavel Grafov75c0a892017-05-18 17:28:27 +01003511 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003512 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3513 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3514 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3515
3516 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3517 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3518
3519 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3520 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3521 // Failed password attempts on the parent user are taken into account, as there isn't a
3522 // separate work challenge.
3523 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3524 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3525 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3526
3527 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3528 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003529 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003530 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003531 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003532 }
3533
3534 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3535 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003536 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003537 UserManager.DISALLOW_FACTORY_RESET,
3538 UserHandle.SYSTEM))
3539 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3540
3541 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3542
3543 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3544 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3545 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3546 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3547 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3548
3549 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3550 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003551 verify(getServices().recoverySystem).rebootWipeUserData(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003552 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3553 }
3554
3555 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3556 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003557 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003558 UserManager.DISALLOW_FACTORY_RESET,
3559 UserHandle.SYSTEM))
3560 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3561
3562 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3563
3564 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3565 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3566 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3567 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3568 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3569
3570 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003571 verifyZeroInteractions(getServices().recoverySystem);
3572 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003573 .removeUserEvenWhenDisallowed(anyInt());
3574 }
3575
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003576 public void testGetPermissionGrantState() throws Exception {
3577 final String permission = "some.permission";
3578 final String app1 = "com.example.app1";
3579 final String app2 = "com.example.app2";
3580
Pavel Grafov75c0a892017-05-18 17:28:27 +01003581 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003582 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003583 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003584 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003585 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003586 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3587 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003588 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003589 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003590 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003591 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003592 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003593 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3594
3595 // System can retrieve permission grant state.
3596 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003597 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003598 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3599 dpm.getPermissionGrantState(null, app1, permission));
3600 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3601 dpm.getPermissionGrantState(null, app2, permission));
3602
3603 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003604 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3605 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003606 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3607 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003608
3609 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003610 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3611 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003612 setAsProfileOwner(admin1);
3613 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3614 dpm.getPermissionGrantState(admin1, app1, permission));
3615 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3616 dpm.getPermissionGrantState(admin1, app2, permission));
3617 }
3618
Rubin Xuaab7a412016-12-30 21:13:29 +00003619 public void testResetPasswordWithToken() throws Exception {
3620 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3621 setupDeviceOwner();
3622 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003623 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3624 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3625
Rubin Xuaab7a412016-12-30 21:13:29 +00003626 // test adding a token
3627 final byte[] token = new byte[32];
3628 final long handle = 123456;
3629 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003630 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003631 .thenReturn(handle);
3632 assertTrue(dpm.setResetPasswordToken(admin1, token));
3633
3634 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003635 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003636 .thenReturn(true);
3637 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3638
3639 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003640 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xuaab7a412016-12-30 21:13:29 +00003641 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3642 eq(UserHandle.USER_SYSTEM)))
3643 .thenReturn(true);
3644 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3645
3646 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003647 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003648 .thenReturn(true);
3649 assertTrue(dpm.clearResetPasswordToken(admin1));
3650 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003651
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003652 public void testIsActivePasswordSufficient() throws Exception {
3653 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3654 mContext.packageName = admin1.getPackageName();
3655 setupDeviceOwner();
3656
3657 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3658 dpm.setPasswordMinimumLength(admin1, 8);
3659 dpm.setPasswordMinimumLetters(admin1, 6);
3660 dpm.setPasswordMinimumLowerCase(admin1, 3);
3661 dpm.setPasswordMinimumUpperCase(admin1, 1);
3662 dpm.setPasswordMinimumNonLetter(admin1, 1);
3663 dpm.setPasswordMinimumNumeric(admin1, 1);
3664 dpm.setPasswordMinimumSymbols(admin1, 0);
3665
3666 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3667 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3668 8, 2,
3669 6, 1,
3670 0, 1);
3671
3672 setActivePasswordState(passwordMetricsNoSymbols);
3673 assertTrue(dpm.isActivePasswordSufficient());
3674
3675 initializeDpms();
3676 reset(mContext.spiedContext);
3677 assertTrue(dpm.isActivePasswordSufficient());
3678
3679 // This call simulates the user entering the password for the first time after a reboot.
3680 // This causes password metrics to be reloaded into memory. Until this happens,
3681 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3682 // even if the DPC changes password requirements so that the password no longer meets the
3683 // requirements. This is a known limitation of the current implementation of
3684 // isActivePasswordSufficient() - see b/34218769.
3685 setActivePasswordState(passwordMetricsNoSymbols);
3686 assertTrue(dpm.isActivePasswordSufficient());
3687
3688 dpm.setPasswordMinimumSymbols(admin1, 1);
3689 // This assertion would fail if we had not called setActivePasswordState() again after
3690 // initializeDpms() - see previous comment.
3691 assertFalse(dpm.isActivePasswordSufficient());
3692
3693 initializeDpms();
3694 reset(mContext.spiedContext);
3695 assertFalse(dpm.isActivePasswordSufficient());
3696
3697 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3698 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3699 7, 2,
3700 5, 1,
3701 1, 2);
3702
3703 setActivePasswordState(passwordMetricsWithSymbols);
3704 assertTrue(dpm.isActivePasswordSufficient());
3705 }
3706
Pavel Grafov75c0a892017-05-18 17:28:27 +01003707 private void setActivePasswordState(PasswordMetrics passwordMetrics)
3708 throws Exception {
3709 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003710 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003711
Pavel Grafov75c0a892017-05-18 17:28:27 +01003712 dpm.setActivePasswordState(passwordMetrics, userHandle);
3713 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003714
Pavel Grafov75c0a892017-05-18 17:28:27 +01003715 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3716 intent.setComponent(admin1);
3717 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3718
3719 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3720 MockUtils.checkIntent(intent),
3721 MockUtils.checkUserHandle(userHandle));
3722
3723 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
3724 // let it finish with system uid, otherwise it will throw and crash.
3725 flushTasks();
3726
3727 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003728 }
3729
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003730 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3731 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3732 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3733 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3734 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3735 DpmMockContext.SYSTEM_UID);
3736 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3737 DpmMockContext.SYSTEM_UID);
3738
3739 // Set up a device owner.
3740 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003741 setupDeviceOwner();
3742
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003743 // First and second user set IMEs manually.
3744 mContext.binder.callingUid = firstUserSystemUid;
3745 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3746 mContext.binder.callingUid = secondUserSystemUid;
3747 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003748
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003749 // Device owner changes IME for first user.
3750 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003751 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003752 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003753 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003754 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003755 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003756 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003757 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3758 mContext.binder.callingUid = firstUserSystemUid;
3759 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3760 mContext.binder.callingUid = secondUserSystemUid;
3761 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003762
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003763 // Second user changes IME manually.
3764 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3765 mContext.binder.callingUid = firstUserSystemUid;
3766 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3767 mContext.binder.callingUid = secondUserSystemUid;
3768 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003769
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003770 // First user changes IME manually.
3771 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3772 mContext.binder.callingUid = firstUserSystemUid;
3773 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3774 mContext.binder.callingUid = secondUserSystemUid;
3775 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003776
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003777 // Device owner changes IME for first user again.
3778 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003779 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003780 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003781 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003782 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003783 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003784 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3785 mContext.binder.callingUid = firstUserSystemUid;
3786 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3787 mContext.binder.callingUid = secondUserSystemUid;
3788 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003789
3790 // Restarting the DPMS should not lose information.
3791 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003792 mContext.binder.callingUid = firstUserSystemUid;
3793 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3794 mContext.binder.callingUid = secondUserSystemUid;
3795 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003796
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003797 // Device owner can find out whether it set the current IME itself.
3798 mContext.binder.callingUid = deviceOwnerUid;
3799 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003800
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003801 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003802 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003803 mContext.binder.callingUid = firstUserSystemUid;
3804 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3805 mContext.binder.callingUid = secondUserSystemUid;
3806 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003807 }
3808
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003809 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3810 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3811 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3812 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3813 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3814 DpmMockContext.SYSTEM_UID);
3815 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3816 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003817
3818 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003819 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003820 setupProfileOwner();
3821
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003822 // First and second user set IMEs manually.
3823 mContext.binder.callingUid = firstUserSystemUid;
3824 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3825 mContext.binder.callingUid = secondUserSystemUid;
3826 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003827
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003828 // Profile owner changes IME for second user.
3829 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003830 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003831 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003832 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003833 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003834 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003835 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003836 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3837 mContext.binder.callingUid = firstUserSystemUid;
3838 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3839 mContext.binder.callingUid = secondUserSystemUid;
3840 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003841
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003842 // First user changes IME manually.
3843 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3844 mContext.binder.callingUid = firstUserSystemUid;
3845 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3846 mContext.binder.callingUid = secondUserSystemUid;
3847 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003848
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003849 // Second user changes IME manually.
3850 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3851 mContext.binder.callingUid = firstUserSystemUid;
3852 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3853 mContext.binder.callingUid = secondUserSystemUid;
3854 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003855
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003856 // Profile owner changes IME for second user again.
3857 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003858 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003859 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003860 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003861 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003862 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003863 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3864 mContext.binder.callingUid = firstUserSystemUid;
3865 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3866 mContext.binder.callingUid = secondUserSystemUid;
3867 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003868
3869 // Restarting the DPMS should not lose information.
3870 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003871 mContext.binder.callingUid = firstUserSystemUid;
3872 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3873 mContext.binder.callingUid = secondUserSystemUid;
3874 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003875
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003876 // Profile owner can find out whether it set the current IME itself.
3877 mContext.binder.callingUid = profileOwnerUid;
3878 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003879
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003880 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003881 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003882 mContext.binder.callingUid = firstUserSystemUid;
3883 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3884 mContext.binder.callingUid = secondUserSystemUid;
3885 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003886 }
Rubin Xuaab7a412016-12-30 21:13:29 +00003887
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003888 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
3889 throws Exception {
3890 // Set up a device owner.
3891 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3892 setupDeviceOwner();
3893 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3894 }
3895
3896 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
3897 throws Exception {
3898 // Set up a profile owner.
3899 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3900 setupProfileOwner();
3901 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3902 }
3903
3904 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
3905 int adminUid) throws Exception {
3906 mContext.binder.callingUid = adminUid;
3907 final int userId = UserHandle.getUserId(adminUid);
3908
3909 final String packageName = "some.package";
3910 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
3911 admin1, Collections.singletonList(packageName)));
3912 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3913
3914 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3915 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
3916
3917 // Attempt to set to empty list (which means no listener is whitelisted)
3918 mContext.binder.callingUid = adminUid;
3919 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01003920 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003921 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3922
3923 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3924 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
3925 }
3926
3927 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
3928 // Set up a managed profile
3929 final int MANAGED_PROFILE_USER_ID = 15;
3930 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3931 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3932 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3933
3934 final String permittedListener = "some.package";
3935 setupPackageInPackageManager(
3936 permittedListener,
3937 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3938 /*appId=*/ 12345, /*flags=*/ 0);
3939
3940 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
3941 admin1, Collections.singletonList(permittedListener)));
3942
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003943 // isNotificationListenerServicePermitted should throw if not called from System.
3944 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3945 () -> dpms.isNotificationListenerServicePermitted(
3946 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003947
3948 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3949 assertTrue(dpms.isNotificationListenerServicePermitted(
3950 permittedListener, MANAGED_PROFILE_USER_ID));
3951 }
3952
3953 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
3954 throws Exception {
3955 // Set up a managed profile
3956 final int MANAGED_PROFILE_USER_ID = 15;
3957 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3958 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3959 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3960
3961 final String permittedListener = "permitted.package";
3962 int appId = 12345;
3963 setupPackageInPackageManager(
3964 permittedListener,
3965 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3966 appId, /*flags=*/ 0);
3967
3968 final String notPermittedListener = "not.permitted.package";
3969 setupPackageInPackageManager(
3970 notPermittedListener,
3971 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3972 ++appId, /*flags=*/ 0);
3973
3974 final String systemListener = "system.package";
3975 setupPackageInPackageManager(
3976 systemListener,
3977 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3978 ++appId, ApplicationInfo.FLAG_SYSTEM);
3979
3980 // By default all packages are allowed
3981 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3982
3983 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3984 assertTrue(dpms.isNotificationListenerServicePermitted(
3985 permittedListener, MANAGED_PROFILE_USER_ID));
3986 assertTrue(dpms.isNotificationListenerServicePermitted(
3987 notPermittedListener, MANAGED_PROFILE_USER_ID));
3988 assertTrue(dpms.isNotificationListenerServicePermitted(
3989 systemListener, MANAGED_PROFILE_USER_ID));
3990
3991 // Setting only one package in the whitelist
3992 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3993 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
3994 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003995 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003996 dpms.getPermittedCrossProfileNotificationListeners(admin1);
3997 assertEquals(1, permittedListeners.size());
3998 assertEquals(permittedListener, permittedListeners.get(0));
3999
4000 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4001 assertTrue(dpms.isNotificationListenerServicePermitted(
4002 permittedListener, MANAGED_PROFILE_USER_ID));
4003 assertFalse(dpms.isNotificationListenerServicePermitted(
4004 notPermittedListener, MANAGED_PROFILE_USER_ID));
4005 // System packages are always allowed (even if not in the whitelist)
4006 assertTrue(dpms.isNotificationListenerServicePermitted(
4007 systemListener, MANAGED_PROFILE_USER_ID));
4008
4009 // Setting an empty whitelist - only system listeners allowed
4010 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4011 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004012 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004013 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4014
4015 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4016 assertFalse(dpms.isNotificationListenerServicePermitted(
4017 permittedListener, MANAGED_PROFILE_USER_ID));
4018 assertFalse(dpms.isNotificationListenerServicePermitted(
4019 notPermittedListener, MANAGED_PROFILE_USER_ID));
4020 // System packages are always allowed (even if not in the whitelist)
4021 assertTrue(dpms.isNotificationListenerServicePermitted(
4022 systemListener, MANAGED_PROFILE_USER_ID));
4023
4024 // Setting a null whitelist - all listeners allowed
4025 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4026 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4027 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4028
4029 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4030 assertTrue(dpms.isNotificationListenerServicePermitted(
4031 permittedListener, MANAGED_PROFILE_USER_ID));
4032 assertTrue(dpms.isNotificationListenerServicePermitted(
4033 notPermittedListener, MANAGED_PROFILE_USER_ID));
4034 assertTrue(dpms.isNotificationListenerServicePermitted(
4035 systemListener, MANAGED_PROFILE_USER_ID));
4036 }
4037
4038 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4039 throws Exception {
4040 // Set up a managed profile
4041 final int MANAGED_PROFILE_USER_ID = 15;
4042 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4043 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4044 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4045
4046 final String nonSystemPackage = "non.system.package";
4047 int appId = 12345;
4048 setupPackageInPackageManager(
4049 nonSystemPackage,
4050 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4051 appId, /*flags=*/ 0);
4052
4053 final String systemListener = "system.package";
4054 setupPackageInPackageManager(
4055 systemListener,
4056 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4057 ++appId, ApplicationInfo.FLAG_SYSTEM);
4058
4059 // By default all packages are allowed (for all profiles)
4060 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4061
4062 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4063 assertTrue(dpms.isNotificationListenerServicePermitted(
4064 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4065 assertTrue(dpms.isNotificationListenerServicePermitted(
4066 systemListener, MANAGED_PROFILE_USER_ID));
4067 assertTrue(dpms.isNotificationListenerServicePermitted(
4068 nonSystemPackage, UserHandle.USER_SYSTEM));
4069 assertTrue(dpms.isNotificationListenerServicePermitted(
4070 systemListener, UserHandle.USER_SYSTEM));
4071
4072 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4073 // all allowed in primary profile
4074 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4075 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004076 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004077 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4078
4079 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4080 assertFalse(dpms.isNotificationListenerServicePermitted(
4081 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4082 assertTrue(dpms.isNotificationListenerServicePermitted(
4083 systemListener, MANAGED_PROFILE_USER_ID));
4084 assertTrue(dpms.isNotificationListenerServicePermitted(
4085 nonSystemPackage, UserHandle.USER_SYSTEM));
4086 assertTrue(dpms.isNotificationListenerServicePermitted(
4087 systemListener, UserHandle.USER_SYSTEM));
4088 }
4089
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004090 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004091 mServiceContext.packageName = mRealTestContext.getPackageName();
4092 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4093 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004094 setDeviceOwner();
4095
Pavel Grafov75c0a892017-05-18 17:28:27 +01004096 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004097 }
4098
4099 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004100 mServiceContext.packageName = mRealTestContext.getPackageName();
4101 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4102 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004103 setAsProfileOwner(admin1);
4104
Pavel Grafov75c0a892017-05-18 17:28:27 +01004105 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4106 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004107 }
4108
4109 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004110 mServiceContext.packageName = mRealTestContext.getPackageName();
4111 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4112 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004113 setAsProfileOwner(admin1);
4114
Pavel Grafov75c0a892017-05-18 17:28:27 +01004115 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4116 caller.packageName = "com.example.delegate";
4117 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4118 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004119
Pavel Grafov75c0a892017-05-18 17:28:27 +01004120 // Make caller a delegated cert installer.
4121 runAsCaller(mAdmin1Context, dpms,
4122 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004123
4124 verifyCanGetOwnerInstalledCaCerts(null, caller);
4125 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004126 }
4127
Robin Lee2c68dad2017-03-17 12:50:24 +00004128 private void verifyCanGetOwnerInstalledCaCerts(
4129 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004130 final String alias = "cert";
4131 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004132
4133 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004134 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004135 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4136 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004137 }
4138 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4139
4140 // caller: device admin or delegated certificate installer
4141 callerContext.applicationInfo = new ApplicationInfo();
4142 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4143
4144 // system_server
4145 final DpmMockContext serviceContext = mContext;
4146 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004147 getServices().addPackageContext(callerUser, admin1Context);
4148 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004149
4150 // Install a CA cert.
4151 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004152 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004153 .thenReturn(alias);
4154 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004155 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004156 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004157 });
4158
Pavel Grafov75c0a892017-05-18 17:28:27 +01004159 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4160 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4161 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004162 flushTasks();
4163
Robin Lee2c68dad2017-03-17 12:50:24 +00004164 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4165
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004166 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004167 runAsCaller(admin1Context, dpms, (dpm) -> {
4168 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004169 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004170 ownerInstalledCaCerts.addAll(installedCaCerts);
4171 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004172
4173 // Restarting the DPMS should not lose information.
4174 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004175 runAsCaller(admin1Context, dpms, (dpm) ->
4176 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004177
4178 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004179 runAsCaller(serviceContext, dpms, (dpm) -> {
4180 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004181
Robin Lee2c68dad2017-03-17 12:50:24 +00004182 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004183 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004184 });
4185
Pavel Grafov75c0a892017-05-18 17:28:27 +01004186 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4187 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4188 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004189 flushTasks();
4190
4191 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4192 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004193 runAsCaller(admin1Context, dpms, (dpm) -> {
4194 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4195 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004196 }
4197
Robin Lee2c68dad2017-03-17 12:50:24 +00004198 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4199 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004200 final String alias = "cert";
4201 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004202
4203 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004204 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004205 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4206 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004207 }
4208 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4209
4210 // caller: device admin or delegated certificate installer
4211 callerContext.applicationInfo = new ApplicationInfo();
4212 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4213
4214 // system_server
4215 final DpmMockContext serviceContext = mContext;
4216 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004217 getServices().addPackageContext(callerUser, admin1Context);
4218 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004219
4220 // Install a CA cert as caller
4221 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004222 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004223 .thenReturn(alias);
4224 assertTrue(dpm.installCaCert(callerName, caCert));
4225 });
4226
4227 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004228 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004229 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004230 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4231 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4232 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004233 flushTasks();
4234
Robin Lee2c68dad2017-03-17 12:50:24 +00004235 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004236 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004237
4238 runAsCaller(serviceContext, dpms, (dpm) -> {
4239 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4240 assertNotNull(ownerInstalledCaCerts);
4241 assertTrue(ownerInstalledCaCerts.isEmpty());
4242 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004243 }
4244
Victor Chang3e794af2016-03-04 13:48:17 +00004245 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004246 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004247 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4248 dpms.notifyChangeToContentObserver(
4249 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4250 }
4251
4252 private void assertProvisioningAllowed(String action, boolean expected) {
4253 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4254 dpm.isProvisioningAllowed(action));
4255 }
Tony Mak2f26b792016-11-28 17:54:51 +00004256
Nicolas Prevot45d29072017-01-18 16:11:19 +00004257 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4258 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004259 final String previousPackageName = mContext.packageName;
4260 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004261
4262 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4263 mContext.packageName = packageName;
4264 mMockContext.binder.callingUid = uid;
4265 assertProvisioningAllowed(action, expected);
4266
4267 // Set the previous package name / calling uid to go back to the initial state.
4268 mContext.packageName = previousPackageName;
4269 mMockContext.binder.callingUid = previousUid;
4270 }
4271
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004272 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004273 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4274 }
4275
4276 private void assertCheckProvisioningPreCondition(
4277 String action, String packageName, int provisioningCondition) {
4278 assertEquals("checkProvisioningPreCondition("
4279 + action + ", " + packageName + ") returning unexpected result",
4280 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004281 }
4282
Tony Mak2f26b792016-11-28 17:54:51 +00004283 /**
4284 * Setup a managed profile with the specified admin and its uid.
4285 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4286 * @param adminUid uid of the admin package.
4287 * @param copyFromAdmin package information for {@code admin} will be built based on this
4288 * component's information.
4289 */
4290 private void addManagedProfile(
4291 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4292 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004293 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004294 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4295 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4296 dpm.setActiveAdmin(admin, false, userId);
4297 assertTrue(dpm.setProfileOwner(admin, null, userId));
4298 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4299 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004300
4301 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004302 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004303 */
Robin Leeabaa0692017-02-20 20:54:22 +00004304 private static StringParceledListSlice asSlice(String[] s) {
4305 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004306 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004307
4308 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004309 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4310 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004311
Robin Lee2c68dad2017-03-17 12:50:24 +00004312 // We can't let exceptions happen on the background thread. Throw them here if they happen
4313 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004314 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004315 }
Victor Chang3e794af2016-03-04 13:48:17 +00004316}