blob: bad9b5b97e1f2098ddf09fb014815ed766dfafcb [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;
yinxuf4f9cec2017-06-19 10:28:19 -070020import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010021import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
22import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
23import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
24
Pavel Grafova1ea8d92017-05-25 21:55:24 +010025import static com.android.server.testutis.TestUtils.assertExpectException;
26
Pavel Grafov75c0a892017-05-18 17:28:27 +010027import static org.mockito.Matchers.any;
28import static org.mockito.Matchers.anyInt;
29import static org.mockito.Matchers.anyLong;
30import static org.mockito.Matchers.anyObject;
31import static org.mockito.Matchers.anyString;
32import static org.mockito.Matchers.eq;
33import static org.mockito.Matchers.isNull;
34import static org.mockito.Mockito.atLeast;
35import static org.mockito.Mockito.doAnswer;
36import static org.mockito.Mockito.doReturn;
Christine Franks361b8252017-06-23 18:12:46 -070037import static org.mockito.Mockito.mock;
Pavel Grafov75c0a892017-05-18 17:28:27 +010038import static org.mockito.Mockito.never;
39import static org.mockito.Mockito.nullable;
40import static org.mockito.Mockito.reset;
41import static org.mockito.Mockito.timeout;
42import static org.mockito.Mockito.times;
43import static org.mockito.Mockito.verify;
44import static org.mockito.Mockito.verifyZeroInteractions;
45import static org.mockito.Mockito.when;
46import static org.mockito.hamcrest.MockitoHamcrest.argThat;
47
Makoto Onukif76b06a2015-09-22 15:03:44 -070048import android.Manifest.permission;
49import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000050import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070051import android.app.admin.DeviceAdminReceiver;
52import android.app.admin.DevicePolicyManager;
53import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010054import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070055import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070056import android.content.ComponentName;
Christine Franks361b8252017-06-23 18:12:46 -070057import android.content.Context;
Tony Mak2f26b792016-11-28 17:54:51 +000058import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000059import android.content.pm.ApplicationInfo;
60import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061import android.content.pm.PackageManager;
Robin Leeabaa0692017-02-20 20:54:22 +000062import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000063import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010064import android.graphics.Color;
65import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080066import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080067import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070068import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080069import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070070import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070071import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080072import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010073import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000074import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080075import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000076import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010077import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070078import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070079
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010080import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000081import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000082import com.android.server.LocalServices;
83import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000084import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000085
Robin Lee7f5c91c2017-02-08 21:27:02 +000086import org.hamcrest.BaseMatcher;
87import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070088import org.mockito.invocation.InvocationOnMock;
89import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070090
Makoto Onukic8a5a552015-11-19 14:29:12 -080091import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000092import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000093import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070094import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070096import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010097import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000098import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070099
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700101 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000102 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103 m FrameworksServicesTests &&
104 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000105 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800107 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108
109 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000110 *
111 * , or:
112 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000114@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000116 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
117 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
118 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100119 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
120 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000121
Pavel Grafov75c0a892017-05-18 17:28:27 +0100122 // TODO replace all instances of this with explicit {@link #mServiceContext}.
123 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100125
126 private DpmMockContext mServiceContext;
127 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700128 public DevicePolicyManager dpm;
129 public DevicePolicyManagerServiceTestable dpms;
130
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100131 /*
132 * The CA cert below is the content of cacert.pem as generated by:
133 *
134 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
135 */
136 private static final String TEST_CA =
137 "-----BEGIN CERTIFICATE-----\n" +
138 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
139 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
140 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
141 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
142 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
143 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
144 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
145 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
146 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
147 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
148 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
149 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
150 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
151 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
152 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
153 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
154 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
155 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
156 "wQ==\n" +
157 "-----END CERTIFICATE-----\n";
158
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700159 @Override
160 protected void setUp() throws Exception {
161 super.setUp();
162
163 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100164 mServiceContext = mContext;
165 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
166 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700167 .thenReturn(true);
168
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800169 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100170 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800171
Makoto Onukia52562c2015-10-01 16:12:31 -0700172 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700173
Makoto Onukid932f762015-09-29 16:53:38 -0700174 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
175 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
176 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800177 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700178
Pavel Grafov75c0a892017-05-18 17:28:27 +0100179 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
180 mAdmin1Context.packageName = admin1.getPackageName();
181 mAdmin1Context.applicationInfo = new ApplicationInfo();
182 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
183
Makoto Onukib643fb02015-09-22 15:03:44 -0700184 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700185 }
186
Robin Lee2c68dad2017-03-17 12:50:24 +0000187 @Override
188 protected void tearDown() throws Exception {
189 flushTasks();
190 super.tearDown();
191 }
192
Makoto Onukia52562c2015-10-01 16:12:31 -0700193 private void initializeDpms() {
194 // Need clearCallingIdentity() to pass permission checks.
195 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100196 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700197
Pavel Grafov75c0a892017-05-18 17:28:27 +0100198 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
199 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
200 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700201
Pavel Grafov75c0a892017-05-18 17:28:27 +0100202 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700203
Pavel Grafov75c0a892017-05-18 17:28:27 +0100204 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700205 }
206
Makoto Onukib643fb02015-09-22 15:03:44 -0700207 private void setUpUserManager() {
208 // Emulate UserManager.set/getApplicationRestriction().
209 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
210
211 // UM.setApplicationRestrictions() will save to appRestrictions.
212 doAnswer(new Answer<Void>() {
213 @Override
214 public Void answer(InvocationOnMock invocation) throws Throwable {
215 String pkg = (String) invocation.getArguments()[0];
216 Bundle bundle = (Bundle) invocation.getArguments()[1];
217 UserHandle user = (UserHandle) invocation.getArguments()[2];
218
219 appRestrictions.put(Pair.create(pkg, user), bundle);
220
221 return null;
222 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100223 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100224 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700225
226 // UM.getApplicationRestrictions() will read from appRestrictions.
227 doAnswer(new Answer<Bundle>() {
228 @Override
229 public Bundle answer(InvocationOnMock invocation) throws Throwable {
230 String pkg = (String) invocation.getArguments()[0];
231 UserHandle user = (UserHandle) invocation.getArguments()[1];
232
233 return appRestrictions.get(Pair.create(pkg, user));
234 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100235 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700236 anyString(), any(UserHandle.class));
237
Makoto Onukid932f762015-09-29 16:53:38 -0700238 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100239 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700240 }
241
242 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100243 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700244
Pavel Grafov75c0a892017-05-18 17:28:27 +0100245 mServiceContext.binder.callingUid =
246 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
247 runAsCaller(mServiceContext, dpms, dpm -> {
248 // PO needs to be a DA.
249 dpm.setActiveAdmin(admin, /*replace=*/ false);
250 // Fire!
251 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
252 // Check
253 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
254 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700255
Pavel Grafov75c0a892017-05-18 17:28:27 +0100256 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700257 }
258
259 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100260 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700261 .thenReturn(false);
262
263 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100264 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700265
266 // If the device has no DPMS feature, it shouldn't register the local service.
267 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
268 }
269
270 /**
271 * Caller doesn't have proper permissions.
272 */
273 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700274 // 1. Failure cases.
275
276 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100277 assertExpectException(SecurityException.class, /* messageRegex= */ null,
278 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700279
280 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
281 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100282
283 assertExpectException(SecurityException.class, /* messageRegex= */ null,
284 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700285 }
286
Makoto Onukif76b06a2015-09-22 15:03:44 -0700287 /**
288 * Test for:
289 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800290 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700291 * {@link DevicePolicyManager#isAdminActive}
292 * {@link DevicePolicyManager#isAdminActiveAsUser}
293 * {@link DevicePolicyManager#getActiveAdmins}
294 * {@link DevicePolicyManager#getActiveAdminsAsUser}
295 */
296 public void testSetActiveAdmin() throws Exception {
297 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700298 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
299
Makoto Onukif76b06a2015-09-22 15:03:44 -0700300 // 2. Call the API.
301 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700302
303 // 3. Verify internal calls.
304
305 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700306 verify(mContext.spiedContext).sendBroadcastAsUser(
307 MockUtils.checkIntentAction(
308 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
309 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
310 verify(mContext.spiedContext).sendBroadcastAsUser(
311 MockUtils.checkIntentAction(
312 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700313 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
314
Pavel Grafov75c0a892017-05-18 17:28:27 +0100315 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700316 eq(admin1.getPackageName()),
317 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
318 eq(PackageManager.DONT_KILL_APP),
319 eq(DpmMockContext.CALLER_USER_HANDLE),
320 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700321
322 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700323
324 // Make sure it's active admin1.
325 assertTrue(dpm.isAdminActive(admin1));
326 assertFalse(dpm.isAdminActive(admin2));
327 assertFalse(dpm.isAdminActive(admin3));
328
329 // But not admin1 for a different user.
330
331 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
332 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
333 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
334
335 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
336 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
337
338 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
339
340 // Next, add one more admin.
341 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700342 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700343 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700344
345 dpm.setActiveAdmin(admin2, /* replace =*/ false);
346
347 // Now we have two admins.
348 assertTrue(dpm.isAdminActive(admin1));
349 assertTrue(dpm.isAdminActive(admin2));
350 assertFalse(dpm.isAdminActive(admin3));
351
352 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
353 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100354 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700355 eq(admin1.getPackageName()),
356 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
357 eq(PackageManager.DONT_KILL_APP),
358 eq(DpmMockContext.CALLER_USER_HANDLE),
359 anyString());
360
361 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100362 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
363 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700364
365 // 5. Add the same admin1 again with replace, which should succeed.
366 dpm.setActiveAdmin(admin1, /* replace =*/ true);
367
368 // TODO make sure it's replaced.
369
370 // 6. Test getActiveAdmins()
371 List<ComponentName> admins = dpm.getActiveAdmins();
372 assertEquals(2, admins.size());
373 assertEquals(admin1, admins.get(0));
374 assertEquals(admin2, admins.get(1));
375
376 // Another user has no admins.
377 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
378
379 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
380 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
381
382 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
383 }
384
Christine Franks361b8252017-06-23 18:12:46 -0700385 public void testCreateAndManageUser_demoUserSystemApp() throws Exception {
386 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
387
388 setDeviceOwner();
389
390 final int id = UserHandle.getUserId(DpmMockContext.CALLER_UID);
391
392 final UserInfo demoUserInfo = mock(UserInfo.class);
393 demoUserInfo.id = id;
394 doReturn(UserHandle.of(id)).when(demoUserInfo).getUserHandle();
395 doReturn(true).when(demoUserInfo).isDemo();
396 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
397 doReturn(demoUserInfo).when(um).getUserInfo(id);
398 doReturn(demoUserInfo).when(mContext.getUserManagerInternal())
399 .createUserEvenWhenDisallowed(anyString(), anyInt());
400
401 final ApplicationInfo applicationInfo = getServices().ipackageManager.getApplicationInfo(
402 admin2.getPackageName(), PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, id);
403 applicationInfo.flags = ApplicationInfo.FLAG_SYSTEM;
404 doReturn(applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
405 anyString(), anyInt(), anyInt());
406
407 final UserHandle userHandle = dpm.createAndManageUser(admin1, "", admin2, null, 0);
408
409 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
410 eq(admin2.getPackageName()),
411 eq(PackageManager.COMPONENT_ENABLED_STATE_ENABLED),
412 eq(PackageManager.DONT_KILL_APP),
413 eq(id),
414 anyString());
415
416 assertNotNull(userHandle);
417 }
418
419 public void testCreateAndManageUser_demoUserSystemUpdatedApp() throws Exception {
420 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
421
422 setDeviceOwner();
423
424 final int id = UserHandle.getUserId(DpmMockContext.CALLER_UID);
425
426 final UserInfo demoUserInfo = mock(UserInfo.class);
427 demoUserInfo.id = id;
428 doReturn(UserHandle.of(id)).when(demoUserInfo).getUserHandle();
429 doReturn(true).when(demoUserInfo).isDemo();
430 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
431 doReturn(demoUserInfo).when(um).getUserInfo(id);
432 doReturn(demoUserInfo).when(mContext.getUserManagerInternal())
433 .createUserEvenWhenDisallowed(anyString(), anyInt());
434
435 final ApplicationInfo applicationInfo = getServices().ipackageManager.getApplicationInfo(
436 admin2.getPackageName(), PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, id);
437 applicationInfo.flags = ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
438 doReturn(applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
439 anyString(), anyInt(), anyInt());
440
441 final UserHandle userHandle = dpm.createAndManageUser(admin1, "", admin2, null, 0);
442
443 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
444 eq(admin2.getPackageName()),
445 eq(PackageManager.COMPONENT_ENABLED_STATE_ENABLED),
446 eq(PackageManager.DONT_KILL_APP),
447 eq(id),
448 anyString());
449
450 assertNotNull(userHandle);
451 }
452
Makoto Onukid932f762015-09-29 16:53:38 -0700453 public void testSetActiveAdmin_multiUsers() throws Exception {
454
455 final int ANOTHER_USER_ID = 100;
456 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
457
Pavel Grafov75c0a892017-05-18 17:28:27 +0100458 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700459
460 // Set up pacakge manager for the other user.
461 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700462
463 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
464
465 dpm.setActiveAdmin(admin1, /* replace =*/ false);
466
467 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
468 dpm.setActiveAdmin(admin2, /* replace =*/ false);
469
470
471 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
472 assertTrue(dpm.isAdminActive(admin1));
473 assertFalse(dpm.isAdminActive(admin2));
474
475 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
476 assertFalse(dpm.isAdminActive(admin1));
477 assertTrue(dpm.isAdminActive(admin2));
478 }
479
Makoto Onukif76b06a2015-09-22 15:03:44 -0700480 /**
481 * Test for:
482 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800483 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700484 */
485 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
486 // 1. Make sure the caller has proper permissions.
487 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
488
489 dpm.setActiveAdmin(admin1, /* replace =*/ false);
490 assertTrue(dpm.isAdminActive(admin1));
491
492 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100493 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
494 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700495 }
496
497 /**
498 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800499 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
500 * BIND_DEVICE_ADMIN.
501 */
502 public void testSetActiveAdmin_permissionCheck() throws Exception {
503 // 1. Make sure the caller has proper permissions.
504 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
505
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100506 assertExpectException(IllegalArgumentException.class,
507 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
508 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800509 assertFalse(dpm.isAdminActive(adminNoPerm));
510
511 // Change the target API level to MNC. Now it can be set as DA.
512 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
513 VERSION_CODES.M);
514 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
515 assertTrue(dpm.isAdminActive(adminNoPerm));
516
517 // TODO Test the "load from the file" case where DA will still be loaded even without
518 // BIND_DEVICE_ADMIN and target API is N.
519 }
520
521 /**
522 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700523 * {@link DevicePolicyManager#removeActiveAdmin}
524 */
525 public void testRemoveActiveAdmin_SecurityException() {
526 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
527
528 // Add admin.
529
530 dpm.setActiveAdmin(admin1, /* replace =*/ false);
531
532 assertTrue(dpm.isAdminActive(admin1));
533
534 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
535
536 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100537 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
538 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700539
540 // Try to remove active admin with a different caller userid should fail too, without
541 // having MANAGE_DEVICE_ADMINS.
542 mContext.callerPermissions.clear();
543
Makoto Onukid932f762015-09-29 16:53:38 -0700544 // Change the caller, and call into DPMS directly with a different user-id.
545
Makoto Onukif76b06a2015-09-22 15:03:44 -0700546 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100547 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
548 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700549 }
550
551 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800552 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
553 * (because we can't send the remove broadcast).
554 */
555 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
556 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
557
558 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
559
560 // Add admin.
561
562 dpm.setActiveAdmin(admin1, /* replace =*/ false);
563
564 assertTrue(dpm.isAdminActive(admin1));
565
566 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
567
568 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100569 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800570 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100571 assertExpectException(IllegalStateException.class,
572 /* messageRegex= */ "User must be running and unlocked",
573 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800574
575 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
576
577 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100578 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800579 .thenReturn(true);
580
581 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700582 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800583 }
584
585 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700586 * Test for:
587 * {@link DevicePolicyManager#removeActiveAdmin}
588 */
Makoto Onukid932f762015-09-29 16:53:38 -0700589 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700590 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
591
592 // Add admin1.
593
594 dpm.setActiveAdmin(admin1, /* replace =*/ false);
595
596 assertTrue(dpm.isAdminActive(admin1));
597 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
598
599 // Different user, but should work, because caller has proper permissions.
600 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700601
602 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700603 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700604
605 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700606 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700607
608 // TODO DO Still can't be removed in this case.
609 }
610
611 /**
612 * Test for:
613 * {@link DevicePolicyManager#removeActiveAdmin}
614 */
615 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
616 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
617 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
618
619 // Add admin1.
620
621 dpm.setActiveAdmin(admin1, /* replace =*/ false);
622
623 assertTrue(dpm.isAdminActive(admin1));
624 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
625
626 // Broadcast from saveSettingsLocked().
627 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
628 MockUtils.checkIntentAction(
629 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
630 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
631
632 // Remove. No permissions, but same user, so it'll work.
633 mContext.callerPermissions.clear();
634 dpm.removeActiveAdmin(admin1);
635
Makoto Onukif76b06a2015-09-22 15:03:44 -0700636 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
637 MockUtils.checkIntentAction(
638 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
639 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
640 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700641 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700642 eq(dpms.mHandler),
643 eq(Activity.RESULT_OK),
644 isNull(String.class),
645 isNull(Bundle.class));
646
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700647 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700648
649 // Again broadcast from saveSettingsLocked().
650 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
651 MockUtils.checkIntentAction(
652 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
653 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
654
655 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700656 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700657
658 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000659 * Test for: @{link DevicePolicyManager#setActivePasswordState}
660 *
661 * Validates that when the password for a user changes, the notification broadcast intent
662 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
663 * addition to ones in the original user.
664 */
665 public void testSetActivePasswordState_sendToProfiles() throws Exception {
666 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
667
668 final int MANAGED_PROFILE_USER_ID = 78;
669 final int MANAGED_PROFILE_ADMIN_UID =
670 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
671
672 // Setup device owner.
673 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
674 mContext.packageName = admin1.getPackageName();
675 setupDeviceOwner();
676
677 // Add a managed profile belonging to the system user.
678 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
679
680 // Change the parent user's password.
681 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
682
683 // Both the device owner and the managed profile owner should receive this broadcast.
684 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
685 intent.setComponent(admin1);
686 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
687
688 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
689 MockUtils.checkIntent(intent),
690 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
691 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
692 MockUtils.checkIntent(intent),
693 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
694 }
695
696 /**
697 * Test for: @{link DevicePolicyManager#setActivePasswordState}
698 *
699 * Validates that when the password for a managed profile changes, the notification broadcast
700 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
701 * its parent.
702 */
703 public void testSetActivePasswordState_notSentToParent() throws Exception {
704 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
705
706 final int MANAGED_PROFILE_USER_ID = 78;
707 final int MANAGED_PROFILE_ADMIN_UID =
708 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
709
710 // Setup device owner.
711 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
712 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100713 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000714 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
715 setupDeviceOwner();
716
717 // Add a managed profile belonging to the system user.
718 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
719
720 // Change the profile's password.
721 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
722
723 // Both the device owner and the managed profile owner should receive this broadcast.
724 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
725 intent.setComponent(admin1);
726 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
727
728 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
729 MockUtils.checkIntent(intent),
730 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
731 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
732 MockUtils.checkIntent(intent),
733 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
734 }
735 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000736 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700737 */
738 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000739 setDeviceOwner();
740
741 // Try to set a profile owner on the same user, which should fail.
742 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
743 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100744 assertExpectException(IllegalStateException.class,
745 /* messageRegex= */ "already has a device owner",
746 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000747
748 // DO admin can't be deactivated.
749 dpm.removeActiveAdmin(admin1);
750 assertTrue(dpm.isAdminActive(admin1));
751
752 // TODO Test getDeviceOwnerName() too. To do so, we need to change
753 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
754 }
755
756 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700757 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800758 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700759 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
760 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
761
Makoto Onukid932f762015-09-29 16:53:38 -0700762 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700763 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
764
Makoto Onukid932f762015-09-29 16:53:38 -0700765 // Make sure admin1 is installed on system user.
766 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700767
Makoto Onukic8a5a552015-11-19 14:29:12 -0800768 // Check various get APIs.
769 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
770
Makoto Onukib643fb02015-09-22 15:03:44 -0700771 // DO needs to be an DA.
772 dpm.setActiveAdmin(admin1, /* replace =*/ false);
773
774 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700775 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700776
Makoto Onukic8a5a552015-11-19 14:29:12 -0800777 // getDeviceOwnerComponent should return the admin1 component.
778 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
779 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
780
781 // Check various get APIs.
782 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
783
784 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
785 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
786 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
787 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
788
789 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
790
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000791 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100792 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000793 eq(admin1.getPackageName()));
794
Makoto Onukib643fb02015-09-22 15:03:44 -0700795 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100796 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700797 eq(UserHandle.USER_SYSTEM), eq(false));
798
799 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
800 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
801 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
802
Makoto Onukic8a5a552015-11-19 14:29:12 -0800803 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700804 }
805
Makoto Onukic8a5a552015-11-19 14:29:12 -0800806 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
807 final int origCallingUser = mContext.binder.callingUid;
808 final List origPermissions = new ArrayList(mContext.callerPermissions);
809 mContext.callerPermissions.clear();
810
811 mContext.callerPermissions.add(permission.MANAGE_USERS);
812
813 mContext.binder.callingUid = Process.SYSTEM_UID;
814
815 // TODO Test getDeviceOwnerName() too. To do so, we need to change
816 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
817 if (hasDeviceOwner) {
818 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
819 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
820 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
821
822 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
823 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
824 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
825 } else {
826 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
827 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
828 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
829
830 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
831 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
832 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
833 }
834
835 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
836 if (hasDeviceOwner) {
837 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
838 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
839 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
840
841 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
842 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
843 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
844 } else {
845 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
846 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
847 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
848
849 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
850 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
851 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
852 }
853
854 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
855 // Still with MANAGE_USERS.
856 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
857 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
858 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
859
860 if (hasDeviceOwner) {
861 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
862 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
863 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
864 } else {
865 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
866 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
867 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
868 }
869
870 mContext.binder.callingUid = Process.SYSTEM_UID;
871 mContext.callerPermissions.remove(permission.MANAGE_USERS);
872 // System can still call "OnAnyUser" without MANAGE_USERS.
873 if (hasDeviceOwner) {
874 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
875 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
876 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
877
878 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
879 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
880 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
881 } else {
882 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
883 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
884 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
885
886 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
887 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
888 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
889 }
890
891 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
892 // Still no MANAGE_USERS.
893 if (hasDeviceOwner) {
894 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
895 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
896 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
897 } else {
898 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
899 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
900 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
901 }
902
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100903 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
904 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
905 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
906 dpm::getDeviceOwnerComponentOnAnyUser);
907 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
908 dpm::getDeviceOwnerUserId);
909 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
910 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800911
912 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
913 // Still no MANAGE_USERS.
914 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
915 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
916 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
917
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100918 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
919 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
920 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
921 dpm::getDeviceOwnerComponentOnAnyUser);
922 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
923 dpm::getDeviceOwnerUserId);
924 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
925 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800926
927 // Restore.
928 mContext.binder.callingUid = origCallingUser;
929 mContext.callerPermissions.addAll(origPermissions);
930 }
931
932
Makoto Onukib643fb02015-09-22 15:03:44 -0700933 /**
934 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
935 */
936 public void testSetDeviceOwner_noSuchPackage() {
937 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800938 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700939 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
940 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
941
942 // Call from a process on the system user.
943 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
944
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100945 assertExpectException(IllegalArgumentException.class,
946 /* messageRegex= */ "Invalid component",
947 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -0700948 }
949
950 public void testSetDeviceOwner_failures() throws Exception {
951 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
952 }
953
Makoto Onukia52562c2015-10-01 16:12:31 -0700954 public void testClearDeviceOwner() throws Exception {
955 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800956 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700957 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
958 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
959
960 // Set admin1 as a DA to the secondary user.
961 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
962
963 dpm.setActiveAdmin(admin1, /* replace =*/ false);
964
965 // Set admin 1 as the DO to the system user.
966
967 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
968 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
969 dpm.setActiveAdmin(admin1, /* replace =*/ false);
970 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
971
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000972 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100973 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000974 eq(admin1.getPackageName()));
975
Makoto Onukic8a5a552015-11-19 14:29:12 -0800976 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700977
Makoto Onuki90b89652016-01-28 14:44:18 -0800978 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100979 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +0000980 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800981
982 assertTrue(dpm.isAdminActive(admin1));
983 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
984
Makoto Onukia52562c2015-10-01 16:12:31 -0700985 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100986 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -0700987
988 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100989 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
990 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800991
992 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100993 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100994 assertExpectException(IllegalStateException.class,
995 /* messageRegex= */ "User must be running and unlocked",
996 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800997
Pavel Grafov75c0a892017-05-18 17:28:27 +0100998 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
999 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001000 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1001
1002 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001003 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001004
Pavel Grafov75c0a892017-05-18 17:28:27 +01001005 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001006 eq(false),
1007 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1008
Pavel Grafov75c0a892017-05-18 17:28:27 +01001009 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001010 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001011 eq(null),
1012 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001013
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001014 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001015
1016 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1017 // and once for clearing it.
1018 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1019 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1020 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001021 // TODO Check other calls.
1022 }
1023
1024 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1025 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001026 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001027 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1028 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1029
1030 // Set admin1 as a DA to the secondary user.
1031 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1032
1033 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1034
1035 // Set admin 1 as the DO to the system user.
1036
1037 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1038 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1039 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1040 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1041
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001042 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001043 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001044 eq(admin1.getPackageName()));
1045
Makoto Onukic8a5a552015-11-19 14:29:12 -08001046 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001047
1048 // Now call clear from the secondary user, which should throw.
1049 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1050
1051 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001052 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001053 eq(admin1.getPackageName()),
1054 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001055 assertExpectException(SecurityException.class,
1056 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1057 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001058
Makoto Onukic8a5a552015-11-19 14:29:12 -08001059 // DO shouldn't be removed.
1060 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001061 }
1062
Makoto Onukib643fb02015-09-22 15:03:44 -07001063 public void testSetProfileOwner() throws Exception {
1064 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001065
Makoto Onuki90b89652016-01-28 14:44:18 -08001066 // PO admin can't be deactivated.
1067 dpm.removeActiveAdmin(admin1);
1068 assertTrue(dpm.isAdminActive(admin1));
1069
Makoto Onuki803d6752015-10-30 12:58:39 -07001070 // Try setting DO on the same user, which should fail.
1071 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001072 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1073 runAsCaller(mServiceContext, dpms, dpm -> {
1074 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001075 assertExpectException(IllegalStateException.class,
1076 /* messageRegex= */ "already has a profile owner",
1077 () -> dpm.setDeviceOwner(admin2, "owner-name",
1078 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001079 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001080 }
1081
Makoto Onuki90b89652016-01-28 14:44:18 -08001082 public void testClearProfileOwner() throws Exception {
1083 setAsProfileOwner(admin1);
1084
1085 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1086
1087 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1088 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1089
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001090 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001091 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001092 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001093 assertExpectException(IllegalStateException.class,
1094 /* messageRegex= */ "User must be running and unlocked",
1095 () -> dpm.clearProfileOwner(admin1));
1096
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001097 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001098 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001099 dpm.clearProfileOwner(admin1);
1100
1101 // Check
1102 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001103 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001104 }
1105
Makoto Onukib643fb02015-09-22 15:03:44 -07001106 public void testSetProfileOwner_failures() throws Exception {
1107 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1108 }
1109
Makoto Onukia52562c2015-10-01 16:12:31 -07001110 public void testGetDeviceOwnerAdminLocked() throws Exception {
1111 checkDeviceOwnerWithMultipleDeviceAdmins();
1112 }
1113
1114 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1115 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1116 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1117 // make sure it gets the right component from the right user.
1118
1119 final int ANOTHER_USER_ID = 100;
1120 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1121
Pavel Grafov75c0a892017-05-18 17:28:27 +01001122 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001123
1124 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001125 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001126 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1127 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1128
1129 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1130
Pavel Grafov75c0a892017-05-18 17:28:27 +01001131 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001132
Makoto Onukia52562c2015-10-01 16:12:31 -07001133 // Make sure the admin packge is installed to each user.
1134 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1135 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1136
1137 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1138 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1139
1140 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1141
1142
1143 // Set active admins to the users.
1144 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1145 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1146
1147 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1148 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1149
1150 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1151
1152 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001153 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001154 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1155
Makoto Onukic8a5a552015-11-19 14:29:12 -08001156 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001157
1158 // Then check getDeviceOwnerAdminLocked().
1159 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1160 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1161 }
1162
1163 /**
1164 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001165 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1166 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001167 *
1168 * We didn't use to persist the DO component class name, but now we do, and the above method
1169 * finds the right component from a package name upon migration.
1170 */
1171 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001172 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001173 checkDeviceOwnerWithMultipleDeviceAdmins();
1174
1175 // Overwrite the device owner setting and clears the clas name.
1176 dpms.mOwners.setDeviceOwner(
1177 new ComponentName(admin2.getPackageName(), ""),
1178 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1179 dpms.mOwners.writeDeviceOwner();
1180
1181 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001182 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001183
1184 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001185 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001186 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001187 initializeDpms();
1188
1189 // Now the DO component name is a full name.
1190 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1191 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001192 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001193 }
1194
Makoto Onukib643fb02015-09-22 15:03:44 -07001195 public void testSetGetApplicationRestriction() {
1196 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001197 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001198
1199 {
1200 Bundle rest = new Bundle();
1201 rest.putString("KEY_STRING", "Foo1");
1202 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1203 }
1204
1205 {
1206 Bundle rest = new Bundle();
1207 rest.putString("KEY_STRING", "Foo2");
1208 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1209 }
1210
1211 {
1212 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1213 assertNotNull(returned);
1214 assertEquals(returned.size(), 1);
1215 assertEquals(returned.get("KEY_STRING"), "Foo1");
1216 }
1217
1218 {
1219 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1220 assertNotNull(returned);
1221 assertEquals(returned.size(), 1);
1222 assertEquals(returned.get("KEY_STRING"), "Foo2");
1223 }
1224
1225 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1226 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1227 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001228
Edman Anjosf9946772016-11-28 16:35:15 +01001229 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001230 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1231 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001232 *
1233 * @param packageName the name of the package to be setup
1234 * @param appId the application ID to be given to the package
1235 * @return the UID of the package as known by the mock package manager
1236 */
1237 private int setupPackageInPackageManager(final String packageName, final int appId)
1238 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001239 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001240 ApplicationInfo.FLAG_HAS_CODE);
1241 }
1242
1243 /**
1244 * Setup a package in the package manager mock. Useful for faking installed applications.
1245 *
1246 * @param packageName the name of the package to be setup
1247 * @param userId the user id where the package will be "installed"
1248 * @param appId the application ID to be given to the package
1249 * @param flags flags to set in the ApplicationInfo for this package
1250 * @return the UID of the package as known by the mock package manager
1251 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001252 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1253 int flags) throws Exception {
1254 final int uid = UserHandle.getUid(userId, appId);
1255 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001256 final PackageInfo pi = new PackageInfo();
1257 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001258 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001259 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001260 eq(packageName),
1261 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001262 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001263 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001264 eq(packageName),
1265 anyInt(),
1266 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001267 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001268 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001269 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001270 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001271 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001272 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001273 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001274 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001275 return uid;
1276 }
1277
Robin Lee7f5c91c2017-02-08 21:27:02 +00001278 public void testCertificateDisclosure() throws Exception {
1279 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1280 final UserHandle user = UserHandle.of(userId);
1281
1282 mContext.applicationInfo = new ApplicationInfo();
1283 mContext.callerPermissions.add(permission.MANAGE_USERS);
1284 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001285 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001286 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1287
Robin Leeabaa0692017-02-20 20:54:22 +00001288 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1289 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001290
1291 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1292 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1293
1294 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001295 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001296 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001297 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001298 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001299 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001300 .cancelAsUser(anyString(), anyInt(), eq(user));
1301
1302 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001303 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001304 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001305 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1306 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001307 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001308 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001309 .notifyAsUser(anyString(), anyInt(), argThat(
1310 new BaseMatcher<Notification>() {
1311 @Override
1312 public boolean matches(Object item) {
1313 final Notification noti = (Notification) item;
1314 return TEST_STRING.equals(
1315 noti.extras.getString(Notification.EXTRA_TITLE));
1316 }
1317 @Override
1318 public void describeTo(Description description) {
1319 description.appendText(
1320 "Notification{title=\"" + TEST_STRING + "\"}");
1321 }
1322 }), eq(user));
1323 }
1324
Edman Anjosf9946772016-11-28 16:35:15 +01001325 /**
1326 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1327 * privileges can acually be exercised by a delegate are not covered here.
1328 */
1329 public void testDelegation() throws Exception {
1330 setAsProfileOwner(admin1);
1331
1332 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1333
1334 // Given two packages
1335 final String CERT_DELEGATE = "com.delegate.certs";
1336 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1337 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1338 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1339 20989);
1340
1341 // On delegation
1342 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1343 mContext.packageName = admin1.getPackageName();
1344 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1345 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1346
1347 // DPMS correctly stores and retrieves the delegates
1348 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1349 assertEquals(2, policy.mDelegationMap.size());
1350 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1351 DELEGATION_CERT_INSTALL);
1352 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1353 DELEGATION_CERT_INSTALL);
1354 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1355 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1356 DELEGATION_APP_RESTRICTIONS);
1357 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1358 DELEGATION_APP_RESTRICTIONS);
1359 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1360
1361 // On calling install certificate APIs from an unauthorized process
1362 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1363 mContext.packageName = RESTRICTIONS_DELEGATE;
1364
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001365 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1366 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001367
1368 // On calling install certificate APIs from an authorized process
1369 mContext.binder.callingUid = CERT_DELEGATE_UID;
1370 mContext.packageName = CERT_DELEGATE;
1371
1372 // DPMS executes without a SecurityException
1373 try {
1374 dpm.installCaCert(null, null);
1375 } catch (SecurityException unexpected) {
1376 fail("Threw SecurityException on authorized access");
1377 } catch (NullPointerException expected) {
1378 }
1379
1380 // On removing a delegate
1381 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1382 mContext.packageName = admin1.getPackageName();
1383 dpm.setCertInstallerPackage(admin1, null);
1384
1385 // DPMS does not allow access to ex-delegate
1386 mContext.binder.callingUid = CERT_DELEGATE_UID;
1387 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001388 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1389 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001390
1391 // But still allows access to other existing delegates
1392 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1393 mContext.packageName = RESTRICTIONS_DELEGATE;
1394 try {
1395 dpm.getApplicationRestrictions(null, "pkg");
1396 } catch (SecurityException expected) {
1397 fail("Threw SecurityException on authorized access");
1398 }
1399 }
1400
Esteban Talaverabf60f722015-12-10 16:26:44 +00001401 public void testApplicationRestrictionsManagingApp() throws Exception {
1402 setAsProfileOwner(admin1);
1403
Rubin Xued1928a2016-02-11 17:23:06 +00001404 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001405 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001406 final String nonDelegateExceptionMessageRegex =
1407 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001408 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001409 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1410 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001411
Esteban Talaverabf60f722015-12-10 16:26:44 +00001412 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1413 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001414 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1415 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001416 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001417 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001418 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001419 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1420 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001421
1422 // Check via the profile owner that no restrictions were set.
1423 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001424 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001425 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1426
Rubin Xued1928a2016-02-11 17:23:06 +00001427 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001428 assertExpectException(PackageManager.NameNotFoundException.class,
1429 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1430 () -> dpm.setApplicationRestrictionsManagingPackage(
1431 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001432
Esteban Talaverabf60f722015-12-10 16:26:44 +00001433 // Let appRestrictionsManagerPackage manage app restrictions
1434 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1435 assertEquals(appRestrictionsManagerPackage,
1436 dpm.getApplicationRestrictionsManagingPackage(admin1));
1437
1438 // Now that package should be able to set and retrieve app restrictions.
1439 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001440 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001441 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1442 dpm.setApplicationRestrictions(null, "pkg1", rest);
1443 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1444 assertEquals(1, returned.size(), 1);
1445 assertEquals("Foo1", returned.get("KEY_STRING"));
1446
1447 // The same app running on a separate user shouldn't be able to manage app restrictions.
1448 mContext.binder.callingUid = UserHandle.getUid(
1449 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1450 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001451 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1452 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001453
1454 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1455 // too.
1456 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001457 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001458 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1459 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1460 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1461
1462 // Removing the ability for the package to manage app restrictions.
1463 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1464 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1465 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001466 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001467 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001468 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1469 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001470 }
1471
Makoto Onukia4f11972015-10-01 13:19:58 -07001472 public void testSetUserRestriction_asDo() throws Exception {
1473 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001474 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001475 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1476 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1477
1478 // First, set DO.
1479
1480 // Call from a process on the system user.
1481 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1482
1483 // Make sure admin1 is installed on system user.
1484 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001485
1486 // Call.
1487 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001488 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001489 UserHandle.USER_SYSTEM));
1490
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001491 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001492 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001493 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001494 DpmTestUtils.assertRestrictions(
1495 DpmTestUtils.newRestrictions(defaultRestrictions),
1496 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1497 );
1498 DpmTestUtils.assertRestrictions(
1499 DpmTestUtils.newRestrictions(defaultRestrictions),
1500 dpm.getUserRestrictions(admin1)
1501 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001502 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001503 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001504 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001505 eq(true) /* isDeviceOwner */,
1506 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001507 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001508 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001509
1510 for (String restriction : defaultRestrictions) {
1511 dpm.clearUserRestriction(admin1, restriction);
1512 }
1513
Esteban Talavera548a04b2016-12-20 15:22:30 +00001514 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001515 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001516
1517 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001518 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001519 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001520 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1521 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001522 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001523
Makoto Onukia4f11972015-10-01 13:19:58 -07001524 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001525 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001526 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001527 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1528 UserManager.DISALLOW_ADD_USER),
1529 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001530 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001531
Makoto Onuki068c54a2015-10-13 14:34:03 -07001532 DpmTestUtils.assertRestrictions(
1533 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001534 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001535 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1536 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001537 DpmTestUtils.assertRestrictions(
1538 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001539 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001540 dpm.getUserRestrictions(admin1)
1541 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001542
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001543 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001544 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001545 eq(UserHandle.USER_SYSTEM),
1546 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001547 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001548 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001549
Makoto Onuki068c54a2015-10-13 14:34:03 -07001550 DpmTestUtils.assertRestrictions(
1551 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1552 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1553 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001554 DpmTestUtils.assertRestrictions(
1555 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1556 dpm.getUserRestrictions(admin1)
1557 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001558
1559 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001560 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001561 eq(UserHandle.USER_SYSTEM),
1562 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001563 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001564 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001565
Esteban Talavera548a04b2016-12-20 15:22:30 +00001566 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001567
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001568 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1569 // DO sets them, the scope is global.
1570 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001571 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001572 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001573 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001574 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001575 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001576 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1577 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001578 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001579
1580 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1581 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001582 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001583
1584 // More tests.
1585 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001586 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001587 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001588 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1589 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001590 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001591
1592 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001593 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001594 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001595 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001596 UserManager.DISALLOW_ADD_USER),
1597 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001598 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001599
1600 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001601 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001602 eq(UserHandle.USER_SYSTEM),
1603 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001604 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001605 UserManager.DISALLOW_ADD_USER),
1606 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001607 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001608
1609 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1610 // locally.
1611 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001612 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001613
1614 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1615 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1616 dpm.setCameraDisabled(admin2, true);
1617
Pavel Grafov75c0a892017-05-18 17:28:27 +01001618 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001619 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001620 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001621 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001622 UserManager.DISALLOW_ADD_USER),
1623 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001624 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001625 // TODO Make sure restrictions are written to the file.
1626 }
1627
1628 public void testSetUserRestriction_asPo() {
1629 setAsProfileOwner(admin1);
1630
Makoto Onuki068c54a2015-10-13 14:34:03 -07001631 DpmTestUtils.assertRestrictions(
1632 DpmTestUtils.newRestrictions(),
1633 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1634 .ensureUserRestrictions()
1635 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001636
1637 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001638 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001639 eq(DpmMockContext.CALLER_USER_HANDLE),
1640 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001641 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001642 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001643
Makoto Onukia4f11972015-10-01 13:19:58 -07001644 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001645 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001646 eq(DpmMockContext.CALLER_USER_HANDLE),
1647 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1648 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001649 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001650 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001651
Makoto Onuki068c54a2015-10-13 14:34:03 -07001652 DpmTestUtils.assertRestrictions(
1653 DpmTestUtils.newRestrictions(
1654 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1655 UserManager.DISALLOW_OUTGOING_CALLS
1656 ),
1657 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1658 .ensureUserRestrictions()
1659 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001660 DpmTestUtils.assertRestrictions(
1661 DpmTestUtils.newRestrictions(
1662 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1663 UserManager.DISALLOW_OUTGOING_CALLS
1664 ),
1665 dpm.getUserRestrictions(admin1)
1666 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001667
1668 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001669 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001670 eq(DpmMockContext.CALLER_USER_HANDLE),
1671 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001672 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001673 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001674
1675 DpmTestUtils.assertRestrictions(
1676 DpmTestUtils.newRestrictions(
1677 UserManager.DISALLOW_OUTGOING_CALLS
1678 ),
1679 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1680 .ensureUserRestrictions()
1681 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001682 DpmTestUtils.assertRestrictions(
1683 DpmTestUtils.newRestrictions(
1684 UserManager.DISALLOW_OUTGOING_CALLS
1685 ),
1686 dpm.getUserRestrictions(admin1)
1687 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001688
1689 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001690 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001691 eq(DpmMockContext.CALLER_USER_HANDLE),
1692 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001693 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001694 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001695
Makoto Onuki068c54a2015-10-13 14:34:03 -07001696 DpmTestUtils.assertRestrictions(
1697 DpmTestUtils.newRestrictions(),
1698 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1699 .ensureUserRestrictions()
1700 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001701 DpmTestUtils.assertRestrictions(
1702 DpmTestUtils.newRestrictions(),
1703 dpm.getUserRestrictions(admin1)
1704 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001705
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1707 // though when DO sets them they'll be applied globally.
1708 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001709 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001711 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001712 eq(DpmMockContext.CALLER_USER_HANDLE),
1713 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1714 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001715 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001716 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001717
1718 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001719 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001721 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001723 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001724 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001725
Makoto Onukia4f11972015-10-01 13:19:58 -07001726 // TODO Make sure restrictions are written to the file.
1727 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001728
Esteban Talavera548a04b2016-12-20 15:22:30 +00001729
1730 public void testDefaultEnabledUserRestrictions() throws Exception {
1731 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1732 mContext.callerPermissions.add(permission.MANAGE_USERS);
1733 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1734 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1735
1736 // First, set DO.
1737
1738 // Call from a process on the system user.
1739 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1740
1741 // Make sure admin1 is installed on system user.
1742 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1743
1744 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1745 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1746 UserHandle.USER_SYSTEM));
1747
1748 // Check that the user restrictions that are enabled by default are set. Then unset them.
1749 String[] defaultRestrictions = UserRestrictionsUtils
1750 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1751 assertTrue(defaultRestrictions.length > 0);
1752 DpmTestUtils.assertRestrictions(
1753 DpmTestUtils.newRestrictions(defaultRestrictions),
1754 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1755 );
1756 DpmTestUtils.assertRestrictions(
1757 DpmTestUtils.newRestrictions(defaultRestrictions),
1758 dpm.getUserRestrictions(admin1)
1759 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001760 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001761 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001762 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001763 eq(true) /* isDeviceOwner */,
1764 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001765 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001766 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001767
1768 for (String restriction : defaultRestrictions) {
1769 dpm.clearUserRestriction(admin1, restriction);
1770 }
1771
1772 assertNoDeviceOwnerRestrictions();
1773
1774 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001775 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001776 initializeDpms();
1777 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1778 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1779
1780 assertNoDeviceOwnerRestrictions();
1781
1782 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1783 // is set as it wasn't enabled during setDeviceOwner.
1784 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1785 assertFalse(UserRestrictionsUtils
1786 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1787 UserRestrictionsUtils
1788 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1789 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001790 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001791 initializeDpms();
1792 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1793 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1794
1795 DpmTestUtils.assertRestrictions(
1796 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1797 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1798 );
1799 DpmTestUtils.assertRestrictions(
1800 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1801 dpm.getUserRestrictions(admin1)
1802 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001803 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001804 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001805 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001806 eq(true) /* isDeviceOwner */,
1807 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001808 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001809 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001810
1811 // Remove the restriction.
1812 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1813
1814 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1815 initializeDpms();
1816 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1817 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1818 assertNoDeviceOwnerRestrictions();
1819 } finally {
1820 UserRestrictionsUtils
1821 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1822 }
1823 }
1824
1825 private void assertNoDeviceOwnerRestrictions() {
1826 DpmTestUtils.assertRestrictions(
1827 DpmTestUtils.newRestrictions(),
1828 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1829 );
1830 DpmTestUtils.assertRestrictions(
1831 DpmTestUtils.newRestrictions(),
1832 dpm.getUserRestrictions(admin1)
1833 );
1834 }
1835
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001836 public void testGetMacAddress() throws Exception {
1837 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1838 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1839 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1840
1841 // In this test, change the caller user to "system".
1842 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1843
1844 // Make sure admin1 is installed on system user.
1845 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1846
1847 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001848 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1849 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001850
1851 // DO needs to be an DA.
1852 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1853 assertTrue(dpm.isAdminActive(admin1));
1854
1855 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001856 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1857 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001858
1859 // Test 3. Caller has PO, but not DO.
1860 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001861 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1862 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001863
1864 // Remove PO.
1865 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001866 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001867 // Test 4, Caller is DO now.
1868 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1869
1870 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001871 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001872
1873 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001874 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001875 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001876
1877 // 4-3. With a real MAC address.
1878 final WifiInfo wi = new WifiInfo();
1879 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001880 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001881 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001882 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001883
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001884 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001885 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1886 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1887
1888 // In this test, change the caller user to "system".
1889 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1890
1891 // Make sure admin1 is installed on system user.
1892 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1893
1894 // Set admin1 as DA.
1895 dpm.setActiveAdmin(admin1, false);
1896 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001897 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1898 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001899
1900 // Set admin1 as PO.
1901 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001902 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1903 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001904
1905 // Remove PO and add DO.
1906 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001907 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001908 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1909
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001910 // admin1 is DO.
1911 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001912 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001913 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001914 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1915 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001916
1917 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001918 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001919 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001920 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1921 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001922
1923 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001924 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001925 dpm.reboot(admin1);
1926 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001927
1928 public void testSetGetSupportText() {
1929 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1930 dpm.setActiveAdmin(admin1, true);
1931 dpm.setActiveAdmin(admin2, true);
1932 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1933
1934 // Null default support messages.
1935 {
1936 assertNull(dpm.getLongSupportMessage(admin1));
1937 assertNull(dpm.getShortSupportMessage(admin1));
1938 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1939 assertNull(dpm.getShortSupportMessageForUser(admin1,
1940 DpmMockContext.CALLER_USER_HANDLE));
1941 assertNull(dpm.getLongSupportMessageForUser(admin1,
1942 DpmMockContext.CALLER_USER_HANDLE));
1943 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1944 }
1945
1946 // Only system can call the per user versions.
1947 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001948 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1949 () -> dpm.getShortSupportMessageForUser(admin1,
1950 DpmMockContext.CALLER_USER_HANDLE));
1951 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1952 () -> dpm.getLongSupportMessageForUser(admin1,
1953 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00001954 }
1955
1956 // Can't set message for admin in another uid.
1957 {
1958 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001959 assertExpectException(SecurityException.class,
1960 /* messageRegex= */ "is not owned by uid",
1961 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00001962 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1963 }
1964
1965 // Set/Get short returns what it sets and other admins text isn't changed.
1966 {
1967 final String supportText = "Some text to test with.";
1968 dpm.setShortSupportMessage(admin1, supportText);
1969 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1970 assertNull(dpm.getLongSupportMessage(admin1));
1971 assertNull(dpm.getShortSupportMessage(admin2));
1972
1973 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1974 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1975 DpmMockContext.CALLER_USER_HANDLE));
1976 assertNull(dpm.getShortSupportMessageForUser(admin2,
1977 DpmMockContext.CALLER_USER_HANDLE));
1978 assertNull(dpm.getLongSupportMessageForUser(admin1,
1979 DpmMockContext.CALLER_USER_HANDLE));
1980 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1981
1982 dpm.setShortSupportMessage(admin1, null);
1983 assertNull(dpm.getShortSupportMessage(admin1));
1984 }
1985
1986 // Set/Get long returns what it sets and other admins text isn't changed.
1987 {
1988 final String supportText = "Some text to test with.\nWith more text.";
1989 dpm.setLongSupportMessage(admin1, supportText);
1990 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1991 assertNull(dpm.getShortSupportMessage(admin1));
1992 assertNull(dpm.getLongSupportMessage(admin2));
1993
1994 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1995 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1996 DpmMockContext.CALLER_USER_HANDLE));
1997 assertNull(dpm.getLongSupportMessageForUser(admin2,
1998 DpmMockContext.CALLER_USER_HANDLE));
1999 assertNull(dpm.getShortSupportMessageForUser(admin1,
2000 DpmMockContext.CALLER_USER_HANDLE));
2001 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2002
2003 dpm.setLongSupportMessage(admin1, null);
2004 assertNull(dpm.getLongSupportMessage(admin1));
2005 }
2006 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002007
phweiss73145f42017-01-17 19:06:38 +01002008 public void testCreateAdminSupportIntent() throws Exception {
2009 // Setup device owner.
2010 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2011 setupDeviceOwner();
2012
2013 // Nonexisting permission returns null
2014 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2015 assertNull(intent);
2016
2017 // Existing permission that is not set returns null
2018 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2019 assertNull(intent);
2020
2021 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002022 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002023 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2024 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2025 .thenReturn(true);
2026 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2027 assertNull(intent);
2028
2029 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002030 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002031 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2032 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2033 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2034 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2035 assertNotNull(intent);
2036 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2037 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2038 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002039 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002040 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2041 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2042
2043 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2044 // user restrictions
2045
2046 // Camera is not disabled
2047 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2048 assertNull(intent);
2049
2050 // Camera is disabled
2051 dpm.setCameraDisabled(admin1, true);
2052 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2053 assertNotNull(intent);
2054 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2055 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2056
2057 // Screen capture is not disabled
2058 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2059 assertNull(intent);
2060
2061 // Screen capture is disabled
2062 dpm.setScreenCaptureDisabled(admin1, true);
2063 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2064 assertNotNull(intent);
2065 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2066 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2067
2068 // Same checks for different user
2069 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2070 // Camera should be disabled by device owner
2071 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2072 assertNotNull(intent);
2073 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2074 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2075 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2076 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2077 // ScreenCapture should not be disabled by device owner
2078 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2079 assertNull(intent);
2080 }
2081
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002082 /**
2083 * Test for:
2084 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002085 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002086 * {@link DevicePolicyManager#isAffiliatedUser}
2087 */
2088 public void testUserAffiliation() throws Exception {
2089 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2090 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2091 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2092
2093 // Check that the system user is unaffiliated.
2094 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2095 assertFalse(dpm.isAffiliatedUser());
2096
2097 // Set a device owner on the system user. Check that the system user becomes affiliated.
2098 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2099 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2100 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2101 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002102 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002103
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002104 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002105 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2106 setAsProfileOwner(admin2);
2107 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002108 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002109
2110 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2111 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002112 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002113 userAffiliationIds.add("red");
2114 userAffiliationIds.add("green");
2115 userAffiliationIds.add("blue");
2116 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002117 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002118 assertFalse(dpm.isAffiliatedUser());
2119
2120 // Have the device owner specify a set of affiliation ids that do not intersect with those
2121 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002122 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002123 deviceAffiliationIds.add("cyan");
2124 deviceAffiliationIds.add("yellow");
2125 deviceAffiliationIds.add("magenta");
2126 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2127 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002128 MoreAsserts.assertContentsInAnyOrder(
2129 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002130 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2131 assertFalse(dpm.isAffiliatedUser());
2132
2133 // Have the profile owner specify a set of affiliation ids that intersect with those
2134 // specified by the device owner. Check that the test user becomes affiliated.
2135 userAffiliationIds.add("yellow");
2136 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002137 MoreAsserts.assertContentsInAnyOrder(
2138 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002139 assertTrue(dpm.isAffiliatedUser());
2140
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002141 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002142 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002143 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002144 assertFalse(dpm.isAffiliatedUser());
2145
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002146 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2147 dpm.setAffiliationIds(admin2, userAffiliationIds);
2148 assertTrue(dpm.isAffiliatedUser());
2149 dpm.clearProfileOwner(admin2);
2150 assertFalse(dpm.isAffiliatedUser());
2151
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002152 // Check that the system user remains affiliated.
2153 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2154 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002155
2156 // Clear the device owner - the user becomes unaffiliated.
2157 clearDeviceOwner();
2158 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002159 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002160
2161 public void testGetUserProvisioningState_defaultResult() {
2162 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2163 }
2164
2165 public void testSetUserProvisioningState_permission() throws Exception {
2166 setupProfileOwner();
2167 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2168
2169 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2170 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2171 }
2172
2173 public void testSetUserProvisioningState_unprivileged() throws Exception {
2174 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002175 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2176 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2177 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002178 }
2179
2180 public void testSetUserProvisioningState_noManagement() {
2181 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002182 assertExpectException(IllegalStateException.class,
2183 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2184 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2185 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002186 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2187 }
2188
2189 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2190 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2191 setupDeviceOwner();
2192 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2193
2194 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2195 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2196 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2197 }
2198
2199 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2200 throws Exception {
2201 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2202 setupDeviceOwner();
2203 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2204
2205 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2206 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2207 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2208 }
2209
2210 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2211 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2212 setupDeviceOwner();
2213 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2214
2215 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2216 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2217 }
2218
2219 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2220 throws Exception {
2221 setupProfileOwner();
2222 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2223
2224 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2225 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2226 DevicePolicyManager.STATE_USER_UNMANAGED);
2227 }
2228
2229 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2230 throws Exception {
2231 setupProfileOwner();
2232 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2233
2234 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2235 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2236 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2237 }
2238
2239 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2240 setupProfileOwner();
2241 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2242
2243 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2244 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2245 }
2246
2247 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2248 setupProfileOwner();
2249 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2250
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002251 assertExpectException(IllegalStateException.class,
2252 /* messageRegex= */ "Cannot move to user provisioning state",
2253 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2254 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2255 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002256 }
2257
2258 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2259 throws Exception {
2260 setupProfileOwner();
2261 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2262
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002263 assertExpectException(IllegalStateException.class,
2264 /* messageRegex= */ "Cannot move to user provisioning state",
2265 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2266 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2267 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002268 }
2269
2270 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2271 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2272 for (int state : states) {
2273 dpm.setUserProvisioningState(state, userId);
2274 assertEquals(state, dpm.getUserProvisioningState());
2275 }
2276 }
2277
2278 private void setupProfileOwner() throws Exception {
2279 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2280
2281 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2282 dpm.setActiveAdmin(admin1, false);
2283 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2284
2285 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2286 }
2287
2288 private void setupDeviceOwner() throws Exception {
2289 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2290
2291 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2292 dpm.setActiveAdmin(admin1, false);
2293 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2294
2295 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2296 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002297
2298 public void testSetMaximumTimeToLock() {
2299 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2300
2301 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2302 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2303
Pavel Grafov75c0a892017-05-18 17:28:27 +01002304 reset(getServices().powerManagerInternal);
2305 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002306
2307 dpm.setMaximumTimeToLock(admin1, 0);
2308 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002309 reset(getServices().powerManagerInternal);
2310 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002311
2312 dpm.setMaximumTimeToLock(admin1, 1);
2313 verifyScreenTimeoutCall(1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002314 reset(getServices().powerManagerInternal);
2315 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002316
2317 dpm.setMaximumTimeToLock(admin2, 10);
2318 verifyScreenTimeoutCall(null, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002319 reset(getServices().powerManagerInternal);
2320 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002321
2322 dpm.setMaximumTimeToLock(admin1, 5);
2323 verifyScreenTimeoutCall(5, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002324 reset(getServices().powerManagerInternal);
2325 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002326
2327 dpm.setMaximumTimeToLock(admin2, 4);
2328 verifyScreenTimeoutCall(4, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002329 reset(getServices().powerManagerInternal);
2330 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002331
2332 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002333 reset(getServices().powerManagerInternal);
2334 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002335
2336 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2337 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002338 reset(getServices().powerManagerInternal);
2339 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002340
2341 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2342 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002343 reset(getServices().powerManagerInternal);
2344 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002345
2346 dpm.setMaximumTimeToLock(admin2, 10);
2347 verifyScreenTimeoutCall(10, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002348 reset(getServices().powerManagerInternal);
2349 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002350
2351 // There's no restriction; shold be set to MAX.
2352 dpm.setMaximumTimeToLock(admin2, 0);
2353 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2354 }
2355
Michal Karpinski943aabd2016-10-06 11:09:25 +01002356 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2357 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2358 setupDeviceOwner();
2359 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2360
Michal Karpinskid084ca52017-01-18 15:54:18 +00002361 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2362 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2363 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2364 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2365 - ONE_MINUTE;
2366
2367 // verify that the minimum timeout cannot be modified on user builds (system property is
2368 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002369 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002370
2371 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2372 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2373 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2374
Pavel Grafov75c0a892017-05-18 17:28:27 +01002375 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002376
2377 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002378 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002379
2380 // Always return the default (second arg) when getting system property for long type
Pavel Grafov75c0a892017-05-18 17:28:27 +01002381 when(getServices().systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2382 invocation -> invocation.getArguments()[1]
Michal Karpinskid084ca52017-01-18 15:54:18 +00002383 );
2384
2385 // reset to default (0 means the admin is not participating, so default should be returned)
2386 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002387
2388 // aggregation should be the default if unset by any admin
2389 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2390 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2391
2392 // admin not participating by default
2393 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2394
2395 //clamping from the top
2396 dpm.setRequiredStrongAuthTimeout(admin1,
2397 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2398 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2399 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2400 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2401 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2402
Michal Karpinskid084ca52017-01-18 15:54:18 +00002403 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002404 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2405 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2406 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2407 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2408
2409 // clamping from the bottom
2410 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2411 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2412 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2413
Michal Karpinskid084ca52017-01-18 15:54:18 +00002414 // values within range
2415 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2416 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2417 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2418
2419 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2420 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2421 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002422
2423 // reset to default
2424 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2425 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2426 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2427 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2428
2429 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002430 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2431 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002432 }
2433
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002434 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2435 boolean shouldStayOnWhilePluggedInBeCleared) {
2436 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002437 verify(getServices().powerManagerInternal, times(0))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002438 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2439 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002440 verify(getServices().powerManagerInternal, times(1))
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002441 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2442 }
2443 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2444 // UnfinishedVerificationException.
2445 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002446
Esteban Talavera01576862016-12-15 11:16:44 +00002447 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002448 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002449 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002450 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002451 .thenReturn(false);
2452 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002453 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2454 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002455 .thenReturn(true);
2456 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2457
2458 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002459 }
Victor Chang3e794af2016-03-04 13:48:17 +00002460
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002461 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2462 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002463 mContext.packageName = admin1.getPackageName();
2464 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002465 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2466 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2467 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2468 false);
2469 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2470 }
2471
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002472 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2473 setup_DeviceAdminFeatureOff();
2474 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2475 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2476 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2477 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2478 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2479 assertCheckProvisioningPreCondition(
2480 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2481 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2482 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2483 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2484 }
2485
Esteban Talavera01576862016-12-15 11:16:44 +00002486 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002487 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002488 .thenReturn(false);
2489 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002490 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2491 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002492 .thenReturn(true);
2493 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2494
2495 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002496 }
Victor Chang3e794af2016-03-04 13:48:17 +00002497
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002498 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2499 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002500 mContext.packageName = admin1.getPackageName();
2501 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002502 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2503 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2504 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2505 false);
2506 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2507
2508 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002509 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002510 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2511 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2512 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2513 true);
2514 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2515 }
2516
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002517 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2518 setup_ManagedProfileFeatureOff();
2519 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2520 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2521 DevicePolicyManager.CODE_OK);
2522 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2523 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2524 assertCheckProvisioningPreCondition(
2525 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2526 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2527 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2528 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2529
2530 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002531 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002532 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2533 DevicePolicyManager.CODE_OK);
2534 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2535 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2536 assertCheckProvisioningPreCondition(
2537 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2538 DevicePolicyManager.CODE_OK);
2539 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2540 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2541 }
2542
Esteban Talavera01576862016-12-15 11:16:44 +00002543 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002544 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002545 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002546 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2547 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002548 .thenReturn(true);
2549 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2550
2551 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002552 }
Victor Chang3e794af2016-03-04 13:48:17 +00002553
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002554 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2555 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002556 mContext.packageName = admin1.getPackageName();
2557 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002558 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2559 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2560 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2561 false /* because of non-split user */);
2562 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2563 false /* because of non-split user */);
2564 }
2565
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002566 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002567 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002568 setup_nonSplitUser_firstBoot_primaryUser();
2569 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2570 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2571 DevicePolicyManager.CODE_OK);
2572 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2573 DevicePolicyManager.CODE_OK);
2574 assertCheckProvisioningPreCondition(
2575 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2576 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2577 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2578 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2579 }
2580
Esteban Talavera01576862016-12-15 11:16:44 +00002581 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002582 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002583 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002584 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2585 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002586 .thenReturn(true);
2587 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2588
2589 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002590 }
Victor Chang3e794af2016-03-04 13:48:17 +00002591
Nicolas Prevot45d29072017-01-18 16:11:19 +00002592 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2593 setDeviceOwner();
2594 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2595 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2596 }
2597
2598 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2599 setup_nonSplitUser_withDo_primaryUser();
2600 final int MANAGED_PROFILE_USER_ID = 18;
2601 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2602 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002603 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002604 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002605 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002606 true)).thenReturn(true);
2607 }
2608
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002609 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2610 throws Exception {
2611 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002612 mContext.packageName = admin1.getPackageName();
2613 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002614 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2615 false/* because of completed device setup */);
2616 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2617 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2618 false/* because of non-split user */);
2619 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2620 false/* because of non-split user */);
2621 }
2622
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002623 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2624 throws Exception {
2625 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2626 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2627 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2628 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2629 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2630 DevicePolicyManager.CODE_OK);
2631 assertCheckProvisioningPreCondition(
2632 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2633 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2634 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2635 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2636 }
2637
Nicolas Prevot45d29072017-01-18 16:11:19 +00002638 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2639 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002640 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002641 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2642
2643 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2644 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002645 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002646
2647 // COMP mode is allowed.
2648 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2649 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002650 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002651
Nicolas Prevot45d29072017-01-18 16:11:19 +00002652 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002653 assertCheckProvisioningPreCondition(
2654 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002655 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002656 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002657 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2658 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2659 }
Esteban Talavera01576862016-12-15 11:16:44 +00002660
Nicolas Prevot45d29072017-01-18 16:11:19 +00002661 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2662 setup_nonSplitUser_withDo_primaryUser();
2663 mContext.packageName = admin1.getPackageName();
2664 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2665 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2666 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002667 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002668 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2669 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2670 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002671 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002672 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2673 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2674 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2675 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2676 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002677 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002678 assertCheckProvisioningPreCondition(
2679 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002680 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002681 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002682 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2683 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2684 }
Esteban Talavera01576862016-12-15 11:16:44 +00002685
Nicolas Prevot45d29072017-01-18 16:11:19 +00002686 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2687 throws Exception {
2688 setup_nonSplitUser_withDo_primaryUser();
2689 mContext.packageName = admin1.getPackageName();
2690 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002691 // The DO should not be allowed to initiate provisioning if the restriction is set by
2692 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002693 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002694 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2695 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2696 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002697 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002698 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2699 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2700 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2701 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2702 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002703 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2704
2705 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002706 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002707 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002708 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002709 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2710 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2711 }
2712
2713 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2714 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2715 mContext.packageName = admin1.getPackageName();
2716 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2717
2718 // We can delete the managed profile to create a new one, so provisioning is allowed.
2719 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2720 DevicePolicyManager.CODE_OK);
2721 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2722 assertCheckProvisioningPreCondition(
2723 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2724 DpmMockContext.ANOTHER_PACKAGE_NAME,
2725 DevicePolicyManager.CODE_OK);
2726 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2727 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2728 }
2729
2730 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2731 throws Exception {
2732 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2733 mContext.packageName = admin1.getPackageName();
2734 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002735 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002736 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2737 eq(UserHandle.SYSTEM)))
2738 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002739 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002740 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2741 eq(UserHandle.SYSTEM)))
2742 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002743
2744 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002745 assertCheckProvisioningPreCondition(
2746 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2747 DpmMockContext.ANOTHER_PACKAGE_NAME,
2748 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2749 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2750 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002751
2752 // But the device owner can still do it because it has set the restriction itself.
2753 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2754 DevicePolicyManager.CODE_OK);
2755 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002756 }
2757
2758 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002759 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002760 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002761 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2762 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002763 .thenReturn(false);
2764 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2765
2766 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002767 }
Victor Chang3e794af2016-03-04 13:48:17 +00002768
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002769 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2770 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002771 mContext.packageName = admin1.getPackageName();
2772 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002773 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2774 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2775 false /* because canAddMoreManagedProfiles returns false */);
2776 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2777 true);
2778 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2779 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002780 }
2781
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002782 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2783 throws Exception {
2784 setup_splitUser_firstBoot_systemUser();
2785 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2786 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2787 DevicePolicyManager.CODE_OK);
2788 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002789 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002790 assertCheckProvisioningPreCondition(
2791 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2792 DevicePolicyManager.CODE_OK);
2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2794 DevicePolicyManager.CODE_SYSTEM_USER);
2795 }
2796
Esteban Talavera01576862016-12-15 11:16:44 +00002797 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002798 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002799 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002800 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2801 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002802 .thenReturn(false);
2803 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2804
2805 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002806 }
Victor Chang3e794af2016-03-04 13:48:17 +00002807
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002808 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2809 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002810 mContext.packageName = admin1.getPackageName();
2811 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002812 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2813 true/* it's undefined behavior. Can be changed into false in the future */);
2814 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2815 false /* because canAddMoreManagedProfiles returns false */);
2816 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2817 true/* it's undefined behavior. Can be changed into false in the future */);
2818 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2819 false/* because calling uid is system user */);
2820 }
2821
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002822 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2823 throws Exception {
2824 setup_splitUser_afterDeviceSetup_systemUser();
2825 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2826 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2827 DevicePolicyManager.CODE_OK);
2828 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002829 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002830 assertCheckProvisioningPreCondition(
2831 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2832 DevicePolicyManager.CODE_OK);
2833 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2834 DevicePolicyManager.CODE_SYSTEM_USER);
2835 }
2836
Esteban Talavera01576862016-12-15 11:16:44 +00002837 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002838 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002839 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002840 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2841 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002842 true)).thenReturn(true);
2843 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2844
2845 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002846 }
Victor Chang3e794af2016-03-04 13:48:17 +00002847
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002848 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2849 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002850 mContext.packageName = admin1.getPackageName();
2851 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002852 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2853 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2854 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2855 true);
2856 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002857 }
2858
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002859 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002860 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002861 setup_splitUser_firstBoot_primaryUser();
2862 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2863 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2864 DevicePolicyManager.CODE_OK);
2865 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2866 DevicePolicyManager.CODE_OK);
2867 assertCheckProvisioningPreCondition(
2868 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2869 DevicePolicyManager.CODE_OK);
2870 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2871 DevicePolicyManager.CODE_OK);
2872 }
2873
Esteban Talavera01576862016-12-15 11:16:44 +00002874 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002875 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002876 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002877 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2878 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002879 true)).thenReturn(true);
2880 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2881
2882 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002883 }
Victor Chang3e794af2016-03-04 13:48:17 +00002884
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002885 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2886 throws Exception {
2887 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002888 mContext.packageName = admin1.getPackageName();
2889 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002890 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2891 true/* it's undefined behavior. Can be changed into false in the future */);
2892 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2893 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2894 true/* it's undefined behavior. Can be changed into false in the future */);
2895 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2896 false/* because user setup completed */);
2897 }
2898
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002899 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002900 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002901 setup_splitUser_afterDeviceSetup_primaryUser();
2902 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2903 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2904 DevicePolicyManager.CODE_OK);
2905 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2906 DevicePolicyManager.CODE_OK);
2907 assertCheckProvisioningPreCondition(
2908 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2909 DevicePolicyManager.CODE_OK);
2910 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2911 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2912 }
2913
Esteban Talavera01576862016-12-15 11:16:44 +00002914 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002915 setDeviceOwner();
2916
Pavel Grafov75c0a892017-05-18 17:28:27 +01002917 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002918 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002919 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2920 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002921 .thenReturn(false);
2922 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2923
2924 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002925 }
Victor Chang3e794af2016-03-04 13:48:17 +00002926
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002927 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2928 throws Exception {
2929 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002930 mContext.packageName = admin1.getPackageName();
2931 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002932 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2933 false /* can't provision managed profile on system user */);
2934 }
2935
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002936 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002937 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002938 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2939 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2940 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2941 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2942 }
2943
2944 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002945 setDeviceOwner();
2946
Pavel Grafov75c0a892017-05-18 17:28:27 +01002947 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002948 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002949 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2950 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00002951 true)).thenReturn(true);
2952 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2953
2954 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002955 }
Victor Chang3e794af2016-03-04 13:48:17 +00002956
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002957 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2958 throws Exception {
2959 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002960 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2961 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002962 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2963 }
2964
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002965 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002966 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002967 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2968 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002969
2970 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002971 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2972 DevicePolicyManager.CODE_OK);
2973 }
2974
2975 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002976 setDeviceOwner();
2977
Pavel Grafov75c0a892017-05-18 17:28:27 +01002978 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002979 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002980 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2981 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002982 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2983 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002984 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002985 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002986 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002987 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00002988 true)).thenReturn(true);
2989 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2990
2991 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002992 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002993
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002994 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2995 throws Exception {
2996 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002997 mContext.packageName = admin1.getPackageName();
2998 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002999 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3000 }
3001
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003002 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3003 throws Exception {
3004 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3005 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3006 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3007 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3008 }
3009
3010 public void testCheckProvisioningPreCondition_permission() {
3011 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003012 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3013 () -> dpm.checkProvisioningPreCondition(
3014 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003015 }
3016
Victor Chang3577ed22016-08-25 18:49:26 +01003017 public void testForceUpdateUserSetupComplete_permission() {
3018 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003019 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3020 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003021 }
3022
3023 public void testForceUpdateUserSetupComplete_systemUser() {
3024 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3025 // GIVEN calling from user 20
3026 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003027 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3028 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003029 }
3030
3031 public void testForceUpdateUserSetupComplete_userbuild() {
3032 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3033 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3034
3035 final int userId = UserHandle.USER_SYSTEM;
3036 // GIVEN userComplete is false in SettingsProvider
3037 setUserSetupCompleteForUser(false, userId);
3038
3039 // GIVEN userComplete is true in DPM
3040 DevicePolicyManagerService.DevicePolicyData userData =
3041 new DevicePolicyManagerService.DevicePolicyData(userId);
3042 userData.mUserSetupComplete = true;
3043 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3044
3045 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003046 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003047
3048 assertTrue(dpms.hasUserSetupCompleted());
3049
3050 dpm.forceUpdateUserSetupComplete();
3051
3052 // THEN the state in dpms is not changed
3053 assertTrue(dpms.hasUserSetupCompleted());
3054 }
3055
3056 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3057 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3058 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3059
3060 final int userId = UserHandle.USER_SYSTEM;
3061 // GIVEN userComplete is false in SettingsProvider
3062 setUserSetupCompleteForUser(false, userId);
3063
3064 // GIVEN userComplete is true in DPM
3065 DevicePolicyManagerService.DevicePolicyData userData =
3066 new DevicePolicyManagerService.DevicePolicyData(userId);
3067 userData.mUserSetupComplete = true;
3068 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3069
3070 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003071 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003072
3073 assertTrue(dpms.hasUserSetupCompleted());
3074
3075 dpm.forceUpdateUserSetupComplete();
3076
3077 // THEN the state in dpms is not changed
3078 assertFalse(dpms.hasUserSetupCompleted());
3079 }
3080
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003081 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003082 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003083 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003084
3085 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3086 runAsCaller(mAdmin1Context, dpms, dpm -> {
3087 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3088 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003089 }
3090
3091 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3092 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3093 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003094
3095 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3096 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003097 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003098 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3099 .thenReturn(true);
3100
3101 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003102 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003103
3104 // Enabling logging should not change the timestamp.
3105 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003106 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003107 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003108 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003109 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003110 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003111
3112 // Retrieving the logs should update the timestamp.
3113 final long beforeRetrieval = System.currentTimeMillis();
3114 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003115 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003116 final long afterRetrieval = System.currentTimeMillis();
3117 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3118 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3119
3120 // Retrieving the pre-boot logs should update the timestamp.
3121 Thread.sleep(2);
3122 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003123 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003124 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3125
3126 // Checking the timestamp again should not change it.
3127 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003128 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003129
3130 // Retrieving the logs again should update the timestamp.
3131 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003132 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003133 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3134
3135 // Disabling logging should not change the timestamp.
3136 Thread.sleep(2);
3137 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003138 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003139
3140 // Restarting the DPMS should not lose the timestamp.
3141 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003142 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003143
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003144 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3145 mContext.binder.callingUid = 1234567;
3146 mContext.callerPermissions.add(permission.MANAGE_USERS);
3147 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3148 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3149
3150 // System can retrieve the timestamp.
3151 mContext.binder.clearCallingIdentity();
3152 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3153
3154 // Removing the device owner should clear the timestamp.
3155 clearDeviceOwner();
3156 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003157 }
3158
3159 public void testGetLastBugReportRequestTime() throws Exception {
3160 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3161 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003162
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003163 mContext.packageName = admin1.getPackageName();
3164 mContext.applicationInfo = new ApplicationInfo();
3165 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3166 .thenReturn(Color.WHITE);
3167 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3168 anyObject())).thenReturn(Color.WHITE);
3169
Esteban Talaverad36dd152016-12-15 08:51:45 +00003170 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3171 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003172 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003173
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003174 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003175 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003176
3177 // Requesting a bug report should update the timestamp.
3178 final long beforeRequest = System.currentTimeMillis();
3179 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003180 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003181 final long afterRequest = System.currentTimeMillis();
3182 assertTrue(bugReportRequestTime >= beforeRequest);
3183 assertTrue(bugReportRequestTime <= afterRequest);
3184
3185 // Checking the timestamp again should not change it.
3186 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003187 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003188
3189 // Restarting the DPMS should not lose the timestamp.
3190 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003191 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003192
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003193 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3194 mContext.binder.callingUid = 1234567;
3195 mContext.callerPermissions.add(permission.MANAGE_USERS);
3196 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3197 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3198
3199 // System can retrieve the timestamp.
3200 mContext.binder.clearCallingIdentity();
3201 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3202
3203 // Removing the device owner should clear the timestamp.
3204 clearDeviceOwner();
3205 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003206 }
3207
3208 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3209 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3210 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003211 mContext.packageName = admin1.getPackageName();
3212 mContext.applicationInfo = new ApplicationInfo();
3213 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3214 .thenReturn(Color.WHITE);
3215 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3216 anyObject())).thenReturn(Color.WHITE);
3217
3218 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3219 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003220 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
3221 when(getServices().iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003222 .thenReturn(true);
3223
3224 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003225 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003226
3227 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3228 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003229 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003230
3231 // Enabling logging should not change the timestamp.
3232 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003233 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003234
3235 // Retrieving the logs should update the timestamp.
3236 final long beforeRetrieval = System.currentTimeMillis();
3237 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003238 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003239 final long afterRetrieval = System.currentTimeMillis();
3240 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3241 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3242
3243 // Checking the timestamp again should not change it.
3244 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003245 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003246
3247 // Retrieving the logs again should update the timestamp.
3248 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003249 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003250 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3251
3252 // Disabling logging should not change the timestamp.
3253 Thread.sleep(2);
3254 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003255 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003256
3257 // Restarting the DPMS should not lose the timestamp.
3258 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003259 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3260
3261 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3262 mContext.binder.callingUid = 1234567;
3263 mContext.callerPermissions.add(permission.MANAGE_USERS);
3264 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3265 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3266
3267 // System can retrieve the timestamp.
3268 mContext.binder.clearCallingIdentity();
3269 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3270
3271 // Removing the device owner should clear the timestamp.
3272 clearDeviceOwner();
3273 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003274 }
3275
Tony Mak2f26b792016-11-28 17:54:51 +00003276 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3277 // Setup device owner.
3278 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3279 setupDeviceOwner();
3280
3281 // Only device owner is setup, the result list should be empty.
3282 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3283 MoreAsserts.assertEmpty(targetUsers);
3284
3285 // Setup a managed profile managed by the same admin.
3286 final int MANAGED_PROFILE_USER_ID = 15;
3287 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3288 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3289
3290 // Add a secondary user, it should never talk with.
3291 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003292 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003293
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003294 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3295 // other.
3296 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3297 MoreAsserts.assertEmpty(targetUsers);
3298
3299 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3300 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3301 MoreAsserts.assertEmpty(targetUsers);
3302
3303 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003304 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003305 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3306 dpm.setAffiliationIds(admin1, userAffiliationIds);
3307
3308 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3309 dpm.setAffiliationIds(admin1, userAffiliationIds);
3310
Tony Mak2f26b792016-11-28 17:54:51 +00003311 // Calling from device owner admin, the result list should just contain the managed
3312 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003313 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003314 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3315 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3316
3317 // Calling from managed profile admin, the result list should just contain the system
3318 // user id.
3319 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3320 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3321 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003322
3323 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003324 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003325
3326 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3327 // to each other.
3328 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3329 MoreAsserts.assertEmpty(targetUsers);
3330
3331 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3332 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3333 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003334 }
3335
3336 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3337 // Setup a device owner.
3338 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3339 setupDeviceOwner();
3340
3341 // Set up a managed profile managed by different package.
3342 final int MANAGED_PROFILE_USER_ID = 15;
3343 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3344 final ComponentName adminDifferentPackage =
3345 new ComponentName("another.package", "whatever.class");
3346 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3347
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003348 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003349 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003350 dpm.setAffiliationIds(admin1, userAffiliationIds);
3351
3352 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3353 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3354
Tony Mak2f26b792016-11-28 17:54:51 +00003355 // Calling from device owner admin, we should get zero bind device admin target users as
3356 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003357 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003358 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3359 MoreAsserts.assertEmpty(targetUsers);
3360
3361 // Calling from managed profile admin, we should still get zero target users for the same
3362 // reason.
3363 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3364 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3365 MoreAsserts.assertEmpty(targetUsers);
3366 }
3367
Esteban Talaverabdcada92017-02-01 14:20:06 +00003368 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3369 // Setup a device owner.
3370 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3371 setupDeviceOwner();
3372 // Lock task packages are updated when loading user data.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003373 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003374 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3375
3376 // Set up a managed profile managed by different package (package name shouldn't matter)
3377 final int MANAGED_PROFILE_USER_ID = 15;
3378 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3379 final ComponentName adminDifferentPackage =
3380 new ComponentName("another.package", "whatever.class");
3381 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003382 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003383 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3384
3385 // The DO can still set lock task packages
3386 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3387 final String[] doPackages = {"doPackage1", "doPackage2"};
3388 dpm.setLockTaskPackages(admin1, doPackages);
3389 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3390 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3391 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003392 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003393 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3394
3395 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3396 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3397 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003398 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3399 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3400 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3401 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003402 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3403
3404 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003405 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003406 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3407 dpm.setAffiliationIds(admin1, userAffiliationIds);
3408
3409 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3410 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3411
3412 // Now the managed profile can set lock task packages.
3413 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3414 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3415 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3416 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003417 verify(getServices().iactivityManager)
Esteban Talaverabdcada92017-02-01 14:20:06 +00003418 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3419
3420 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003421 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003422 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3423 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003424 verify(getServices().iactivityManager, times(2))
Esteban Talaverabdcada92017-02-01 14:20:06 +00003425 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3426
3427 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3428 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3429 }
3430
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003431 public void testIsDeviceManaged() throws Exception {
3432 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3433 setupDeviceOwner();
3434
3435 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3436 // find out that the device has a device owner.
3437 assertTrue(dpm.isDeviceManaged());
3438 mContext.binder.callingUid = 1234567;
3439 mContext.callerPermissions.add(permission.MANAGE_USERS);
3440 assertTrue(dpm.isDeviceManaged());
3441 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3442 mContext.binder.clearCallingIdentity();
3443 assertTrue(dpm.isDeviceManaged());
3444
3445 clearDeviceOwner();
3446
3447 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3448 // not have a device owner.
3449 mContext.binder.callingUid = 1234567;
3450 mContext.callerPermissions.add(permission.MANAGE_USERS);
3451 assertFalse(dpm.isDeviceManaged());
3452 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3453 mContext.binder.clearCallingIdentity();
3454 assertFalse(dpm.isDeviceManaged());
3455 }
3456
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003457 public void testDeviceOwnerOrganizationName() throws Exception {
3458 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3459 setupDeviceOwner();
3460
3461 dpm.setOrganizationName(admin1, "organization");
3462
3463 // Device owner can retrieve organization managing the device.
3464 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3465
3466 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3467 mContext.binder.callingUid = 1234567;
3468 mContext.callerPermissions.add(permission.MANAGE_USERS);
3469 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3470 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3471
3472 // System can retrieve organization managing the device.
3473 mContext.binder.clearCallingIdentity();
3474 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3475
3476 // Removing the device owner clears the organization managing the device.
3477 clearDeviceOwner();
3478 assertNull(dpm.getDeviceOwnerOrganizationName());
3479 }
3480
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003481 public void testWipeDataManagedProfile() throws Exception {
3482 final int MANAGED_PROFILE_USER_ID = 15;
3483 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3484 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3485 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3486
3487 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003488 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003489 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3490
3491 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003492 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003493 MANAGED_PROFILE_USER_ID);
3494 }
3495
3496 public void testWipeDataManagedProfileDisallowed() throws Exception {
3497 final int MANAGED_PROFILE_USER_ID = 15;
3498 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3499 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3500
3501 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003502 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003503 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3504
Pavel Grafov75c0a892017-05-18 17:28:27 +01003505 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003506 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3507 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3508 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3509 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003510 // The PO is not allowed to remove the profile if the user restriction was set on the
3511 // profile by the system
3512 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3513 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003514 }
3515
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003516 public void testWipeDataDeviceOwner() throws Exception {
3517 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003518 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003519 UserManager.DISALLOW_FACTORY_RESET,
3520 UserHandle.SYSTEM))
3521 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3522
3523 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003524 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003525 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3526 /*wipeEuicc=*/ eq(false));
3527 }
3528
3529 public void testWipeEuiccDataEnabled() throws Exception {
3530 setDeviceOwner();
3531 when(getServices().userManager.getUserRestrictionSource(
3532 UserManager.DISALLOW_FACTORY_RESET,
3533 UserHandle.SYSTEM))
3534 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3535
3536 dpm.wipeData(WIPE_EUICC);
3537 verify(getServices().recoverySystem).rebootWipeUserData(
3538 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3539 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003540 }
3541
3542 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3543 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003544 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003545 UserManager.DISALLOW_FACTORY_RESET,
3546 UserHandle.SYSTEM))
3547 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003548 // The DO is not allowed to wipe the device if the user restriction was set
3549 // by the system
3550 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3551 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003552 }
3553
3554 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3555 final int MANAGED_PROFILE_USER_ID = 15;
3556 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3557 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3558
3559 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003560 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003561 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3562
Pavel Grafov75c0a892017-05-18 17:28:27 +01003563 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003564 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3565 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3566 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3567
3568 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3569 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3570
3571 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3572 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3573 // Failed password attempts on the parent user are taken into account, as there isn't a
3574 // separate work challenge.
3575 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3576 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3577 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3578
3579 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3580 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003581 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003582 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003583 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003584 }
3585
3586 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3587 throws Exception {
3588 final int MANAGED_PROFILE_USER_ID = 15;
3589 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3590 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3591
3592 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003593 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003594 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3595
Pavel Grafov75c0a892017-05-18 17:28:27 +01003596 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003597 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3598 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3599 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3600
3601 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3602 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3603
3604 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3605 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3606 // Failed password attempts on the parent user are taken into account, as there isn't a
3607 // separate work challenge.
3608 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3609 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3610 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3611
3612 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3613 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003614 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003615 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003616 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003617 }
3618
3619 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3620 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003621 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003622 UserManager.DISALLOW_FACTORY_RESET,
3623 UserHandle.SYSTEM))
3624 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3625
3626 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3627
3628 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3629 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3630 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3631 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3632 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3633
3634 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3635 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003636 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003637 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3638 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003639 }
3640
3641 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3642 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003643 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003644 UserManager.DISALLOW_FACTORY_RESET,
3645 UserHandle.SYSTEM))
3646 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3647
3648 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3649
3650 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3651 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3652 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3653 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3654 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3655
3656 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003657 verifyZeroInteractions(getServices().recoverySystem);
3658 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003659 .removeUserEvenWhenDisallowed(anyInt());
3660 }
3661
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003662 public void testGetPermissionGrantState() throws Exception {
3663 final String permission = "some.permission";
3664 final String app1 = "com.example.app1";
3665 final String app2 = "com.example.app2";
3666
Pavel Grafov75c0a892017-05-18 17:28:27 +01003667 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003668 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003669 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003670 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003671 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003672 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3673 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003674 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003675 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003676 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003677 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003678 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003679 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3680
3681 // System can retrieve permission grant state.
3682 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003683 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003684 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3685 dpm.getPermissionGrantState(null, app1, permission));
3686 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3687 dpm.getPermissionGrantState(null, app2, permission));
3688
3689 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003690 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3691 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003692 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3693 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003694
3695 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003696 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3697 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003698 setAsProfileOwner(admin1);
3699 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3700 dpm.getPermissionGrantState(admin1, app1, permission));
3701 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3702 dpm.getPermissionGrantState(admin1, app2, permission));
3703 }
3704
Rubin Xuaab7a412016-12-30 21:13:29 +00003705 public void testResetPasswordWithToken() throws Exception {
3706 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3707 setupDeviceOwner();
3708 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003709 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3710 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3711
Rubin Xuaab7a412016-12-30 21:13:29 +00003712 // test adding a token
3713 final byte[] token = new byte[32];
3714 final long handle = 123456;
3715 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003716 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003717 .thenReturn(handle);
3718 assertTrue(dpm.setResetPasswordToken(admin1, token));
3719
3720 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003721 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003722 .thenReturn(true);
3723 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3724
3725 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003726 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xuaab7a412016-12-30 21:13:29 +00003727 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3728 eq(UserHandle.USER_SYSTEM)))
3729 .thenReturn(true);
3730 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3731
3732 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003733 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003734 .thenReturn(true);
3735 assertTrue(dpm.clearResetPasswordToken(admin1));
3736 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003737
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003738 public void testIsActivePasswordSufficient() throws Exception {
3739 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3740 mContext.packageName = admin1.getPackageName();
3741 setupDeviceOwner();
3742
3743 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3744 dpm.setPasswordMinimumLength(admin1, 8);
3745 dpm.setPasswordMinimumLetters(admin1, 6);
3746 dpm.setPasswordMinimumLowerCase(admin1, 3);
3747 dpm.setPasswordMinimumUpperCase(admin1, 1);
3748 dpm.setPasswordMinimumNonLetter(admin1, 1);
3749 dpm.setPasswordMinimumNumeric(admin1, 1);
3750 dpm.setPasswordMinimumSymbols(admin1, 0);
3751
3752 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3753 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3754 8, 2,
3755 6, 1,
3756 0, 1);
3757
3758 setActivePasswordState(passwordMetricsNoSymbols);
3759 assertTrue(dpm.isActivePasswordSufficient());
3760
3761 initializeDpms();
3762 reset(mContext.spiedContext);
3763 assertTrue(dpm.isActivePasswordSufficient());
3764
3765 // This call simulates the user entering the password for the first time after a reboot.
3766 // This causes password metrics to be reloaded into memory. Until this happens,
3767 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3768 // even if the DPC changes password requirements so that the password no longer meets the
3769 // requirements. This is a known limitation of the current implementation of
3770 // isActivePasswordSufficient() - see b/34218769.
3771 setActivePasswordState(passwordMetricsNoSymbols);
3772 assertTrue(dpm.isActivePasswordSufficient());
3773
3774 dpm.setPasswordMinimumSymbols(admin1, 1);
3775 // This assertion would fail if we had not called setActivePasswordState() again after
3776 // initializeDpms() - see previous comment.
3777 assertFalse(dpm.isActivePasswordSufficient());
3778
3779 initializeDpms();
3780 reset(mContext.spiedContext);
3781 assertFalse(dpm.isActivePasswordSufficient());
3782
3783 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3784 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3785 7, 2,
3786 5, 1,
3787 1, 2);
3788
3789 setActivePasswordState(passwordMetricsWithSymbols);
3790 assertTrue(dpm.isActivePasswordSufficient());
3791 }
3792
Pavel Grafov75c0a892017-05-18 17:28:27 +01003793 private void setActivePasswordState(PasswordMetrics passwordMetrics)
3794 throws Exception {
3795 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003796 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003797
Pavel Grafov75c0a892017-05-18 17:28:27 +01003798 dpm.setActivePasswordState(passwordMetrics, userHandle);
3799 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003800
Pavel Grafov75c0a892017-05-18 17:28:27 +01003801 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3802 intent.setComponent(admin1);
3803 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3804
3805 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3806 MockUtils.checkIntent(intent),
3807 MockUtils.checkUserHandle(userHandle));
3808
3809 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
3810 // let it finish with system uid, otherwise it will throw and crash.
3811 flushTasks();
3812
3813 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003814 }
3815
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003816 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3817 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3818 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3819 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3820 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3821 DpmMockContext.SYSTEM_UID);
3822 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3823 DpmMockContext.SYSTEM_UID);
3824
3825 // Set up a device owner.
3826 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003827 setupDeviceOwner();
3828
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003829 // First and second user set IMEs manually.
3830 mContext.binder.callingUid = firstUserSystemUid;
3831 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3832 mContext.binder.callingUid = secondUserSystemUid;
3833 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003834
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003835 // Device owner changes IME for first user.
3836 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003837 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003838 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003839 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003840 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003841 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003842 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003843 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3844 mContext.binder.callingUid = firstUserSystemUid;
3845 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3846 mContext.binder.callingUid = secondUserSystemUid;
3847 assertFalse(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 assertTrue(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 // First user changes IME manually.
3857 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3858 mContext.binder.callingUid = firstUserSystemUid;
3859 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3860 mContext.binder.callingUid = secondUserSystemUid;
3861 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003862
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003863 // Device owner changes IME for first user again.
3864 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003865 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003866 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003867 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003868 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003869 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003870 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3871 mContext.binder.callingUid = firstUserSystemUid;
3872 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3873 mContext.binder.callingUid = secondUserSystemUid;
3874 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003875
3876 // Restarting the DPMS should not lose information.
3877 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003878 mContext.binder.callingUid = firstUserSystemUid;
3879 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3880 mContext.binder.callingUid = secondUserSystemUid;
3881 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003882
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003883 // Device owner can find out whether it set the current IME itself.
3884 mContext.binder.callingUid = deviceOwnerUid;
3885 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003886
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003887 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003888 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003889 mContext.binder.callingUid = firstUserSystemUid;
3890 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3891 mContext.binder.callingUid = secondUserSystemUid;
3892 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003893 }
3894
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003895 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3896 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3897 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3898 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3899 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3900 DpmMockContext.SYSTEM_UID);
3901 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3902 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003903
3904 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003905 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003906 setupProfileOwner();
3907
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003908 // First and second user set IMEs manually.
3909 mContext.binder.callingUid = firstUserSystemUid;
3910 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3911 mContext.binder.callingUid = secondUserSystemUid;
3912 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003913
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003914 // Profile owner changes IME for second user.
3915 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003916 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003917 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003918 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003919 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003920 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003921 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003922 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3923 mContext.binder.callingUid = firstUserSystemUid;
3924 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3925 mContext.binder.callingUid = secondUserSystemUid;
3926 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003927
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003928 // First user changes IME manually.
3929 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3930 mContext.binder.callingUid = firstUserSystemUid;
3931 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3932 mContext.binder.callingUid = secondUserSystemUid;
3933 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003934
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003935 // Second user changes IME manually.
3936 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3937 mContext.binder.callingUid = firstUserSystemUid;
3938 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3939 mContext.binder.callingUid = secondUserSystemUid;
3940 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003941
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003942 // Profile owner changes IME for second user again.
3943 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003944 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003945 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003946 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01003947 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003948 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003949 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3950 mContext.binder.callingUid = firstUserSystemUid;
3951 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3952 mContext.binder.callingUid = secondUserSystemUid;
3953 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003954
3955 // Restarting the DPMS should not lose information.
3956 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003957 mContext.binder.callingUid = firstUserSystemUid;
3958 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3959 mContext.binder.callingUid = secondUserSystemUid;
3960 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003961
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003962 // Profile owner can find out whether it set the current IME itself.
3963 mContext.binder.callingUid = profileOwnerUid;
3964 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003965
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003966 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003967 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003968 mContext.binder.callingUid = firstUserSystemUid;
3969 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3970 mContext.binder.callingUid = secondUserSystemUid;
3971 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003972 }
Rubin Xuaab7a412016-12-30 21:13:29 +00003973
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01003974 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
3975 throws Exception {
3976 // Set up a device owner.
3977 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3978 setupDeviceOwner();
3979 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3980 }
3981
3982 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
3983 throws Exception {
3984 // Set up a profile owner.
3985 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3986 setupProfileOwner();
3987 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3988 }
3989
3990 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
3991 int adminUid) throws Exception {
3992 mContext.binder.callingUid = adminUid;
3993 final int userId = UserHandle.getUserId(adminUid);
3994
3995 final String packageName = "some.package";
3996 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
3997 admin1, Collections.singletonList(packageName)));
3998 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3999
4000 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4001 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4002
4003 // Attempt to set to empty list (which means no listener is whitelisted)
4004 mContext.binder.callingUid = adminUid;
4005 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004006 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004007 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4008
4009 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4010 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4011 }
4012
4013 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4014 // Set up a managed profile
4015 final int MANAGED_PROFILE_USER_ID = 15;
4016 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4017 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4018 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4019
4020 final String permittedListener = "some.package";
4021 setupPackageInPackageManager(
4022 permittedListener,
4023 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4024 /*appId=*/ 12345, /*flags=*/ 0);
4025
4026 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4027 admin1, Collections.singletonList(permittedListener)));
4028
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004029 // isNotificationListenerServicePermitted should throw if not called from System.
4030 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4031 () -> dpms.isNotificationListenerServicePermitted(
4032 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004033
4034 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4035 assertTrue(dpms.isNotificationListenerServicePermitted(
4036 permittedListener, MANAGED_PROFILE_USER_ID));
4037 }
4038
4039 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4040 throws Exception {
4041 // Set up a managed profile
4042 final int MANAGED_PROFILE_USER_ID = 15;
4043 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4044 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4045 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4046
4047 final String permittedListener = "permitted.package";
4048 int appId = 12345;
4049 setupPackageInPackageManager(
4050 permittedListener,
4051 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4052 appId, /*flags=*/ 0);
4053
4054 final String notPermittedListener = "not.permitted.package";
4055 setupPackageInPackageManager(
4056 notPermittedListener,
4057 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4058 ++appId, /*flags=*/ 0);
4059
4060 final String systemListener = "system.package";
4061 setupPackageInPackageManager(
4062 systemListener,
4063 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4064 ++appId, ApplicationInfo.FLAG_SYSTEM);
4065
4066 // By default all packages are allowed
4067 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4068
4069 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4070 assertTrue(dpms.isNotificationListenerServicePermitted(
4071 permittedListener, MANAGED_PROFILE_USER_ID));
4072 assertTrue(dpms.isNotificationListenerServicePermitted(
4073 notPermittedListener, MANAGED_PROFILE_USER_ID));
4074 assertTrue(dpms.isNotificationListenerServicePermitted(
4075 systemListener, MANAGED_PROFILE_USER_ID));
4076
4077 // Setting only one package in the whitelist
4078 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4079 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4080 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004081 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004082 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4083 assertEquals(1, permittedListeners.size());
4084 assertEquals(permittedListener, permittedListeners.get(0));
4085
4086 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4087 assertTrue(dpms.isNotificationListenerServicePermitted(
4088 permittedListener, MANAGED_PROFILE_USER_ID));
4089 assertFalse(dpms.isNotificationListenerServicePermitted(
4090 notPermittedListener, MANAGED_PROFILE_USER_ID));
4091 // System packages are always allowed (even if not in the whitelist)
4092 assertTrue(dpms.isNotificationListenerServicePermitted(
4093 systemListener, MANAGED_PROFILE_USER_ID));
4094
4095 // Setting an empty whitelist - only system listeners allowed
4096 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4097 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004098 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004099 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4100
4101 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4102 assertFalse(dpms.isNotificationListenerServicePermitted(
4103 permittedListener, MANAGED_PROFILE_USER_ID));
4104 assertFalse(dpms.isNotificationListenerServicePermitted(
4105 notPermittedListener, MANAGED_PROFILE_USER_ID));
4106 // System packages are always allowed (even if not in the whitelist)
4107 assertTrue(dpms.isNotificationListenerServicePermitted(
4108 systemListener, MANAGED_PROFILE_USER_ID));
4109
4110 // Setting a null whitelist - all listeners allowed
4111 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4112 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4113 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4114
4115 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4116 assertTrue(dpms.isNotificationListenerServicePermitted(
4117 permittedListener, MANAGED_PROFILE_USER_ID));
4118 assertTrue(dpms.isNotificationListenerServicePermitted(
4119 notPermittedListener, MANAGED_PROFILE_USER_ID));
4120 assertTrue(dpms.isNotificationListenerServicePermitted(
4121 systemListener, MANAGED_PROFILE_USER_ID));
4122 }
4123
4124 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4125 throws Exception {
4126 // Set up a managed profile
4127 final int MANAGED_PROFILE_USER_ID = 15;
4128 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4129 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4130 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4131
4132 final String nonSystemPackage = "non.system.package";
4133 int appId = 12345;
4134 setupPackageInPackageManager(
4135 nonSystemPackage,
4136 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4137 appId, /*flags=*/ 0);
4138
4139 final String systemListener = "system.package";
4140 setupPackageInPackageManager(
4141 systemListener,
4142 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4143 ++appId, ApplicationInfo.FLAG_SYSTEM);
4144
4145 // By default all packages are allowed (for all profiles)
4146 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4147
4148 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4149 assertTrue(dpms.isNotificationListenerServicePermitted(
4150 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4151 assertTrue(dpms.isNotificationListenerServicePermitted(
4152 systemListener, MANAGED_PROFILE_USER_ID));
4153 assertTrue(dpms.isNotificationListenerServicePermitted(
4154 nonSystemPackage, UserHandle.USER_SYSTEM));
4155 assertTrue(dpms.isNotificationListenerServicePermitted(
4156 systemListener, UserHandle.USER_SYSTEM));
4157
4158 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4159 // all allowed in primary profile
4160 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4161 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004162 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004163 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4164
4165 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4166 assertFalse(dpms.isNotificationListenerServicePermitted(
4167 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4168 assertTrue(dpms.isNotificationListenerServicePermitted(
4169 systemListener, MANAGED_PROFILE_USER_ID));
4170 assertTrue(dpms.isNotificationListenerServicePermitted(
4171 nonSystemPackage, UserHandle.USER_SYSTEM));
4172 assertTrue(dpms.isNotificationListenerServicePermitted(
4173 systemListener, UserHandle.USER_SYSTEM));
4174 }
4175
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004176 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004177 mServiceContext.packageName = mRealTestContext.getPackageName();
4178 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4179 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004180 setDeviceOwner();
4181
Pavel Grafov75c0a892017-05-18 17:28:27 +01004182 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004183 }
4184
4185 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004186 mServiceContext.packageName = mRealTestContext.getPackageName();
4187 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4188 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004189 setAsProfileOwner(admin1);
4190
Pavel Grafov75c0a892017-05-18 17:28:27 +01004191 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4192 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004193 }
4194
4195 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004196 mServiceContext.packageName = mRealTestContext.getPackageName();
4197 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4198 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004199 setAsProfileOwner(admin1);
4200
Pavel Grafov75c0a892017-05-18 17:28:27 +01004201 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4202 caller.packageName = "com.example.delegate";
4203 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4204 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004205
Pavel Grafov75c0a892017-05-18 17:28:27 +01004206 // Make caller a delegated cert installer.
4207 runAsCaller(mAdmin1Context, dpms,
4208 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004209
4210 verifyCanGetOwnerInstalledCaCerts(null, caller);
4211 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004212 }
4213
Robin Lee2c68dad2017-03-17 12:50:24 +00004214 private void verifyCanGetOwnerInstalledCaCerts(
4215 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004216 final String alias = "cert";
4217 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004218
4219 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004220 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004221 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4222 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004223 }
4224 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4225
4226 // caller: device admin or delegated certificate installer
4227 callerContext.applicationInfo = new ApplicationInfo();
4228 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4229
4230 // system_server
4231 final DpmMockContext serviceContext = mContext;
4232 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004233 getServices().addPackageContext(callerUser, admin1Context);
4234 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004235
4236 // Install a CA cert.
4237 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004238 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004239 .thenReturn(alias);
4240 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004241 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004242 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004243 });
4244
Pavel Grafov75c0a892017-05-18 17:28:27 +01004245 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4246 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4247 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004248 flushTasks();
4249
Robin Lee2c68dad2017-03-17 12:50:24 +00004250 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4251
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004252 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004253 runAsCaller(admin1Context, dpms, (dpm) -> {
4254 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004255 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004256 ownerInstalledCaCerts.addAll(installedCaCerts);
4257 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004258
4259 // Restarting the DPMS should not lose information.
4260 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004261 runAsCaller(admin1Context, dpms, (dpm) ->
4262 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004263
4264 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004265 runAsCaller(serviceContext, dpms, (dpm) -> {
4266 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004267
Robin Lee2c68dad2017-03-17 12:50:24 +00004268 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004269 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004270 });
4271
Pavel Grafov75c0a892017-05-18 17:28:27 +01004272 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4273 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4274 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004275 flushTasks();
4276
4277 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4278 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004279 runAsCaller(admin1Context, dpms, (dpm) -> {
4280 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4281 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004282 }
4283
Robin Lee2c68dad2017-03-17 12:50:24 +00004284 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4285 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004286 final String alias = "cert";
4287 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004288
4289 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004290 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004291 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4292 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004293 }
4294 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4295
4296 // caller: device admin or delegated certificate installer
4297 callerContext.applicationInfo = new ApplicationInfo();
4298 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4299
4300 // system_server
4301 final DpmMockContext serviceContext = mContext;
4302 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004303 getServices().addPackageContext(callerUser, admin1Context);
4304 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004305
4306 // Install a CA cert as caller
4307 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004308 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004309 .thenReturn(alias);
4310 assertTrue(dpm.installCaCert(callerName, caCert));
4311 });
4312
4313 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004314 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004315 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004316 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4317 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4318 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004319 flushTasks();
4320
Robin Lee2c68dad2017-03-17 12:50:24 +00004321 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004322 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004323
4324 runAsCaller(serviceContext, dpms, (dpm) -> {
4325 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4326 assertNotNull(ownerInstalledCaCerts);
4327 assertTrue(ownerInstalledCaCerts.isEmpty());
4328 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004329 }
4330
Victor Chang3e794af2016-03-04 13:48:17 +00004331 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004332 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004333 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4334 dpms.notifyChangeToContentObserver(
4335 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4336 }
4337
4338 private void assertProvisioningAllowed(String action, boolean expected) {
4339 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4340 dpm.isProvisioningAllowed(action));
4341 }
Tony Mak2f26b792016-11-28 17:54:51 +00004342
Nicolas Prevot45d29072017-01-18 16:11:19 +00004343 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4344 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004345 final String previousPackageName = mContext.packageName;
4346 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004347
4348 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4349 mContext.packageName = packageName;
4350 mMockContext.binder.callingUid = uid;
4351 assertProvisioningAllowed(action, expected);
4352
4353 // Set the previous package name / calling uid to go back to the initial state.
4354 mContext.packageName = previousPackageName;
4355 mMockContext.binder.callingUid = previousUid;
4356 }
4357
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004358 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004359 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4360 }
4361
4362 private void assertCheckProvisioningPreCondition(
4363 String action, String packageName, int provisioningCondition) {
4364 assertEquals("checkProvisioningPreCondition("
4365 + action + ", " + packageName + ") returning unexpected result",
4366 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004367 }
4368
Tony Mak2f26b792016-11-28 17:54:51 +00004369 /**
4370 * Setup a managed profile with the specified admin and its uid.
4371 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4372 * @param adminUid uid of the admin package.
4373 * @param copyFromAdmin package information for {@code admin} will be built based on this
4374 * component's information.
4375 */
4376 private void addManagedProfile(
4377 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4378 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004379 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004380 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4381 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4382 dpm.setActiveAdmin(admin, false, userId);
4383 assertTrue(dpm.setProfileOwner(admin, null, userId));
4384 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4385 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004386
4387 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004388 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004389 */
Robin Leeabaa0692017-02-20 20:54:22 +00004390 private static StringParceledListSlice asSlice(String[] s) {
4391 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004392 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004393
4394 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004395 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4396 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004397
Robin Lee2c68dad2017-03-17 12:50:24 +00004398 // We can't let exceptions happen on the background thread. Throw them here if they happen
4399 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004400 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004401 }
Victor Chang3e794af2016-03-04 13:48:17 +00004402}